target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test @Ignore public void extractTableModelFromClasses() throws Exception { TableModelExtractor.extractTableModelFromClasses(Paths.get("D:\\redg\\redg-playground\\target\\test-classes"), "com.btc.redg.generated", "G"); }
public static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { LOG.debug("Starting table model extraction from compiled class files..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = classDir.resolve(packageNameAsFolders); LOG.debug("Folder with class files is {}", codeFilePath.toAbsolutePath().toString()); final List<String> classNames = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.class")) .map(classDir::relativize) .map(Path::toString) .map(name -> name.replaceFirst("\\.class$", "")) .map(name -> name.replaceAll("(/|\\\\)", ".")) .collect(Collectors.toList()); LOG.debug("Found following class files:\n{}", classNames.stream().collect(Collectors.joining("\n"))); LOG.debug("Loading all found classes..."); final ClassLoader cl = new URLClassLoader(new URL[]{classDir.toUri().toURL()}); for (String className : classNames) { LOG.debug("Loading class {}.", className); final Class cls = cl.loadClass(className); final Method m = cls.getDeclaredMethod("getTableModel"); results.add((TableModel) m.invoke(null)); LOG.debug("Successfully extracted table model."); } return results; }
TableModelExtractor { public static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { LOG.debug("Starting table model extraction from compiled class files..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = classDir.resolve(packageNameAsFolders); LOG.debug("Folder with class files is {}", codeFilePath.toAbsolutePath().toString()); final List<String> classNames = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.class")) .map(classDir::relativize) .map(Path::toString) .map(name -> name.replaceFirst("\\.class$", "")) .map(name -> name.replaceAll("(/|\\\\)", ".")) .collect(Collectors.toList()); LOG.debug("Found following class files:\n{}", classNames.stream().collect(Collectors.joining("\n"))); LOG.debug("Loading all found classes..."); final ClassLoader cl = new URLClassLoader(new URL[]{classDir.toUri().toURL()}); for (String className : classNames) { LOG.debug("Loading class {}.", className); final Class cls = cl.loadClass(className); final Method m = cls.getDeclaredMethod("getTableModel"); results.add((TableModel) m.invoke(null)); LOG.debug("Successfully extracted table model."); } return results; } }
TableModelExtractor { public static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { LOG.debug("Starting table model extraction from compiled class files..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = classDir.resolve(packageNameAsFolders); LOG.debug("Folder with class files is {}", codeFilePath.toAbsolutePath().toString()); final List<String> classNames = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.class")) .map(classDir::relativize) .map(Path::toString) .map(name -> name.replaceFirst("\\.class$", "")) .map(name -> name.replaceAll("(/|\\\\)", ".")) .collect(Collectors.toList()); LOG.debug("Found following class files:\n{}", classNames.stream().collect(Collectors.joining("\n"))); LOG.debug("Loading all found classes..."); final ClassLoader cl = new URLClassLoader(new URL[]{classDir.toUri().toURL()}); for (String className : classNames) { LOG.debug("Loading class {}.", className); final Class cls = cl.loadClass(className); final Method m = cls.getDeclaredMethod("getTableModel"); results.add((TableModel) m.invoke(null)); LOG.debug("Successfully extracted table model."); } return results; } }
TableModelExtractor { public static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { LOG.debug("Starting table model extraction from compiled class files..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = classDir.resolve(packageNameAsFolders); LOG.debug("Folder with class files is {}", codeFilePath.toAbsolutePath().toString()); final List<String> classNames = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.class")) .map(classDir::relativize) .map(Path::toString) .map(name -> name.replaceFirst("\\.class$", "")) .map(name -> name.replaceAll("(/|\\\\)", ".")) .collect(Collectors.toList()); LOG.debug("Found following class files:\n{}", classNames.stream().collect(Collectors.joining("\n"))); LOG.debug("Loading all found classes..."); final ClassLoader cl = new URLClassLoader(new URL[]{classDir.toUri().toURL()}); for (String className : classNames) { LOG.debug("Loading class {}.", className); final Class cls = cl.loadClass(className); final Method m = cls.getDeclaredMethod("getTableModel"); results.add((TableModel) m.invoke(null)); LOG.debug("Successfully extracted table model."); } return results; } static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix); static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix); }
TableModelExtractor { public static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { LOG.debug("Starting table model extraction from compiled class files..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = classDir.resolve(packageNameAsFolders); LOG.debug("Folder with class files is {}", codeFilePath.toAbsolutePath().toString()); final List<String> classNames = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.class")) .map(classDir::relativize) .map(Path::toString) .map(name -> name.replaceFirst("\\.class$", "")) .map(name -> name.replaceAll("(/|\\\\)", ".")) .collect(Collectors.toList()); LOG.debug("Found following class files:\n{}", classNames.stream().collect(Collectors.joining("\n"))); LOG.debug("Loading all found classes..."); final ClassLoader cl = new URLClassLoader(new URL[]{classDir.toUri().toURL()}); for (String className : classNames) { LOG.debug("Loading class {}.", className); final Class cls = cl.loadClass(className); final Method m = cls.getDeclaredMethod("getTableModel"); results.add((TableModel) m.invoke(null)); LOG.debug("Successfully extracted table model."); } return results; } static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix); static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix); }
@Test public void testGetDataTypeBySqlName() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setDefaultTypeMappings(Arrays.asList( new DefaultTypeMapping("DECIMAL", "java.lang.Long"), new DefaultTypeMapping("DECIMAL(1)", "java.lang.Boolean"), new DefaultTypeMapping(" TIMESTAMP WITH TIME ZONE ( 30 , 0 ) ", "java.sql.Timestamp") )); ColumnDataType cdt = Mockito.mock(ColumnDataType.class); when(cdt.getName()).thenReturn("DECIMAL"); Column column1 = Mockito.mock(Column.class); when(column1.getColumnDataType()).thenReturn(cdt); when(column1.getSize()).thenReturn(1); when(column1.getDecimalDigits()).thenReturn(0); Column column2 = Mockito.mock(Column.class); when(column2.getColumnDataType()).thenReturn(cdt); when(column2.getSize()).thenReturn(10); when(column2.getDecimalDigits()).thenReturn(0); ColumnDataType timestampWithTimeZoneDataType = Mockito.mock(ColumnDataType.class); when(timestampWithTimeZoneDataType.getName()).thenReturn("TIMESTAMP WITH TIME ZONE"); Column column3 = Mockito.mock(Column.class); when(column3.getColumnDataType()).thenReturn(timestampWithTimeZoneDataType); when(column3.getSize()).thenReturn(30); when(column3.getDecimalDigits()).thenReturn(0); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEquals("java.lang.Boolean", dataTypeProvider.getDataTypeBySqlType(column1)); Assert.assertEquals("java.lang.Long", dataTypeProvider.getDataTypeBySqlType(column2)); Assert.assertEquals("java.sql.Timestamp", dataTypeProvider.getDataTypeBySqlType(column3)); }
String getDataTypeBySqlType(final Column column) { if (typeMappings.getDefaultTypeMappings() == null) { return null; } List<String> variants = DataTypePrecisionHelper.getDataTypeWithAllPrecisionVariants(column); return variants.stream() .map(variant -> typeMappings.getDefaultTypeMappings().stream() .filter(dtm -> dtm.getSqlType() .trim() .replaceAll("\\s+", " ") .replaceAll("\\s+(?=[(),])", "") .replaceAll("(?<=[(),])\\s+", "") .toUpperCase().equals(variant.toUpperCase())) .findFirst().orElse(null)) .filter(Objects::nonNull) .map(DefaultTypeMapping::getJavaType) .findFirst().orElse(null); }
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeBySqlType(final Column column) { if (typeMappings.getDefaultTypeMappings() == null) { return null; } List<String> variants = DataTypePrecisionHelper.getDataTypeWithAllPrecisionVariants(column); return variants.stream() .map(variant -> typeMappings.getDefaultTypeMappings().stream() .filter(dtm -> dtm.getSqlType() .trim() .replaceAll("\\s+", " ") .replaceAll("\\s+(?=[(),])", "") .replaceAll("(?<=[(),])\\s+", "") .toUpperCase().equals(variant.toUpperCase())) .findFirst().orElse(null)) .filter(Objects::nonNull) .map(DefaultTypeMapping::getJavaType) .findFirst().orElse(null); } }
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeBySqlType(final Column column) { if (typeMappings.getDefaultTypeMappings() == null) { return null; } List<String> variants = DataTypePrecisionHelper.getDataTypeWithAllPrecisionVariants(column); return variants.stream() .map(variant -> typeMappings.getDefaultTypeMappings().stream() .filter(dtm -> dtm.getSqlType() .trim() .replaceAll("\\s+", " ") .replaceAll("\\s+(?=[(),])", "") .replaceAll("(?<=[(),])\\s+", "") .toUpperCase().equals(variant.toUpperCase())) .findFirst().orElse(null)) .filter(Objects::nonNull) .map(DefaultTypeMapping::getJavaType) .findFirst().orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); }
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeBySqlType(final Column column) { if (typeMappings.getDefaultTypeMappings() == null) { return null; } List<String> variants = DataTypePrecisionHelper.getDataTypeWithAllPrecisionVariants(column); return variants.stream() .map(variant -> typeMappings.getDefaultTypeMappings().stream() .filter(dtm -> dtm.getSqlType() .trim() .replaceAll("\\s+", " ") .replaceAll("\\s+(?=[(),])", "") .replaceAll("(?<=[(),])\\s+", "") .toUpperCase().equals(variant.toUpperCase())) .findFirst().orElse(null)) .filter(Objects::nonNull) .map(DefaultTypeMapping::getJavaType) .findFirst().orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeBySqlType(final Column column) { if (typeMappings.getDefaultTypeMappings() == null) { return null; } List<String> variants = DataTypePrecisionHelper.getDataTypeWithAllPrecisionVariants(column); return variants.stream() .map(variant -> typeMappings.getDefaultTypeMappings().stream() .filter(dtm -> dtm.getSqlType() .trim() .replaceAll("\\s+", " ") .replaceAll("\\s+(?=[(),])", "") .replaceAll("(?<=[(),])\\s+", "") .toUpperCase().equals(variant.toUpperCase())) .findFirst().orElse(null)) .filter(Objects::nonNull) .map(DefaultTypeMapping::getJavaType) .findFirst().orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
@Test public void testCanHandleMissingTableTypeMappings() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setDefaultTypeMappings(Collections.emptyList()); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEquals("java.lang.Integer", dataTypeProvider.getCanonicalDataTypeName(createColumnMock())); }
@Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); }
XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } }
XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); }
XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
@Test public void testCanHandleMissingDefaultTypeMappings() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setTableTypeMappings(Collections.emptyList()); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEquals("java.lang.Integer", dataTypeProvider.getCanonicalDataTypeName(createColumnMock())); }
@Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); }
XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } }
XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); }
XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
@Test public void getDataTypeBoolean() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "boolean"); Assert.assertEquals("java.lang.Boolean", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void getDataTypeCharacter() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "char"); Assert.assertEquals("java.lang.Character", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void getDataTypeByte() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "byte"); Assert.assertEquals("java.lang.Byte", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void getDataTypeShort() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "short"); Assert.assertEquals("java.lang.Short", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void getDataTypeInteger() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "int"); Assert.assertEquals("java.lang.Integer", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void getDataTypeLong() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "long"); Assert.assertEquals("java.lang.Long", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void testGetMethodNameForColumnJoined() throws Exception { Assert.assertEquals("superJoinedImpliciteNameColumn", provider.getMethodNameForColumn(getColumn("MANAGEDSUPERCLASSJOINED", "SUPERJOINEDIMPLICITENAMECOLUMN"))); Assert.assertEquals("superJoinedExpliciteNameColumn", provider.getMethodNameForColumn(getColumn("MANAGEDSUPERCLASSJOINED", "SUPER_JOINED_EXPLICIT_NAME_COLUMN"))); Assert.assertEquals("subJoinedImpliciteNameColumn", provider.getMethodNameForColumn(getColumn("SUB_ENTITY_JOINED_1", "SUBJOINEDIMPLICITENAMECOLUMN"))); Assert.assertEquals("subJoinedExpliciteNameColumn", provider.getMethodNameForColumn(getColumn("SUB_ENTITY_JOINED_1", "SUB_JOINED_EXPLICITE_NAME_COLUMN"))); Assert.assertEquals("subEntityJoined2Attribute", provider.getMethodNameForColumn(getColumn("SUBENTITY_JOINED_2", "SUBENTITYJOINED2ATTRIBUTE"))); }
@Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
@Test public void getDataTypeFloat() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "float"); Assert.assertEquals("java.lang.Float", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void getDataTypeDouble() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "double"); Assert.assertEquals("java.lang.Double", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void getDataTypeNonPrimitiveType() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "java.lang.Double"); Assert.assertEquals("java.lang.Double", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
NoPrimitiveTypesDataTypeProviderWrapper implements DataTypeProvider { @Override public String getCanonicalDataTypeName(Column column) { String dataTypeName = originalDataTypeProvider.getCanonicalDataTypeName(column); return OBJECT_TYPE_BY_PRIMITIVE_TYPE.keySet().contains(dataTypeName) ? OBJECT_TYPE_BY_PRIMITIVE_TYPE.get(dataTypeName).getCanonicalName() : dataTypeName; } NoPrimitiveTypesDataTypeProviderWrapper(DataTypeProvider originalDataTypeProvider); @Override String getCanonicalDataTypeName(Column column); }
@Test public void testForeignKeyExtraction() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-fe", "", ""); assertNotNull(connection); File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Catalog db = DatabaseManager.crawlDatabase(connection, new IncludeAll(), new IncludeAll()); assertNotNull(db); Schema s = db.lookupSchema("\"RT-FE\".PUBLIC").orElse(null); assertNotNull(s); Table t = db.lookupTable(s, "DEMO_USER").orElse(null); assertNotNull(t); assertEquals(1, t.getImportedForeignKeys().size()); ForeignKey fk = (ForeignKey) t.getImportedForeignKeys().toArray()[0]; assertNotNull(fk); ForeignKeyExtractor extractor = new ForeignKeyExtractor(new DefaultDataTypeProvider(), new DefaultNameProvider(), new DefaultExplicitAttributeDecider(),"My"); ForeignKeyModel model = extractor.extractForeignKeyModel(fk); assertEquals("MyDemoCompany", model.getJavaTypeName()); assertEquals("worksAtDemoCompany", model.getName()); assertEquals(1, model.getReferences().size()); assertTrue(model.getReferences().containsKey("WORKS_AT")); ForeignKeyColumnModel columnModel = model.getReferences().get("WORKS_AT"); assertEquals("id", columnModel.getPrimaryKeyAttributeName()); assertEquals("worksAt", columnModel.getLocalName()); assertEquals("java.math.BigDecimal", columnModel.getLocalType()); assertEquals("WORKS_AT", columnModel.getDbName()); assertEquals("DEMO_USER", columnModel.getDbTableName()); }
public ForeignKeyModel extractForeignKeyModel(final ForeignKey foreignKey) { LOG.debug("Extracting model for foreign key {}", foreignKey.getName()); final ForeignKeyModel model = new ForeignKeyModel(); final Table targetTable = foreignKey.getColumnReferences().get(0).getPrimaryKeyColumn().getParent(); final Table originTable = foreignKey.getColumnReferences().get(0).getForeignKeyColumn().getParent(); try { targetTable.hasPrimaryKey(); } catch (NotLoadedException e) { LOG.error("Foreign key reference on an excluded table {}. Cannot generate valid java code.", targetTable.getFullName()); throw new RedGGenerationException("Referenced foreign key is in an excluded table: " + targetTable.getFullName()); } model.setJavaTypeName(this.classPrefix + this.nameProvider.getClassNameForTable(targetTable)); model.setName(this.nameProvider.getMethodNameForReference(foreignKey)); model.setNotNull(foreignKey.getColumnReferences().stream().noneMatch(x -> x.getForeignKeyColumn().isNullable()) || explicitAttributeDecider.isExplicitForeignKey(foreignKey)); for (final ColumnReference reference : foreignKey.getColumnReferences()) { LOG.debug("{}: {} -> {}", foreignKey.getName(), reference.getForeignKeyColumn().getName(), reference.getPrimaryKeyColumn().getName()); final ForeignKeyColumnModel columnModel = new ForeignKeyColumnModel(); columnModel.setPrimaryKeyAttributeName(this.nameProvider.getMethodNameForColumn(reference.getPrimaryKeyColumn())); columnModel.setLocalName(this.nameProvider.getMethodNameForForeignKeyColumn(foreignKey, reference.getPrimaryKeyColumn(), reference.getForeignKeyColumn())); columnModel.setLocalType(dataTypeProvider.getCanonicalDataTypeName(reference.getForeignKeyColumn())); columnModel.setSqlType(reference.getForeignKeyColumn().getColumnDataType().getName()); columnModel.setSqlTypeInt(reference.getForeignKeyColumn().getColumnDataType().getJavaSqlType().getVendorTypeNumber()); columnModel.setDbName(reference.getForeignKeyColumn().getName()); columnModel.setDbTableName(originTable.getName()); columnModel.setDbFullTableName(originTable.getFullName()); model.getReferences().put(reference.getForeignKeyColumn().getName(), columnModel); } return model; }
ForeignKeyExtractor { public ForeignKeyModel extractForeignKeyModel(final ForeignKey foreignKey) { LOG.debug("Extracting model for foreign key {}", foreignKey.getName()); final ForeignKeyModel model = new ForeignKeyModel(); final Table targetTable = foreignKey.getColumnReferences().get(0).getPrimaryKeyColumn().getParent(); final Table originTable = foreignKey.getColumnReferences().get(0).getForeignKeyColumn().getParent(); try { targetTable.hasPrimaryKey(); } catch (NotLoadedException e) { LOG.error("Foreign key reference on an excluded table {}. Cannot generate valid java code.", targetTable.getFullName()); throw new RedGGenerationException("Referenced foreign key is in an excluded table: " + targetTable.getFullName()); } model.setJavaTypeName(this.classPrefix + this.nameProvider.getClassNameForTable(targetTable)); model.setName(this.nameProvider.getMethodNameForReference(foreignKey)); model.setNotNull(foreignKey.getColumnReferences().stream().noneMatch(x -> x.getForeignKeyColumn().isNullable()) || explicitAttributeDecider.isExplicitForeignKey(foreignKey)); for (final ColumnReference reference : foreignKey.getColumnReferences()) { LOG.debug("{}: {} -> {}", foreignKey.getName(), reference.getForeignKeyColumn().getName(), reference.getPrimaryKeyColumn().getName()); final ForeignKeyColumnModel columnModel = new ForeignKeyColumnModel(); columnModel.setPrimaryKeyAttributeName(this.nameProvider.getMethodNameForColumn(reference.getPrimaryKeyColumn())); columnModel.setLocalName(this.nameProvider.getMethodNameForForeignKeyColumn(foreignKey, reference.getPrimaryKeyColumn(), reference.getForeignKeyColumn())); columnModel.setLocalType(dataTypeProvider.getCanonicalDataTypeName(reference.getForeignKeyColumn())); columnModel.setSqlType(reference.getForeignKeyColumn().getColumnDataType().getName()); columnModel.setSqlTypeInt(reference.getForeignKeyColumn().getColumnDataType().getJavaSqlType().getVendorTypeNumber()); columnModel.setDbName(reference.getForeignKeyColumn().getName()); columnModel.setDbTableName(originTable.getName()); columnModel.setDbFullTableName(originTable.getFullName()); model.getReferences().put(reference.getForeignKeyColumn().getName(), columnModel); } return model; } }
ForeignKeyExtractor { public ForeignKeyModel extractForeignKeyModel(final ForeignKey foreignKey) { LOG.debug("Extracting model for foreign key {}", foreignKey.getName()); final ForeignKeyModel model = new ForeignKeyModel(); final Table targetTable = foreignKey.getColumnReferences().get(0).getPrimaryKeyColumn().getParent(); final Table originTable = foreignKey.getColumnReferences().get(0).getForeignKeyColumn().getParent(); try { targetTable.hasPrimaryKey(); } catch (NotLoadedException e) { LOG.error("Foreign key reference on an excluded table {}. Cannot generate valid java code.", targetTable.getFullName()); throw new RedGGenerationException("Referenced foreign key is in an excluded table: " + targetTable.getFullName()); } model.setJavaTypeName(this.classPrefix + this.nameProvider.getClassNameForTable(targetTable)); model.setName(this.nameProvider.getMethodNameForReference(foreignKey)); model.setNotNull(foreignKey.getColumnReferences().stream().noneMatch(x -> x.getForeignKeyColumn().isNullable()) || explicitAttributeDecider.isExplicitForeignKey(foreignKey)); for (final ColumnReference reference : foreignKey.getColumnReferences()) { LOG.debug("{}: {} -> {}", foreignKey.getName(), reference.getForeignKeyColumn().getName(), reference.getPrimaryKeyColumn().getName()); final ForeignKeyColumnModel columnModel = new ForeignKeyColumnModel(); columnModel.setPrimaryKeyAttributeName(this.nameProvider.getMethodNameForColumn(reference.getPrimaryKeyColumn())); columnModel.setLocalName(this.nameProvider.getMethodNameForForeignKeyColumn(foreignKey, reference.getPrimaryKeyColumn(), reference.getForeignKeyColumn())); columnModel.setLocalType(dataTypeProvider.getCanonicalDataTypeName(reference.getForeignKeyColumn())); columnModel.setSqlType(reference.getForeignKeyColumn().getColumnDataType().getName()); columnModel.setSqlTypeInt(reference.getForeignKeyColumn().getColumnDataType().getJavaSqlType().getVendorTypeNumber()); columnModel.setDbName(reference.getForeignKeyColumn().getName()); columnModel.setDbTableName(originTable.getName()); columnModel.setDbFullTableName(originTable.getFullName()); model.getReferences().put(reference.getForeignKeyColumn().getName(), columnModel); } return model; } ForeignKeyExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final String classPrefix); }
ForeignKeyExtractor { public ForeignKeyModel extractForeignKeyModel(final ForeignKey foreignKey) { LOG.debug("Extracting model for foreign key {}", foreignKey.getName()); final ForeignKeyModel model = new ForeignKeyModel(); final Table targetTable = foreignKey.getColumnReferences().get(0).getPrimaryKeyColumn().getParent(); final Table originTable = foreignKey.getColumnReferences().get(0).getForeignKeyColumn().getParent(); try { targetTable.hasPrimaryKey(); } catch (NotLoadedException e) { LOG.error("Foreign key reference on an excluded table {}. Cannot generate valid java code.", targetTable.getFullName()); throw new RedGGenerationException("Referenced foreign key is in an excluded table: " + targetTable.getFullName()); } model.setJavaTypeName(this.classPrefix + this.nameProvider.getClassNameForTable(targetTable)); model.setName(this.nameProvider.getMethodNameForReference(foreignKey)); model.setNotNull(foreignKey.getColumnReferences().stream().noneMatch(x -> x.getForeignKeyColumn().isNullable()) || explicitAttributeDecider.isExplicitForeignKey(foreignKey)); for (final ColumnReference reference : foreignKey.getColumnReferences()) { LOG.debug("{}: {} -> {}", foreignKey.getName(), reference.getForeignKeyColumn().getName(), reference.getPrimaryKeyColumn().getName()); final ForeignKeyColumnModel columnModel = new ForeignKeyColumnModel(); columnModel.setPrimaryKeyAttributeName(this.nameProvider.getMethodNameForColumn(reference.getPrimaryKeyColumn())); columnModel.setLocalName(this.nameProvider.getMethodNameForForeignKeyColumn(foreignKey, reference.getPrimaryKeyColumn(), reference.getForeignKeyColumn())); columnModel.setLocalType(dataTypeProvider.getCanonicalDataTypeName(reference.getForeignKeyColumn())); columnModel.setSqlType(reference.getForeignKeyColumn().getColumnDataType().getName()); columnModel.setSqlTypeInt(reference.getForeignKeyColumn().getColumnDataType().getJavaSqlType().getVendorTypeNumber()); columnModel.setDbName(reference.getForeignKeyColumn().getName()); columnModel.setDbTableName(originTable.getName()); columnModel.setDbFullTableName(originTable.getFullName()); model.getReferences().put(reference.getForeignKeyColumn().getName(), columnModel); } return model; } ForeignKeyExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final String classPrefix); ForeignKeyModel extractForeignKeyModel(final ForeignKey foreignKey); IncomingForeignKeyModel extractIncomingForeignKeyModel(final ForeignKey foreignKey); }
ForeignKeyExtractor { public ForeignKeyModel extractForeignKeyModel(final ForeignKey foreignKey) { LOG.debug("Extracting model for foreign key {}", foreignKey.getName()); final ForeignKeyModel model = new ForeignKeyModel(); final Table targetTable = foreignKey.getColumnReferences().get(0).getPrimaryKeyColumn().getParent(); final Table originTable = foreignKey.getColumnReferences().get(0).getForeignKeyColumn().getParent(); try { targetTable.hasPrimaryKey(); } catch (NotLoadedException e) { LOG.error("Foreign key reference on an excluded table {}. Cannot generate valid java code.", targetTable.getFullName()); throw new RedGGenerationException("Referenced foreign key is in an excluded table: " + targetTable.getFullName()); } model.setJavaTypeName(this.classPrefix + this.nameProvider.getClassNameForTable(targetTable)); model.setName(this.nameProvider.getMethodNameForReference(foreignKey)); model.setNotNull(foreignKey.getColumnReferences().stream().noneMatch(x -> x.getForeignKeyColumn().isNullable()) || explicitAttributeDecider.isExplicitForeignKey(foreignKey)); for (final ColumnReference reference : foreignKey.getColumnReferences()) { LOG.debug("{}: {} -> {}", foreignKey.getName(), reference.getForeignKeyColumn().getName(), reference.getPrimaryKeyColumn().getName()); final ForeignKeyColumnModel columnModel = new ForeignKeyColumnModel(); columnModel.setPrimaryKeyAttributeName(this.nameProvider.getMethodNameForColumn(reference.getPrimaryKeyColumn())); columnModel.setLocalName(this.nameProvider.getMethodNameForForeignKeyColumn(foreignKey, reference.getPrimaryKeyColumn(), reference.getForeignKeyColumn())); columnModel.setLocalType(dataTypeProvider.getCanonicalDataTypeName(reference.getForeignKeyColumn())); columnModel.setSqlType(reference.getForeignKeyColumn().getColumnDataType().getName()); columnModel.setSqlTypeInt(reference.getForeignKeyColumn().getColumnDataType().getJavaSqlType().getVendorTypeNumber()); columnModel.setDbName(reference.getForeignKeyColumn().getName()); columnModel.setDbTableName(originTable.getName()); columnModel.setDbFullTableName(originTable.getFullName()); model.getReferences().put(reference.getForeignKeyColumn().getName(), columnModel); } return model; } ForeignKeyExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final String classPrefix); ForeignKeyModel extractForeignKeyModel(final ForeignKey foreignKey); IncomingForeignKeyModel extractIncomingForeignKeyModel(final ForeignKey foreignKey); }
@Test public void testExtractTable() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-te", "", ""); assertNotNull(connection); File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Catalog db = DatabaseManager.crawlDatabase(connection, new IncludeAll(), new IncludeAll()); assertNotNull(db); Schema s = db.lookupSchema("\"RT-TE\".PUBLIC").orElse(null); assertNotNull(s); Table t = db.lookupTable(s, "DEMO_USER").orElse(null); assertNotNull(t); TableExtractor extractor = new TableExtractor("My", "com.demo.pkg", null, null, null, null); TableModel model = extractor.extractTableModel(t); assertNotNull(model); assertEquals("MyDemoUser", model.getClassName()); assertEquals("DemoUser", model.getName()); assertEquals("com.demo.pkg", model.getPackageName()); assertEquals("DEMO_USER", model.getSqlName()); assertEquals(1, model.getForeignKeys().size()); assertEquals(7, model.getColumns().size()); assertEquals(6, model.getNonForeignKeyColumns().size()); assertTrue(model.hasColumnsAndForeignKeys()); }
public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; }
TableExtractor { public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; } }
TableExtractor { public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; } TableExtractor(); TableExtractor(final String classPrefix, final String targetPackage, DataTypeProvider dataTypeProvider, final NameProvider nameProvider, ExplicitAttributeDecider explicitAttributeDecider, ConvenienceSetterProvider convenienceSetterProvider); }
TableExtractor { public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; } TableExtractor(); TableExtractor(final String classPrefix, final String targetPackage, DataTypeProvider dataTypeProvider, final NameProvider nameProvider, ExplicitAttributeDecider explicitAttributeDecider, ConvenienceSetterProvider convenienceSetterProvider); TableModel extractTableModel(final Table table); static boolean isJoinTable(final Table table); static Map<String, Map<Table, List<String>>> analyzeJoinTable(Table table); }
TableExtractor { public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; } TableExtractor(); TableExtractor(final String classPrefix, final String targetPackage, DataTypeProvider dataTypeProvider, final NameProvider nameProvider, ExplicitAttributeDecider explicitAttributeDecider, ConvenienceSetterProvider convenienceSetterProvider); TableModel extractTableModel(final Table table); static boolean isJoinTable(final Table table); static Map<String, Map<Table, List<String>>> analyzeJoinTable(Table table); static final String DEFAULT_CLASS_PREFIX; static final String DEFAULT_TARGET_PACKAGE; }
@Test public void testExtractTableCompositeForeignKey() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-te", "", ""); assertNotNull(connection); File tempFile = Helpers.getResourceAsFile("codegenerator/test-exchange-rate.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Catalog db = DatabaseManager.crawlDatabase(connection, new IncludeAll(), new IncludeAll()); assertNotNull(db); Schema s = db.lookupSchema("\"RT-TE\".PUBLIC").orElse(null); assertNotNull(s); Table exchangeRateTable = db.lookupTable(s, "EXCHANGE_RATE").orElse(null); assertNotNull(exchangeRateTable); Table exchangeRefTable = db.lookupTable(s, "EXCHANGE_REF").orElse(null); assertNotNull(exchangeRateTable); TableExtractor extractor = new TableExtractor("My", "com.demo.pkg", null, null, null, null); TableModel exchangeRateTableModel = extractor.extractTableModel(exchangeRateTable); TableModel exchangeRefTableModel = extractor.extractTableModel(exchangeRefTable); Assert.assertEquals(1, exchangeRefTableModel.getPrimaryKeyColumns().size()); Assert.assertEquals("ID", exchangeRefTableModel.getPrimaryKeyColumns().get(0).getDbName()); Assert.assertEquals("DECIMAL", exchangeRefTableModel.getPrimaryKeyColumns().get(0).getSqlType()); Assert.assertEquals("java.math.BigDecimal", exchangeRefTableModel.getPrimaryKeyColumns().get(0).getJavaTypeName()); Assert.assertTrue(exchangeRefTableModel.getForeignKeyColumns().isEmpty()); Assert.assertEquals(1, exchangeRefTableModel.getNonPrimaryKeyNonFKColumns().size()); Assert.assertEquals("NAME", exchangeRefTableModel.getNonPrimaryKeyNonFKColumns().get(0).getDbName()); Assert.assertEquals("VARCHAR", exchangeRefTableModel.getNonPrimaryKeyNonFKColumns().get(0).getSqlType()); Assert.assertEquals("java.lang.String", exchangeRefTableModel.getNonPrimaryKeyNonFKColumns().get(0).getJavaTypeName()); Assert.assertEquals(1, exchangeRateTableModel.getNonPrimaryKeyNonFKColumns().size()); Assert.assertEquals("FIRST_NAME", exchangeRateTableModel.getNonPrimaryKeyNonFKColumns().get(0).getDbName()); Assert.assertEquals("VARCHAR", exchangeRateTableModel.getNonPrimaryKeyNonFKColumns().get(0).getSqlType()); Assert.assertEquals("java.lang.String", exchangeRateTableModel.getNonPrimaryKeyNonFKColumns().get(0).getJavaTypeName()); Assert.assertEquals(2, exchangeRateTableModel.getForeignKeyColumns().size()); Assert.assertEquals(1, exchangeRateTableModel.getIncomingForeignKeys().size()); Assert.assertEquals("composite", exchangeRateTableModel.getIncomingForeignKeys().get(0).getReferencingAttributeName()); Assert.assertEquals("composite", exchangeRateTableModel.getIncomingForeignKeys().get(0).getReferencingAttributeName()); ForeignKeyModel compositeForeignKeyModel = exchangeRateTableModel.getForeignKeys().stream() .filter(fk -> fk.getName().equals("composite")) .findFirst().orElse(null); Assert.assertNotNull(compositeForeignKeyModel); Assert.assertEquals(compositeForeignKeyModel.getReferences().size(), 2); Assertions .assertThat(compositeForeignKeyModel.getReferences().keySet()) .containsExactlyInAnyOrder("REFERENCE_ID", "PREV_FIRST_NAME"); Assert.assertFalse(compositeForeignKeyModel.isNotNull()); }
public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; }
TableExtractor { public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; } }
TableExtractor { public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; } TableExtractor(); TableExtractor(final String classPrefix, final String targetPackage, DataTypeProvider dataTypeProvider, final NameProvider nameProvider, ExplicitAttributeDecider explicitAttributeDecider, ConvenienceSetterProvider convenienceSetterProvider); }
TableExtractor { public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; } TableExtractor(); TableExtractor(final String classPrefix, final String targetPackage, DataTypeProvider dataTypeProvider, final NameProvider nameProvider, ExplicitAttributeDecider explicitAttributeDecider, ConvenienceSetterProvider convenienceSetterProvider); TableModel extractTableModel(final Table table); static boolean isJoinTable(final Table table); static Map<String, Map<Table, List<String>>> analyzeJoinTable(Table table); }
TableExtractor { public TableModel extractTableModel(final Table table) { Objects.requireNonNull(table); final TableModel model = new TableModel(); model.setClassName(this.classPrefix + this.nameProvider.getClassNameForTable(table)); model.setName(this.nameProvider.getClassNameForTable(table)); model.setSqlFullName(table.getFullName()); model.setSqlName(table.getName()); model.setPackageName(this.targetPackage); model.setColumns(table.getColumns().stream() .map(this.columnExtractor::extractColumnModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples = new HashSet<>(); model.setForeignKeys(table.getImportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractForeignKeyModel) .collect(Collectors.toList())); Set<Set<String>> seenForeignKeyColumnNameTuples2 = new HashSet<>(); model.setIncomingForeignKeys(table.getExportedForeignKeys().stream() .filter(foreignKeyColumnReferences -> { Set<String> foreignKeyColumnNames = foreignKeyColumnReferences.getColumnReferences().stream() .map(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getFullName()) .collect(Collectors.toSet()); return seenForeignKeyColumnNameTuples2.add(foreignKeyColumnNames); }) .map(this.foreignKeyExtractor::extractIncomingForeignKeyModel) .collect(Collectors.toList())); model.setHasColumnsAndForeignKeys(!model.getNonForeignKeyColumns().isEmpty() && !model.getForeignKeys().isEmpty()); return model; } TableExtractor(); TableExtractor(final String classPrefix, final String targetPackage, DataTypeProvider dataTypeProvider, final NameProvider nameProvider, ExplicitAttributeDecider explicitAttributeDecider, ConvenienceSetterProvider convenienceSetterProvider); TableModel extractTableModel(final Table table); static boolean isJoinTable(final Table table); static Map<String, Map<Table, List<String>>> analyzeJoinTable(Table table); static final String DEFAULT_CLASS_PREFIX; static final String DEFAULT_TARGET_PACKAGE; }
@Test public void testColumnExtraction() throws Exception { Column column = extractColumnFromDemoDb("DEMO_USER", "ID"); ColumnExtractor extractor = new ColumnExtractor(new DefaultDataTypeProvider(), new DefaultNameProvider(), new DefaultExplicitAttributeDecider(), new DefaultConvenienceSetterProvider()); ColumnModel model = extractor.extractColumnModel(column); assertEquals("id", model.getName()); assertEquals("ID", model.getDbName()); assertEquals("DEMO_USER", model.getDbTableName()); assertEquals("DECIMAL", model.getSqlType()); assertEquals("java.math.BigDecimal", model.getJavaTypeName()); assertTrue(model.isNotNull()); }
public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); ColumnModel extractColumnModel(Column column); }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); ColumnModel extractColumnModel(Column column); }
@Test public void testExtractColumnModelForExpliciteAttribute() throws Exception { Column column = extractColumnFromDemoDb("DEMO_USER", "DTYPE"); ColumnExtractor extractor = new ColumnExtractor(new DefaultDataTypeProvider(), new DefaultNameProvider(), new ExplicitAttributeDecider() { @Override public boolean isExplicitAttribute(final Column column) { return column.getName().equals("DTYPE"); } @Override public boolean isExplicitForeignKey(final ForeignKey foreignKey) { return false; } }, new DefaultConvenienceSetterProvider()); ColumnModel columnModel = extractor.extractColumnModel(column); assertEquals("DTYPE", columnModel.getDbName()); assertTrue(columnModel.isExplicitAttribute()); }
public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); ColumnModel extractColumnModel(Column column); }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); ColumnModel extractColumnModel(Column column); }
@Test public void testExtractColumnModelForKeywordColumn() throws Exception { Column column = extractColumnFromDemoDb("DEMO_USER", "DAY"); ColumnExtractor extractor = new ColumnExtractor(new DefaultDataTypeProvider(), new DefaultNameProvider(), new DefaultExplicitAttributeDecider(), new DefaultConvenienceSetterProvider()); ColumnModel model = extractor.extractColumnModel(column); assertEquals("DAY", model.getDbName()); }
public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); ColumnModel extractColumnModel(Column column); }
ColumnExtractor { public ColumnModel extractColumnModel(Column column) { LOG.debug("Extracting model for column {}", column.getName()); ColumnModel model = new ColumnModel(); model.setName(this.nameProvider.getMethodNameForColumn(column)); model.setDbName(column.getName()); model.setDbTableName(column.getParent().getName()); model.setDbFullTableName(column.getParent().getFullName()); model.setSqlType(column.getColumnDataType().getName()); model.setSqlTypeInt(column.getColumnDataType().getJavaSqlType().getVendorTypeNumber()); String javaDataTypeName = dataTypeProvider.getCanonicalDataTypeName(column); model.setJavaTypeName(javaDataTypeName); model.setNotNull(!column.isNullable()); model.setPartOfPrimaryKey(column.isPartOfPrimaryKey()); model.setPartOfForeignKey(column.isPartOfForeignKey()); model.setExplicitAttribute(explicitAttributeDecider.isExplicitAttribute(column)); model.setUnique(column.isPartOfUniqueIndex() || column.isPartOfPrimaryKey()); model.setConvenienceSetters(convenienceSetterProvider.getConvenienceSetters(column, javaDataTypeName)); return model; } ColumnExtractor(final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider); ColumnModel extractColumnModel(Column column); }
@Test public void getConvenienceSetters() throws Exception { InputStream stream = this.getClass().getResourceAsStream("XmlFileConvencienceSetterProviderTest.xml"); InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); XmlFileConvenienceSetterProvider provider = new XmlFileConvenienceSetterProvider(reader); Assert.assertEquals(1, provider.getConvenienceSetters(Mockito.mock(Column.class), "java.util.Date").size()); }
@Override public List<ConvenienceSetterModel> getConvenienceSetters(Column column, String javaDataTypeName) { return this.convenienceSetterConfig.getConvenienceSetterConfigs().stream() .filter(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getJavaDataTypeName().equals(javaDataTypeName)) .flatMap(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getConvenienceSetters().stream()) .collect(Collectors.toList()); }
XmlFileConvenienceSetterProvider implements ConvenienceSetterProvider { @Override public List<ConvenienceSetterModel> getConvenienceSetters(Column column, String javaDataTypeName) { return this.convenienceSetterConfig.getConvenienceSetterConfigs().stream() .filter(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getJavaDataTypeName().equals(javaDataTypeName)) .flatMap(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getConvenienceSetters().stream()) .collect(Collectors.toList()); } }
XmlFileConvenienceSetterProvider implements ConvenienceSetterProvider { @Override public List<ConvenienceSetterModel> getConvenienceSetters(Column column, String javaDataTypeName) { return this.convenienceSetterConfig.getConvenienceSetterConfigs().stream() .filter(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getJavaDataTypeName().equals(javaDataTypeName)) .flatMap(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getConvenienceSetters().stream()) .collect(Collectors.toList()); } XmlFileConvenienceSetterProvider(Reader xmlReader); XmlFileConvenienceSetterProvider(ConvenienceSetterConfig convenienceSetterConfig); }
XmlFileConvenienceSetterProvider implements ConvenienceSetterProvider { @Override public List<ConvenienceSetterModel> getConvenienceSetters(Column column, String javaDataTypeName) { return this.convenienceSetterConfig.getConvenienceSetterConfigs().stream() .filter(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getJavaDataTypeName().equals(javaDataTypeName)) .flatMap(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getConvenienceSetters().stream()) .collect(Collectors.toList()); } XmlFileConvenienceSetterProvider(Reader xmlReader); XmlFileConvenienceSetterProvider(ConvenienceSetterConfig convenienceSetterConfig); @Override List<ConvenienceSetterModel> getConvenienceSetters(Column column, String javaDataTypeName); }
XmlFileConvenienceSetterProvider implements ConvenienceSetterProvider { @Override public List<ConvenienceSetterModel> getConvenienceSetters(Column column, String javaDataTypeName) { return this.convenienceSetterConfig.getConvenienceSetterConfigs().stream() .filter(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getJavaDataTypeName().equals(javaDataTypeName)) .flatMap(dataTypeConvenienceSetterConfig -> dataTypeConvenienceSetterConfig.getConvenienceSetters().stream()) .collect(Collectors.toList()); } XmlFileConvenienceSetterProvider(Reader xmlReader); XmlFileConvenienceSetterProvider(ConvenienceSetterConfig convenienceSetterConfig); @Override List<ConvenienceSetterModel> getConvenienceSetters(Column column, String javaDataTypeName); }
@Test public void testGetMethodNameForColumnSingleTable() throws Exception { Assert.assertEquals("superSingleTableImpliciteNameColumn", provider.getMethodNameForColumn(getColumn("MANAGED_SUPERCLASS_SINGLE_TABLE", "SUPERSINGLETABLEIMPLICITENAMECOLUMN"))); Assert.assertEquals("superSingleTableExpliciteNameColumn", provider.getMethodNameForColumn(getColumn("MANAGED_SUPERCLASS_SINGLE_TABLE", "SUPER_SINGLE_TABLE_EXPLICIT_NAME_COLUMN"))); Assert.assertEquals("subSingleTableImpliciteNameColumn", provider.getMethodNameForColumn(getColumn("MANAGED_SUPERCLASS_SINGLE_TABLE", "SUBSINGLETABLEIMPLICITENAMECOLUMN"))); Assert.assertEquals("subSingleTableExpliciteNameColumn", provider.getMethodNameForColumn(getColumn("MANAGED_SUPERCLASS_SINGLE_TABLE", "SUB_SINGLE_TABLE_EXPLICITE_NAME_COLUMN"))); Assert.assertEquals("subEntitySingleTable2Attribute", provider.getMethodNameForColumn(getColumn("MANAGED_SUPERCLASS_SINGLE_TABLE", "SUBENTITYSINGLETABLE2ATTRIBUTE"))); }
@Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
@Test public void testJoinTableProcessing() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-me", "", ""); assertNotNull(connection); File tempFile = Helpers.getResourceAsFile("codegenerator/test-join-table.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Catalog db = DatabaseManager.crawlDatabase(connection, new IncludeAll(), new IncludeAll()); assertNotNull(db); List<TableModel> models = MetadataExtractor.extract(db); assertEquals(3, models.size()); for (TableModel model : models) { if (model.getName().equals("DemoCompany")) { assertEquals(1, model.getJoinTableSimplifierData().size()); assertTrue(model.getJoinTableSimplifierData().containsKey("GUserWorksAtCompanies")); assertEquals(Arrays.asList("this", "userIdDemoUser"), model.getJoinTableSimplifierData().get("GUserWorksAtCompanies").getConstructorParams()); assertEquals(1, model.getJoinTableSimplifierData().get("GUserWorksAtCompanies").getMethodParams().size()); } else if (model.getName().equals("DemoUser")) { assertEquals(1, model.getJoinTableSimplifierData().size()); assertTrue(model.getJoinTableSimplifierData().containsKey("GUserWorksAtCompanies")); assertEquals(Arrays.asList("companyIdDemoCompany", "this"), model.getJoinTableSimplifierData().get("GUserWorksAtCompanies").getConstructorParams()); assertEquals(1, model.getJoinTableSimplifierData().get("GUserWorksAtCompanies").getMethodParams().size()); } else { assertEquals(0, model.getJoinTableSimplifierData().size()); } } }
public static List<TableModel> extract(final Catalog catalog, final TableExtractor tableExtractor) { LOG.info("Extracting model data from {}", catalog.getFullName()); List<Table> tables = catalog.getTables().stream() .filter(table -> !(table instanceof View)) .collect(Collectors.toList()); final List<TableModel> result = new LinkedList<>(); Map<String, Map<Table, List<String>>> joinTableMetadata = new HashMap<>(); for (Table table : tables) { if (TableExtractor.isJoinTable(table)) { LOG.debug("Found join table: {}", table.getFullName()); joinTableMetadata = MetadataExtractor.mergeJoinTableMetadata(joinTableMetadata, TableExtractor.analyzeJoinTable(table)); } LOG.debug("Extracting model for table {}", table.getFullName()); result.add(tableExtractor.extractTableModel(table)); } LOG.debug("Post-processing the join tables..."); processJoinTables(result, joinTableMetadata); LOG.debug("Post-processing done."); LOG.info("Done extracting the model"); return result; }
MetadataExtractor { public static List<TableModel> extract(final Catalog catalog, final TableExtractor tableExtractor) { LOG.info("Extracting model data from {}", catalog.getFullName()); List<Table> tables = catalog.getTables().stream() .filter(table -> !(table instanceof View)) .collect(Collectors.toList()); final List<TableModel> result = new LinkedList<>(); Map<String, Map<Table, List<String>>> joinTableMetadata = new HashMap<>(); for (Table table : tables) { if (TableExtractor.isJoinTable(table)) { LOG.debug("Found join table: {}", table.getFullName()); joinTableMetadata = MetadataExtractor.mergeJoinTableMetadata(joinTableMetadata, TableExtractor.analyzeJoinTable(table)); } LOG.debug("Extracting model for table {}", table.getFullName()); result.add(tableExtractor.extractTableModel(table)); } LOG.debug("Post-processing the join tables..."); processJoinTables(result, joinTableMetadata); LOG.debug("Post-processing done."); LOG.info("Done extracting the model"); return result; } }
MetadataExtractor { public static List<TableModel> extract(final Catalog catalog, final TableExtractor tableExtractor) { LOG.info("Extracting model data from {}", catalog.getFullName()); List<Table> tables = catalog.getTables().stream() .filter(table -> !(table instanceof View)) .collect(Collectors.toList()); final List<TableModel> result = new LinkedList<>(); Map<String, Map<Table, List<String>>> joinTableMetadata = new HashMap<>(); for (Table table : tables) { if (TableExtractor.isJoinTable(table)) { LOG.debug("Found join table: {}", table.getFullName()); joinTableMetadata = MetadataExtractor.mergeJoinTableMetadata(joinTableMetadata, TableExtractor.analyzeJoinTable(table)); } LOG.debug("Extracting model for table {}", table.getFullName()); result.add(tableExtractor.extractTableModel(table)); } LOG.debug("Post-processing the join tables..."); processJoinTables(result, joinTableMetadata); LOG.debug("Post-processing done."); LOG.info("Done extracting the model"); return result; } }
MetadataExtractor { public static List<TableModel> extract(final Catalog catalog, final TableExtractor tableExtractor) { LOG.info("Extracting model data from {}", catalog.getFullName()); List<Table> tables = catalog.getTables().stream() .filter(table -> !(table instanceof View)) .collect(Collectors.toList()); final List<TableModel> result = new LinkedList<>(); Map<String, Map<Table, List<String>>> joinTableMetadata = new HashMap<>(); for (Table table : tables) { if (TableExtractor.isJoinTable(table)) { LOG.debug("Found join table: {}", table.getFullName()); joinTableMetadata = MetadataExtractor.mergeJoinTableMetadata(joinTableMetadata, TableExtractor.analyzeJoinTable(table)); } LOG.debug("Extracting model for table {}", table.getFullName()); result.add(tableExtractor.extractTableModel(table)); } LOG.debug("Post-processing the join tables..."); processJoinTables(result, joinTableMetadata); LOG.debug("Post-processing done."); LOG.info("Done extracting the model"); return result; } static List<TableModel> extract(final Catalog catalog, final TableExtractor tableExtractor); static List<TableModel> extract(final Catalog catalog); }
MetadataExtractor { public static List<TableModel> extract(final Catalog catalog, final TableExtractor tableExtractor) { LOG.info("Extracting model data from {}", catalog.getFullName()); List<Table> tables = catalog.getTables().stream() .filter(table -> !(table instanceof View)) .collect(Collectors.toList()); final List<TableModel> result = new LinkedList<>(); Map<String, Map<Table, List<String>>> joinTableMetadata = new HashMap<>(); for (Table table : tables) { if (TableExtractor.isJoinTable(table)) { LOG.debug("Found join table: {}", table.getFullName()); joinTableMetadata = MetadataExtractor.mergeJoinTableMetadata(joinTableMetadata, TableExtractor.analyzeJoinTable(table)); } LOG.debug("Extracting model for table {}", table.getFullName()); result.add(tableExtractor.extractTableModel(table)); } LOG.debug("Post-processing the join tables..."); processJoinTables(result, joinTableMetadata); LOG.debug("Post-processing done."); LOG.info("Done extracting the model"); return result; } static List<TableModel> extract(final Catalog catalog, final TableExtractor tableExtractor); static List<TableModel> extract(final Catalog catalog); }
@Test public void testConnectToDatabase_H2Success() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:redg", "", ""); assertNotNull(connection); assertTrue(connection.isValid(10)); }
public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password); static void executePreparationScripts(final Connection connection, final File[] sqlScripts); static Catalog crawlDatabase(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule); }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password); static void executePreparationScripts(final Connection connection, final File[] sqlScripts); static Catalog crawlDatabase(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule); }
@Test public void testConnectToDatabase_InvalidDriver() throws Exception { thrown.expect(ClassNotFoundException.class); DatabaseManager.connectToDatabase("does.not.exist.Driver", "jdbc:dne:mem:redg", "", ""); }
public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password); static void executePreparationScripts(final Connection connection, final File[] sqlScripts); static Catalog crawlDatabase(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule); }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password); static void executePreparationScripts(final Connection connection, final File[] sqlScripts); static Catalog crawlDatabase(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule); }
@Test public void testConnectToDatabase_FailedConnection() throws Exception { thrown.expect(SQLException.class); Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h4:invalid:redg", "", ""); }
public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password); static void executePreparationScripts(final Connection connection, final File[] sqlScripts); static Catalog crawlDatabase(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule); }
DatabaseManager { public static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password) throws ClassNotFoundException, SQLException { try { LOG.debug("Trying to load jdbc driver " + jdbcDriver); Class.forName(jdbcDriver); LOG.info("Successfully loaded jdbc driver"); } catch (ClassNotFoundException e) { LOG.error("Could not load jdbc driver with name " + jdbcDriver); throw e; } try { LOG.debug("Connecting to extractor " + connectionString); final Connection conn = DriverManager.getConnection(connectionString, username, password); LOG.info("Successfully connected to extractor"); return conn; } catch (SQLException e) { LOG.error("Could not connect to extractor", e); throw e; } } static Connection connectToDatabase(final String jdbcDriver, final String connectionString, final String username, final String password); static void executePreparationScripts(final Connection connection, final File[] sqlScripts); static Catalog crawlDatabase(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule); }
@Test public void testFirstCharacterToLowerCase() { assertEquals("hello", NameUtils.firstCharacterToLowerCase("hello")); assertEquals("hello", NameUtils.firstCharacterToLowerCase("Hello")); assertEquals("hELLO", NameUtils.firstCharacterToLowerCase("HELLO")); assertEquals("4heLLo", NameUtils.firstCharacterToLowerCase("4heLLo")); assertEquals("", NameUtils.firstCharacterToLowerCase("")); assertEquals(null, NameUtils.firstCharacterToLowerCase(null)); }
public static String firstCharacterToLowerCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toLowerCase(letters[0]); return new String(letters); }
NameUtils { public static String firstCharacterToLowerCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toLowerCase(letters[0]); return new String(letters); } }
NameUtils { public static String firstCharacterToLowerCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toLowerCase(letters[0]); return new String(letters); } }
NameUtils { public static String firstCharacterToLowerCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toLowerCase(letters[0]); return new String(letters); } static String firstCharacterToLowerCase(final String s); static String firstCharacterToUpperCase(final String s); static String escapeQuotationMarks(final String s); }
NameUtils { public static String firstCharacterToLowerCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toLowerCase(letters[0]); return new String(letters); } static String firstCharacterToLowerCase(final String s); static String firstCharacterToUpperCase(final String s); static String escapeQuotationMarks(final String s); }
@Test public void testFirstCharacterToUpperCase() { assertEquals("Hello", NameUtils.firstCharacterToUpperCase("hello")); assertEquals("Hello", NameUtils.firstCharacterToUpperCase("Hello")); assertEquals("HELLO", NameUtils.firstCharacterToUpperCase("HELLO")); assertEquals("4heLLo", NameUtils.firstCharacterToUpperCase("4heLLo")); assertEquals("", NameUtils.firstCharacterToUpperCase("")); assertEquals(null, NameUtils.firstCharacterToUpperCase(null)); }
public static String firstCharacterToUpperCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toUpperCase(letters[0]); return new String(letters); }
NameUtils { public static String firstCharacterToUpperCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toUpperCase(letters[0]); return new String(letters); } }
NameUtils { public static String firstCharacterToUpperCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toUpperCase(letters[0]); return new String(letters); } }
NameUtils { public static String firstCharacterToUpperCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toUpperCase(letters[0]); return new String(letters); } static String firstCharacterToLowerCase(final String s); static String firstCharacterToUpperCase(final String s); static String escapeQuotationMarks(final String s); }
NameUtils { public static String firstCharacterToUpperCase(final String s) { if (s == null || s.length() < 1) { return s; } final char[] letters = s.toCharArray(); letters[0] = Character.toUpperCase(letters[0]); return new String(letters); } static String firstCharacterToLowerCase(final String s); static String firstCharacterToUpperCase(final String s); static String escapeQuotationMarks(final String s); }
@Test public void get() { JavaSqlStringEscapeMap defaultMap = new JavaSqlStringEscapeMap(); assertThat(defaultMap.get("asdf")).isEqualTo("\\\"asdf\\\""); assertThat(defaultMap.get("ASDF")).isEqualTo("\\\"ASDF\\\""); assertThat(defaultMap.get("\"TABLE\"")).isEqualTo("\\\"TABLE\\\""); JavaSqlStringEscapeMap mySqlMap = new JavaSqlStringEscapeMap("`"); assertThat(mySqlMap.get("asdf")).isEqualTo("`asdf`"); assertThat(mySqlMap.get("ASDF")).isEqualTo("`ASDF`"); assertThat(mySqlMap.get("\"TABLE\"")).isEqualTo("`TABLE`"); JavaSqlStringEscapeMap msSqlMap = new JavaSqlStringEscapeMap("[", "]"); assertThat(msSqlMap.get("asdf")).isEqualTo("[asdf]"); assertThat(msSqlMap.get("ASDF")).isEqualTo("[ASDF]"); assertThat(msSqlMap.get("\"TABLE\"")).isEqualTo("[TABLE]"); }
@Override public Object get(Object key) { if (key instanceof String) { String str = (String) key; return this.escapeStringBefore + str.replace("\"", "") + this.escapeStringAfter; } return super.get(key); }
JavaSqlStringEscapeMap extends AbstractMap<String, Object> { @Override public Object get(Object key) { if (key instanceof String) { String str = (String) key; return this.escapeStringBefore + str.replace("\"", "") + this.escapeStringAfter; } return super.get(key); } }
JavaSqlStringEscapeMap extends AbstractMap<String, Object> { @Override public Object get(Object key) { if (key instanceof String) { String str = (String) key; return this.escapeStringBefore + str.replace("\"", "") + this.escapeStringAfter; } return super.get(key); } JavaSqlStringEscapeMap(String escapeStringBefore, String escapeStringAfter); JavaSqlStringEscapeMap(String escapeString); JavaSqlStringEscapeMap(); }
JavaSqlStringEscapeMap extends AbstractMap<String, Object> { @Override public Object get(Object key) { if (key instanceof String) { String str = (String) key; return this.escapeStringBefore + str.replace("\"", "") + this.escapeStringAfter; } return super.get(key); } JavaSqlStringEscapeMap(String escapeStringBefore, String escapeStringAfter); JavaSqlStringEscapeMap(String escapeString); JavaSqlStringEscapeMap(); @Override Object get(Object key); @Override boolean containsKey(Object key); @Override Set<Entry<String, Object>> entrySet(); }
JavaSqlStringEscapeMap extends AbstractMap<String, Object> { @Override public Object get(Object key) { if (key instanceof String) { String str = (String) key; return this.escapeStringBefore + str.replace("\"", "") + this.escapeStringAfter; } return super.get(key); } JavaSqlStringEscapeMap(String escapeStringBefore, String escapeStringAfter); JavaSqlStringEscapeMap(String escapeString); JavaSqlStringEscapeMap(); @Override Object get(Object key); @Override boolean containsKey(Object key); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void containsKey() { JavaSqlStringEscapeMap map = new JavaSqlStringEscapeMap(); assertThat(map.containsKey("A")).isTrue(); assertThat(map.containsKey("Longer String")).isTrue(); assertThat(map.containsKey(10)).isFalse(); assertThat(map.containsKey(new BigDecimal(1))).isFalse(); assertThat(map.containsKey(new Date())).isFalse(); }
@Override public boolean containsKey(Object key) { return (key instanceof String); }
JavaSqlStringEscapeMap extends AbstractMap<String, Object> { @Override public boolean containsKey(Object key) { return (key instanceof String); } }
JavaSqlStringEscapeMap extends AbstractMap<String, Object> { @Override public boolean containsKey(Object key) { return (key instanceof String); } JavaSqlStringEscapeMap(String escapeStringBefore, String escapeStringAfter); JavaSqlStringEscapeMap(String escapeString); JavaSqlStringEscapeMap(); }
JavaSqlStringEscapeMap extends AbstractMap<String, Object> { @Override public boolean containsKey(Object key) { return (key instanceof String); } JavaSqlStringEscapeMap(String escapeStringBefore, String escapeStringAfter); JavaSqlStringEscapeMap(String escapeString); JavaSqlStringEscapeMap(); @Override Object get(Object key); @Override boolean containsKey(Object key); @Override Set<Entry<String, Object>> entrySet(); }
JavaSqlStringEscapeMap extends AbstractMap<String, Object> { @Override public boolean containsKey(Object key) { return (key instanceof String); } JavaSqlStringEscapeMap(String escapeStringBefore, String escapeStringAfter); JavaSqlStringEscapeMap(String escapeString); JavaSqlStringEscapeMap(); @Override Object get(Object key); @Override boolean containsKey(Object key); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testGenerateCode_Working() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:redg-test-all", "", ""); File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Path p = Files.createTempDirectory("redg-test"); RedGGenerator.generateCode(connection, new IncludeAll(), new IncludeAll(), null, "", p, null, null, null, null, false, true); Path mainFile = Paths.get(p.toAbsolutePath().toString(), "com", "btc", "redg", "generated", "RedG.java"); assertTrue(Files.exists(mainFile)); Path classFileUser = Paths.get(p.toAbsolutePath().toString(), "com", "btc", "redg", "generated", "GDemoUser.java"); assertTrue(Files.exists(mainFile)); Path classFileCompany = Paths.get(p.toAbsolutePath().toString(), "com", "btc", "redg", "generated", "GDemoCompany.java"); assertTrue(Files.exists(mainFile)); }
public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection); static Catalog crawlDatabase(Connection connection, InclusionRule schemaRule, InclusionRule tableRule, boolean shouldCloseConnection); static List<TableModel> extractTableModel(TableExtractor tableExtractor, Catalog database); static Path createPackageFolderStructure(Path targetDirectory, String targetPackage); }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection); static Catalog crawlDatabase(Connection connection, InclusionRule schemaRule, InclusionRule tableRule, boolean shouldCloseConnection); static List<TableModel> extractTableModel(TableExtractor tableExtractor, Catalog database); static Path createPackageFolderStructure(Path targetDirectory, String targetPackage); }
@Test public void testGenerateCode_NoTables() throws Exception { thrown.expect(RedGGenerationException.class); thrown.expectMessage("Crawling failed"); Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:redg-test-all", "", ""); File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Path p = Files.createTempDirectory("redg-test"); RedGGenerator.generateCode(connection, new ExcludeAll(), new ExcludeAll(), null, "", p, null, null, null, null, false, true); }
public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection); static Catalog crawlDatabase(Connection connection, InclusionRule schemaRule, InclusionRule tableRule, boolean shouldCloseConnection); static List<TableModel> extractTableModel(TableExtractor tableExtractor, Catalog database); static Path createPackageFolderStructure(Path targetDirectory, String targetPackage); }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection); static Catalog crawlDatabase(Connection connection, InclusionRule schemaRule, InclusionRule tableRule, boolean shouldCloseConnection); static List<TableModel> extractTableModel(TableExtractor tableExtractor, Catalog database); static Path createPackageFolderStructure(Path targetDirectory, String targetPackage); }
@Test public void testGetMethodNameForColumnTablePerClass() throws Exception { Assert.assertEquals("superTablePerClassImpliciteNameColumn", provider.getMethodNameForColumn(getColumn("SUBENTITYTABLEPERCLASS1", "SUPERTABLEPERCLASSIMPLICITENAMECOLUMN"))); Assert.assertEquals("superTablePerClassExpliciteNameColumn", provider.getMethodNameForColumn(getColumn("SUBENTITYTABLEPERCLASS1", "SUPER_TABLE_PER_CLASS_EXPLICIT_NAME_COLUMN"))); Assert.assertEquals("subTablePerClassImpliciteNameColumn", provider.getMethodNameForColumn(getColumn("SUBENTITYTABLEPERCLASS1", "SUBTABLEPERCLASSIMPLICITENAMECOLUMN"))); Assert.assertEquals("subTablePerClassExpliciteNameColumn", provider.getMethodNameForColumn(getColumn("SUBENTITYTABLEPERCLASS1", "SUB_TABLE_PER_CLASS_EXPLICITE_NAME_COLUMN"))); Assert.assertEquals("subEntityTablePerClass2Attribute", provider.getMethodNameForColumn(getColumn("SUBENTITY_TABLE_PER_CLASS_2", "SUBENTITYTABLEPERCLASS2ATTRIBUTE"))); }
@Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableName, column.getName().toUpperCase())); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForColumn(column); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
@Test public void testGenerateCode_CannotWriteFolder() throws Exception { thrown.expect(RedGGenerationException.class); thrown.expectMessage("Creation of package folder structure failed"); Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:redg-test-all", "", ""); File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Path p; if (System.getProperty("os.name").toLowerCase().contains("win")) { p = Paths.get("C:/windows/system32/redg"); } else { p = Paths.get("/dev/redg"); } RedGGenerator.generateCode(connection, new IncludeAll(), new IncludeAll(), null, "", p, null, null, null, null, false, true); }
public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection); static Catalog crawlDatabase(Connection connection, InclusionRule schemaRule, InclusionRule tableRule, boolean shouldCloseConnection); static List<TableModel> extractTableModel(TableExtractor tableExtractor, Catalog database); static Path createPackageFolderStructure(Path targetDirectory, String targetPackage); }
RedGGenerator { public static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection) { Objects.requireNonNull(connection, "RedG requires a JDBC connection to a database to perform an analysis"); targetPackage = targetPackage != null ? targetPackage : TableExtractor.DEFAULT_TARGET_PACKAGE; classPrefix = classPrefix != null ? classPrefix : TableExtractor.DEFAULT_CLASS_PREFIX; final TableExtractor tableExtractor = new TableExtractor(classPrefix, targetPackage, dataTypeProvider, nameProvider, explicitAttributeDecider, convenienceSetterProvider); Objects.requireNonNull(targetDirectory, "RedG needs a target directory for the generated source code"); LOG.info("Starting the RedG all-in-one code generation."); Catalog databaseCatalog = crawlDatabase(connection, schemaRule, tableRule, shouldCloseConnection); final List<TableModel> tables = extractTableModel(tableExtractor, databaseCatalog); Path targetWithPkgFolders = createPackageFolderStructure(targetDirectory, targetPackage); new CodeGenerator().generate(tables, targetWithPkgFolders, enableVisualizationSupport); } static void generateCode(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule, String targetPackage, String classPrefix, final Path targetDirectory, final DataTypeProvider dataTypeProvider, final NameProvider nameProvider, final ExplicitAttributeDecider explicitAttributeDecider, final ConvenienceSetterProvider convenienceSetterProvider, final boolean enableVisualizationSupport, final boolean shouldCloseConnection); static Catalog crawlDatabase(Connection connection, InclusionRule schemaRule, InclusionRule tableRule, boolean shouldCloseConnection); static List<TableModel> extractTableModel(TableExtractor tableExtractor, Catalog database); static Path createPackageFolderStructure(Path targetDirectory, String targetPackage); }
@Test public void testGenerateCodeForTable() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-cg-tt", "", ""); assertNotNull(connection); File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Catalog db = DatabaseManager.crawlDatabase(connection, new IncludeAll(), new IncludeAll()); assertNotNull(db); Schema s = db.getSchemas().stream().filter(schema -> schema.getName().equals("PUBLIC")).findFirst().orElse(null); assertNotNull(s); Table t = db.getTables(s).stream().filter(table -> table.getName().equals("DEMO_USER")).findFirst().orElse(null); assertNotNull(t); List<TableModel> models = MetadataExtractor.extract(db, new TableExtractor("G", "com.btc.redg.generated", new DefaultDataTypeProvider(), new DefaultNameProvider(), new ExplicitAttributeDecider() { @Override public boolean isExplicitAttribute(final Column column) { return column.getName().equals("DTYPE"); } @Override public boolean isExplicitForeignKey(final ForeignKey foreignKey) { return false; } }, new DefaultConvenienceSetterProvider())); TableModel model = models.stream().filter(m -> Objects.equals("DemoUser", m.getName())).findFirst().orElse(null); assertNotNull(model); CodeGenerator cg = new CodeGenerator(); String result = cg.generateCodeForTable(model, false); assertNotNull(result); assertEquals(Helpers.getResourceAsString("codegenerator/tableResult.java"), result); String existingClassResult = cg.generateExistingClassCodeForTable(model); assertNotNull(existingClassResult); assertEquals(Helpers.getResourceAsString("codegenerator/tableResultExisting.java"), existingClassResult); connection.close(); }
public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); }
CodeGenerator { public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); } }
CodeGenerator { public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); }
CodeGenerator { public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); void generate(List<TableModel> tables, Path targetWithPkgFolders, final boolean enableVisualizationSupport); String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport); String generateExistingClassCodeForTable(final TableModel table); String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport); }
CodeGenerator { public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); void generate(List<TableModel> tables, Path targetWithPkgFolders, final boolean enableVisualizationSupport); String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport); String generateExistingClassCodeForTable(final TableModel table); String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport); }
@Test public void testGenerateCodeEscaping() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-cg-te", "", ""); assertNotNull(connection); File tempFile = Helpers.getResourceAsFile("codegenerator/test-escaping.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Catalog db = DatabaseManager.crawlDatabase(connection, new IncludeAll(), new IncludeAll()); assertNotNull(db); Schema s = db.getSchemas().stream().filter(schema -> schema.getName().equals("PUBLIC")).findFirst().orElse(null); assertNotNull(s); Table t1 = db.getTables(s).stream().filter(table -> table.getName().equals("TABLE")).findFirst().orElse(null); assertNotNull(t1); Table t2 = db.getTables(s).stream().filter(table -> table.getName().equals("GROUP")).findFirst().orElse(null); assertNotNull(t2); List<TableModel> models = MetadataExtractor.extract(db); assertNotNull(models); assertThat(models.size(), is(2)); TableModel modelTable = models.stream().filter(m -> Objects.equals("Table", m.getName())).findFirst().orElse(null); assertNotNull(modelTable); TableModel modelGroup = models.stream().filter(m -> Objects.equals("Group", m.getName())).findFirst().orElse(null); assertNotNull(modelGroup); CodeGenerator cg = new CodeGenerator(); String resultTable = cg.generateCodeForTable(modelTable, false); String resultGroup = cg.generateCodeForTable(modelGroup, false); assertNotNull(resultTable); assertNotNull(resultGroup); assertEquals(Helpers.getResourceAsString("codegenerator/table-escaping-Result-table.java"), resultTable); assertEquals(Helpers.getResourceAsString("codegenerator/table-escaping-Result-group.java"), resultGroup); connection.close(); }
public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); }
CodeGenerator { public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); } }
CodeGenerator { public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); }
CodeGenerator { public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); void generate(List<TableModel> tables, Path targetWithPkgFolders, final boolean enableVisualizationSupport); String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport); String generateExistingClassCodeForTable(final TableModel table); String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport); }
CodeGenerator { public String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport) { final ST template = this.stGroup.getInstanceOf("tableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Package is {} | Class name is {}", table.getPackageName(), table.getClassName()); template.add("colAndForeignKeys", table.hasColumnsAndForeignKeys()); template.add("firstRowComma", (!table.getNullableForeignKeys().isEmpty() || table.hasColumnsAndForeignKeys()) && !table.getNotNullForeignKeys().isEmpty()); template.add("secondRowComma", table.hasColumnsAndForeignKeys() && !table.getNullableForeignKeys().isEmpty()); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(table); oos.close(); String serializedData = Base64.getEncoder().encodeToString(baos.toByteArray()); template.add("serializedTableModelString", serializedData); } catch (IOException e) { LOG.error("Could not serialize table model. Model will not be included in the file", e); } template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Rendering template..."); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); void generate(List<TableModel> tables, Path targetWithPkgFolders, final boolean enableVisualizationSupport); String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport); String generateExistingClassCodeForTable(final TableModel table); String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport); }
@Test public void testGenerateMainClass() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-cg-main", "", ""); assertNotNull(connection); File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Catalog db = DatabaseManager.crawlDatabase(connection, new IncludeAll(), new IncludeAll()); assertNotNull(db); List<TableModel> models = MetadataExtractor.extract(db); CodeGenerator cg = new CodeGenerator(); String result = cg.generateMainClass(models, false); assertNotNull(result); assertEquals(Helpers.getResourceAsString("codegenerator/mainResult.java"), result); connection.close(); }
public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); }
CodeGenerator { public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); } }
CodeGenerator { public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); }
CodeGenerator { public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); void generate(List<TableModel> tables, Path targetWithPkgFolders, final boolean enableVisualizationSupport); String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport); String generateExistingClassCodeForTable(final TableModel table); String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport); }
CodeGenerator { public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); void generate(List<TableModel> tables, Path targetWithPkgFolders, final boolean enableVisualizationSupport); String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport); String generateExistingClassCodeForTable(final TableModel table); String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport); }
@Test public void testGenerateMainClassWithVisualization() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:rt-cg-main", "", ""); assertNotNull(connection); File tempFile = Helpers.getResourceAsFile("codegenerator/test.sql"); assertNotNull(tempFile); DatabaseManager.executePreparationScripts(connection, new File[]{tempFile}); Catalog db = DatabaseManager.crawlDatabase(connection, new IncludeAll(), new IncludeAll()); assertNotNull(db); List<TableModel> models = MetadataExtractor.extract(db); CodeGenerator cg = new CodeGenerator(); String result = cg.generateMainClass(models, true); assertNotNull(result); assertEquals(Helpers.getResourceAsString("codegenerator/mainResult-wV.java"), result); connection.close(); }
public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); }
CodeGenerator { public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); } }
CodeGenerator { public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); }
CodeGenerator { public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); void generate(List<TableModel> tables, Path targetWithPkgFolders, final boolean enableVisualizationSupport); String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport); String generateExistingClassCodeForTable(final TableModel table); String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport); }
CodeGenerator { public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInstanceOf("mainClass"); LOG.debug("Filling main class template containing helpers for {} classes...", tables.size()); template.add("package", targetPackage); template.add("prefix", ""); template.add("enableVisualizationSupport", enableVisualizationSupport); LOG.debug("Package is {} | Prefix is {}", targetPackage, ""); template.add("tables", tables); return template.render(); } CodeGenerator(); CodeGenerator(final String templateResource, final String sqlEscapeString); CodeGenerator(final String templateResource); void generate(List<TableModel> tables, Path targetWithPkgFolders, final boolean enableVisualizationSupport); String generateCodeForTable(final TableModel table, final boolean enableVisualizationSupport); String generateExistingClassCodeForTable(final TableModel table); String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport); }
@Test public void testHappyPaths() throws Exception { Assert.assertTrue(new ClassAvailabilityChecker("java.util.HashMap").isAvailable()); Assert.assertFalse(new ClassAvailabilityChecker("no.java.util.HashMap").isAvailable()); }
public boolean isAvailable() { return available; }
ClassAvailabilityChecker { public boolean isAvailable() { return available; } }
ClassAvailabilityChecker { public boolean isAvailable() { return available; } ClassAvailabilityChecker(String fqcn); }
ClassAvailabilityChecker { public boolean isAvailable() { return available; } ClassAvailabilityChecker(String fqcn); boolean isAvailable(); }
ClassAvailabilityChecker { public boolean isAvailable() { return available; } ClassAvailabilityChecker(String fqcn); boolean isAvailable(); }
@Test public void testTransform() throws Exception { PreparedStatement preparedStatementMock = Mockito.mock(PreparedStatement.class); DefaultPreparedStatementParameterSetter parameterSetter = new DefaultPreparedStatementParameterSetter(); parameterSetter.setParameter(preparedStatementMock, 1, "test", createMockAttributeMetaInfo(), null); Mockito.verify(preparedStatementMock).setObject(1, "test", Types.VARCHAR); parameterSetter.setParameter(preparedStatementMock, 1, 'a', createMockAttributeMetaInfo(), null); Mockito.verify(preparedStatementMock).setObject(1, "a", Types.VARCHAR); parameterSetter.setParameter(preparedStatementMock, 1, 10, createMockAttributeMetaInfo2(), null); Mockito.verify(preparedStatementMock).setObject(1, 10, Types.BIGINT); }
@Override public void setParameter(PreparedStatement statement, int parameterIndex, final Object o, final AttributeMetaInfo attributeMetaInfo, final Connection connection) throws SQLException { if (!(o instanceof String) && STRING_SQL_TYPES.contains(attributeMetaInfo.getSqlTypeInt())) { statement.setObject(parameterIndex, o.toString(), attributeMetaInfo.getSqlTypeInt()); } else { statement.setObject(parameterIndex, o, attributeMetaInfo.getSqlTypeInt()); } }
DefaultPreparedStatementParameterSetter implements PreparedStatementParameterSetter { @Override public void setParameter(PreparedStatement statement, int parameterIndex, final Object o, final AttributeMetaInfo attributeMetaInfo, final Connection connection) throws SQLException { if (!(o instanceof String) && STRING_SQL_TYPES.contains(attributeMetaInfo.getSqlTypeInt())) { statement.setObject(parameterIndex, o.toString(), attributeMetaInfo.getSqlTypeInt()); } else { statement.setObject(parameterIndex, o, attributeMetaInfo.getSqlTypeInt()); } } }
DefaultPreparedStatementParameterSetter implements PreparedStatementParameterSetter { @Override public void setParameter(PreparedStatement statement, int parameterIndex, final Object o, final AttributeMetaInfo attributeMetaInfo, final Connection connection) throws SQLException { if (!(o instanceof String) && STRING_SQL_TYPES.contains(attributeMetaInfo.getSqlTypeInt())) { statement.setObject(parameterIndex, o.toString(), attributeMetaInfo.getSqlTypeInt()); } else { statement.setObject(parameterIndex, o, attributeMetaInfo.getSqlTypeInt()); } } }
DefaultPreparedStatementParameterSetter implements PreparedStatementParameterSetter { @Override public void setParameter(PreparedStatement statement, int parameterIndex, final Object o, final AttributeMetaInfo attributeMetaInfo, final Connection connection) throws SQLException { if (!(o instanceof String) && STRING_SQL_TYPES.contains(attributeMetaInfo.getSqlTypeInt())) { statement.setObject(parameterIndex, o.toString(), attributeMetaInfo.getSqlTypeInt()); } else { statement.setObject(parameterIndex, o, attributeMetaInfo.getSqlTypeInt()); } } @Override void setParameter(PreparedStatement statement, int parameterIndex, final Object o, final AttributeMetaInfo attributeMetaInfo, final Connection connection); }
DefaultPreparedStatementParameterSetter implements PreparedStatementParameterSetter { @Override public void setParameter(PreparedStatement statement, int parameterIndex, final Object o, final AttributeMetaInfo attributeMetaInfo, final Connection connection) throws SQLException { if (!(o instanceof String) && STRING_SQL_TYPES.contains(attributeMetaInfo.getSqlTypeInt())) { statement.setObject(parameterIndex, o.toString(), attributeMetaInfo.getSqlTypeInt()); } else { statement.setObject(parameterIndex, o, attributeMetaInfo.getSqlTypeInt()); } } @Override void setParameter(PreparedStatement statement, int parameterIndex, final Object o, final AttributeMetaInfo attributeMetaInfo, final Connection connection); }
@Test public void testWhen() throws Exception { DefaultValueStrategyBuilder builder = new DefaultValueStrategyBuilder(); builder.when(columnModel -> false).thenUse(111); builder.when(columnModel -> true).thenUse(222); builder.when(columnModel -> false).thenUse(333); DefaultValueStrategy strategy = builder.build(); Assert.assertEquals(222, strategy.getDefaultValue(Mockito.mock(ColumnModel.class), int.class).intValue()); }
public Condition when(final Predicate<ColumnModel> predicate) { return new PredicateCondition(predicate); }
DefaultValueStrategyBuilder { public Condition when(final Predicate<ColumnModel> predicate) { return new PredicateCondition(predicate); } }
DefaultValueStrategyBuilder { public Condition when(final Predicate<ColumnModel> predicate) { return new PredicateCondition(predicate); } }
DefaultValueStrategyBuilder { public Condition when(final Predicate<ColumnModel> predicate) { return new PredicateCondition(predicate); } Condition when(final Predicate<ColumnModel> predicate); Condition whenTableNameMatches(final String regex); Condition whenColumnNameMatches(final String regex); void setFallbackStrategy(DefaultValueStrategy fallbackStrategy); DefaultValueStrategy build(); }
DefaultValueStrategyBuilder { public Condition when(final Predicate<ColumnModel> predicate) { return new PredicateCondition(predicate); } Condition when(final Predicate<ColumnModel> predicate); Condition whenTableNameMatches(final String regex); Condition whenColumnNameMatches(final String regex); void setFallbackStrategy(DefaultValueStrategy fallbackStrategy); DefaultValueStrategy build(); }
@Test public void testWhenColumnNameMatches() throws Exception { DefaultValueStrategyBuilder builder = new DefaultValueStrategyBuilder(); builder.whenColumnNameMatches(".*X").thenUse(999); DefaultValueStrategy strategy = builder.build(); ColumnModel columnMock = Mockito.mock(ColumnModel.class); Mockito.when(columnMock.getDbName()).thenReturn("ASDFX"); Assert.assertEquals(999, strategy.getDefaultValue(columnMock, int.class).intValue()); Mockito.when(columnMock.getDbName()).thenReturn("ASDFA"); Assert.assertNull("should return null since the default default value is null", strategy.getDefaultValue(columnMock, int.class)); }
public Condition whenColumnNameMatches(final String regex) { return new ColumnNameRegexCondition(regex); }
DefaultValueStrategyBuilder { public Condition whenColumnNameMatches(final String regex) { return new ColumnNameRegexCondition(regex); } }
DefaultValueStrategyBuilder { public Condition whenColumnNameMatches(final String regex) { return new ColumnNameRegexCondition(regex); } }
DefaultValueStrategyBuilder { public Condition whenColumnNameMatches(final String regex) { return new ColumnNameRegexCondition(regex); } Condition when(final Predicate<ColumnModel> predicate); Condition whenTableNameMatches(final String regex); Condition whenColumnNameMatches(final String regex); void setFallbackStrategy(DefaultValueStrategy fallbackStrategy); DefaultValueStrategy build(); }
DefaultValueStrategyBuilder { public Condition whenColumnNameMatches(final String regex) { return new ColumnNameRegexCondition(regex); } Condition when(final Predicate<ColumnModel> predicate); Condition whenTableNameMatches(final String regex); Condition whenColumnNameMatches(final String regex); void setFallbackStrategy(DefaultValueStrategy fallbackStrategy); DefaultValueStrategy build(); }
@Test public void testWhenTableNameMatches() throws Exception { DefaultValueStrategyBuilder builder = new DefaultValueStrategyBuilder(); builder.whenTableNameMatches(".*X").thenUse(999); DefaultValueStrategy strategy = builder.build(); ColumnModel columnMock = Mockito.mock(ColumnModel.class); Mockito.when(columnMock.getDbTableName()).thenReturn("ASDFX"); Assert.assertEquals(999, strategy.getDefaultValue(columnMock, int.class).intValue()); Mockito.when(columnMock.getDbTableName()).thenReturn("ASDFA"); Assert.assertNull(strategy.getDefaultValue(columnMock, int.class)); }
public Condition whenTableNameMatches(final String regex) { return new TableNameRegexCondition(regex); }
DefaultValueStrategyBuilder { public Condition whenTableNameMatches(final String regex) { return new TableNameRegexCondition(regex); } }
DefaultValueStrategyBuilder { public Condition whenTableNameMatches(final String regex) { return new TableNameRegexCondition(regex); } }
DefaultValueStrategyBuilder { public Condition whenTableNameMatches(final String regex) { return new TableNameRegexCondition(regex); } Condition when(final Predicate<ColumnModel> predicate); Condition whenTableNameMatches(final String regex); Condition whenColumnNameMatches(final String regex); void setFallbackStrategy(DefaultValueStrategy fallbackStrategy); DefaultValueStrategy build(); }
DefaultValueStrategyBuilder { public Condition whenTableNameMatches(final String regex) { return new TableNameRegexCondition(regex); } Condition when(final Predicate<ColumnModel> predicate); Condition whenTableNameMatches(final String regex); Condition whenColumnNameMatches(final String regex); void setFallbackStrategy(DefaultValueStrategy fallbackStrategy); DefaultValueStrategy build(); }
@Test public void testGetMethodNameForForeignKey() throws Exception { Assert.assertEquals("subJoinedManyToOne", provider.getMethodNameForReference(getForeignKey("SUB_ENTITY_JOINED_1", "SUBJOINEDMANYTOONE_ID"))); Assert.assertEquals("refEntity2", provider.getMethodNameForReference(getForeignKey("REFERENCEDENTITY1", "REFENTITY2_ID1"))); }
@Override public String getMethodNameForReference(ForeignKey foreignKey) { ForeignKeyRelation foreignKeyRelation = toForeignKeyRelation(foreignKey); SingularAttribute singularAttribute = singularAttributesByForeignKeyRelation.get(foreignKeyRelation); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForReference(foreignKey); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForReference(ForeignKey foreignKey) { ForeignKeyRelation foreignKeyRelation = toForeignKeyRelation(foreignKey); SingularAttribute singularAttribute = singularAttributesByForeignKeyRelation.get(foreignKeyRelation); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForReference(foreignKey); } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForReference(ForeignKey foreignKey) { ForeignKeyRelation foreignKeyRelation = toForeignKeyRelation(foreignKey); SingularAttribute singularAttribute = singularAttributesByForeignKeyRelation.get(foreignKeyRelation); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForReference(foreignKey); } JpaMetamodelRedGProvider(Metamodel metaModel); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForReference(ForeignKey foreignKey) { ForeignKeyRelation foreignKeyRelation = toForeignKeyRelation(foreignKey); SingularAttribute singularAttribute = singularAttributesByForeignKeyRelation.get(foreignKeyRelation); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForReference(foreignKey); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForReference(ForeignKey foreignKey) { ForeignKeyRelation foreignKeyRelation = toForeignKeyRelation(foreignKey); SingularAttribute singularAttribute = singularAttributesByForeignKeyRelation.get(foreignKeyRelation); return singularAttribute != null ? singularAttribute.getName() : fallbackNameProvider.getMethodNameForReference(foreignKey); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
@Test public void testSetFallbackStrategy() throws Exception { DefaultValueStrategyBuilder builder = new DefaultValueStrategyBuilder(); builder.when(columnModel -> false).thenUse("asdf"); builder.setFallbackStrategy(new DefaultValueStrategy() { @Override public <T> T getDefaultValue(ColumnModel columnModel, Class<T> type) { return (T) "fallback value"; } }); DefaultValueStrategy strategy = builder.build(); Assert.assertEquals("fallback value", strategy.getDefaultValue(Mockito.mock(ColumnModel.class), String.class)); }
public void setFallbackStrategy(DefaultValueStrategy fallbackStrategy) { this.fallbackStrategy = fallbackStrategy; }
DefaultValueStrategyBuilder { public void setFallbackStrategy(DefaultValueStrategy fallbackStrategy) { this.fallbackStrategy = fallbackStrategy; } }
DefaultValueStrategyBuilder { public void setFallbackStrategy(DefaultValueStrategy fallbackStrategy) { this.fallbackStrategy = fallbackStrategy; } }
DefaultValueStrategyBuilder { public void setFallbackStrategy(DefaultValueStrategy fallbackStrategy) { this.fallbackStrategy = fallbackStrategy; } Condition when(final Predicate<ColumnModel> predicate); Condition whenTableNameMatches(final String regex); Condition whenColumnNameMatches(final String regex); void setFallbackStrategy(DefaultValueStrategy fallbackStrategy); DefaultValueStrategy build(); }
DefaultValueStrategyBuilder { public void setFallbackStrategy(DefaultValueStrategy fallbackStrategy) { this.fallbackStrategy = fallbackStrategy; } Condition when(final Predicate<ColumnModel> predicate); Condition whenTableNameMatches(final String regex); Condition whenColumnNameMatches(final String regex); void setFallbackStrategy(DefaultValueStrategy fallbackStrategy); DefaultValueStrategy build(); }
@Test public void testStrategy() { DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); ColumnModel columnModel = new ColumnModel(); columnModel.setNotNull(false); assertEquals(null, strategy.getDefaultValue(columnModel, String.class)); defaultMappings.forEach((key, value) -> { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setJavaTypeName(key.getName()); assertEquals(value, strategy.getDefaultValue(cm, key)); }); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_Primitive() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setJavaTypeName("int"); Assert.assertEquals(0, new DefaultDefaultValueStrategy().getDefaultValue(cm, int.class).intValue()); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_NoValue() { thrown.expect(NoDefaultValueException.class); thrown.expectMessage("No default value for type"); DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); strategy.getDefaultValue(cm, Color.class); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_UniqueString() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); for (int i = 0; i < 100; i++) { assertEquals(Long.toString(i, 36), strategy.getDefaultValue(cm, String.class)); } }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_UniqueNumber() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); for (int i = 0; i < 200; i++) { assertEquals(i, (int) strategy.getDefaultValue(cm, Integer.class)); } }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_UniqueChar() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); for (int i = 0; i < Character.MAX_VALUE; i++) { assertEquals((char) (i + 1), (char) strategy.getDefaultValue(cm, char.class)); } thrown.expect(NoDefaultValueException.class); strategy.getDefaultValue(cm, Character.class); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_UniqueBoolean() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); assertFalse(strategy.getDefaultValue(cm, boolean.class)); assertTrue(strategy.getDefaultValue(cm, Boolean.class)); thrown.expect(NoDefaultValueException.class); strategy.getDefaultValue(cm, boolean.class); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_UniqueDate() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); for (int i = 0; i < 200; i++) { assertEquals(i, strategy.getDefaultValue(cm, Date.class).getTime()); } }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_UniqueZonedDateTime() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); for (int i = 0; i < 200; i++) { assertEquals(ZonedDateTime.ofInstant(Instant.ofEpochMilli(i), ZoneId.systemDefault()), strategy.getDefaultValue(cm, ZonedDateTime.class)); } }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testGetDataType() throws Exception { Assert.assertEquals("java.lang.Long", provider.getCanonicalDataTypeName(getColumn("REF_ENTITY_3", "ID"))); Assert.assertEquals("long", provider.getCanonicalDataTypeName(getColumn("REFERENCEDENTITY1", "ID"))); Assert.assertEquals("java.lang.Integer", provider.getCanonicalDataTypeName(getColumn("REFERENCEDENTITY1", "SUBENTITY_ID"))); }
@Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } } JpaMetamodelRedGProvider(Metamodel metaModel); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
@Test public void testStrategy_UniqueEnum() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); for (int i = 0; i < TestEnum.values().length; i++) { assertEquals(TestEnum.values()[i], strategy.getDefaultValue(cm, TestEnum.class)); } thrown.expect(NoDefaultValueException.class); strategy.getDefaultValue(cm, TestEnum.class); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_Enum() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(false); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); for (int i = 0; i < 100; i++) { assertEquals(TestEnum.A, strategy.getDefaultValue(cm, TestEnum.class)); } }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_NoUniquePossible() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); thrown.expect(NoDefaultValueException.class); strategy.getDefaultValue(cm, Object.class); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_EmptyUniqueEnum() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(true); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); thrown.expect(NoDefaultValueException.class); strategy.getDefaultValue(cm, EmptyEnum.class); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testStrategy_EmptyEnum() { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setUnique(false); final DefaultDefaultValueStrategy strategy = new DefaultDefaultValueStrategy(); thrown.expect(NoDefaultValueException.class); strategy.getDefaultValue(cm, EmptyEnum.class); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueStrategy implements DefaultValueStrategy { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (!columnModel.isNotNull()) { return null; } if (columnModel.isUnique()) { long counter = this.uniqueCounter.compute( columnModel.getDbFullTableName() + "." + columnModel.getDbName(), (k, v) -> (v == null) ? 0L : v + 1); if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } if (type.getEnumConstants().length <= counter) { throw new NoDefaultValueException("Cannot generate a unique enum value. No more different enums! If this enum is part of a bigger unique index, you cannot use the DefaultDefaultValueService anymore."); } return type.getEnumConstants()[(int) counter]; } else { return getUniqueValue(counter, type); } } else { if (type.isEnum()) { if (type.getEnumConstants().length == 0) { throw new NoDefaultValueException("Cannot pick a value from an empty enum!"); } return type.getEnumConstants()[0]; } else { Object defaultValue = DefaultDefaultValueStrategy.defaultMappings.get(type); if (defaultValue != null) { return (T) defaultValue; } else { throw new NoDefaultValueException("No default value for type " + type); } } } } @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void getDefaultValue() throws Exception { StaticNumberProvider staticNumberProvider = new StaticNumberProvider(12L); Assert.assertEquals(12d, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), double.class), 0d); Assert.assertEquals(12f, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), float.class), 0f); Assert.assertEquals(12L, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), long.class).longValue()); Assert.assertEquals(12, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), int.class).intValue()); Assert.assertEquals((byte) 12, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), byte.class).byteValue()); Assert.assertEquals((short) 12, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), short.class).shortValue()); Assert.assertEquals(new BigDecimal(12), staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), BigDecimal.class)); Assert.assertEquals(12d, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), Double.class), 0d); Assert.assertEquals(12f, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), Float.class), 0f); Assert.assertEquals(12L, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), Long.class).longValue()); Assert.assertEquals(12, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), Integer.class).intValue()); Assert.assertEquals((byte) 12, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), Byte.class).byteValue()); Assert.assertEquals((short) 12, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), Short.class).shortValue()); Assert.assertEquals(12, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), AtomicInteger.class).get()); Assert.assertEquals(12L, staticNumberProvider.getDefaultValue(Mockito.mock(ColumnModel.class), AtomicLong.class).get()); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return convertNumber(number, type); }
StaticNumberProvider extends NumberProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return convertNumber(number, type); } }
StaticNumberProvider extends NumberProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return convertNumber(number, type); } StaticNumberProvider(long value); StaticNumberProvider(BigDecimal value); }
StaticNumberProvider extends NumberProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return convertNumber(number, type); } StaticNumberProvider(long value); StaticNumberProvider(BigDecimal value); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
StaticNumberProvider extends NumberProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return convertNumber(number, type); } StaticNumberProvider(long value); StaticNumberProvider(BigDecimal value); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void tableName() { final ColumnModel cm = TestUtils.getCM("", "table", "", String.class, true); final ColumnModel cm2 = TestUtils.getCM("", "wrong", "", String.class, true); assertThat(Matchers.tableName("table"::equals)) .accepts(cm) .rejects(cm2); }
public static Predicate<ColumnModel> tableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbTableName()); }
Matchers { public static Predicate<ColumnModel> tableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbTableName()); } }
Matchers { public static Predicate<ColumnModel> tableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbTableName()); } private Matchers(); }
Matchers { public static Predicate<ColumnModel> tableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbTableName()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> tableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbTableName()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void fullTableName() { final ColumnModel cm = TestUtils.getCM("table", "", "", String.class, true); final ColumnModel cm2 = TestUtils.getCM("wrong", "", "", String.class, true); assertThat(Matchers.fullTableName("table"::equals)) .accepts(cm) .rejects(cm2); }
public static Predicate<ColumnModel> fullTableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbFullTableName()); }
Matchers { public static Predicate<ColumnModel> fullTableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbFullTableName()); } }
Matchers { public static Predicate<ColumnModel> fullTableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbFullTableName()); } private Matchers(); }
Matchers { public static Predicate<ColumnModel> fullTableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbFullTableName()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> fullTableName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbFullTableName()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void columnName() { final ColumnModel cm = TestUtils.getCM("", "", "column", String.class, true); final ColumnModel cm2 = TestUtils.getCM("", "", "wrong", String.class, true); assertThat(Matchers.columnName("column"::equals)) .accepts(cm) .rejects(cm2); }
public static Predicate<ColumnModel> columnName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbName()); }
Matchers { public static Predicate<ColumnModel> columnName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbName()); } }
Matchers { public static Predicate<ColumnModel> columnName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbName()); } private Matchers(); }
Matchers { public static Predicate<ColumnModel> columnName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbName()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> columnName(final Predicate<String> condition) { return (cM) -> condition.test(cM.getDbName()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void type() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); final ColumnModel cm2 = TestUtils.getCM("", "", "", Integer.class, true); assertThat(Matchers.type(String.class::equals)) .accepts(cm) .rejects(cm2); }
public static Predicate<ColumnModel> type(final Predicate<Class<?>> condition) { return (cM) -> condition.test(cM.getJavaTypeAsClass()); }
Matchers { public static Predicate<ColumnModel> type(final Predicate<Class<?>> condition) { return (cM) -> condition.test(cM.getJavaTypeAsClass()); } }
Matchers { public static Predicate<ColumnModel> type(final Predicate<Class<?>> condition) { return (cM) -> condition.test(cM.getJavaTypeAsClass()); } private Matchers(); }
Matchers { public static Predicate<ColumnModel> type(final Predicate<Class<?>> condition) { return (cM) -> condition.test(cM.getJavaTypeAsClass()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> type(final Predicate<Class<?>> condition) { return (cM) -> condition.test(cM.getJavaTypeAsClass()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void testGetDataTypeForEmbedded() throws Exception { Assert.assertEquals("long", provider.getCanonicalDataTypeName(getColumn("REFERENCEDENTITY1", "EMBEDDEDLONGATTRIBUTE"))); }
@Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } } JpaMetamodelRedGProvider(Metamodel metaModel); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().getForeignKeys().stream() .flatMap(foreignKeyColumnReferences -> foreignKeyColumnReferences.getColumnReferences().stream()) .filter(foreignKeyColumnReference -> foreignKeyColumnReference.getForeignKeyColumn().getName().equals(column.getName())) .findFirst(); if (foreignKeyColumnReferenceOptional.isPresent()) { ForeignKeyColumnReference ref = foreignKeyColumnReferenceOptional.get(); SingularAttribute targetSingularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(ref.getPrimaryKeyColumn().getParent().getName().toUpperCase(), ref.getPrimaryKeyColumn().getName().toUpperCase())); if (targetSingularAttribute != null) { return targetSingularAttribute.getJavaType().getCanonicalName(); } else { LOG.warn("Could not find target singular attribute for column " + column.getParent().getName() + "." + column.getName()); return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } else { singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(column.getParent().getName().toUpperCase(), column.getName().toUpperCase())); if (singularAttribute != null) { return singularAttribute.getJavaType().getCanonicalName(); } else { return fallbackDataTypeProvider.getCanonicalDataTypeName(column); } } } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
@Test public void notNull() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); final ColumnModel cm2 = TestUtils.getCM("", "", "", String.class, false); assertThat(Matchers.notNull(Boolean::booleanValue)) .accepts(cm) .rejects(cm2); }
public static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition) { return (cM) -> condition.test(cM.isNotNull()); }
Matchers { public static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition) { return (cM) -> condition.test(cM.isNotNull()); } }
Matchers { public static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition) { return (cM) -> condition.test(cM.isNotNull()); } private Matchers(); }
Matchers { public static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition) { return (cM) -> condition.test(cM.isNotNull()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition) { return (cM) -> condition.test(cM.isNotNull()); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void isNotNull() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); final ColumnModel cm2 = TestUtils.getCM("", "", "", String.class, false); assertThat(Matchers.isNotNull()) .accepts(cm) .rejects(cm2); }
public static Predicate<ColumnModel> isNotNull() { return ColumnModel::isNotNull; }
Matchers { public static Predicate<ColumnModel> isNotNull() { return ColumnModel::isNotNull; } }
Matchers { public static Predicate<ColumnModel> isNotNull() { return ColumnModel::isNotNull; } private Matchers(); }
Matchers { public static Predicate<ColumnModel> isNotNull() { return ColumnModel::isNotNull; } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> isNotNull() { return ColumnModel::isNotNull; } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void isUnique() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); cm.setUnique(true); final ColumnModel cm2 = TestUtils.getCM("", "", "", String.class, false); cm2.setUnique(false); assertThat(Matchers.isUnique()) .accepts(cm) .rejects(cm2); }
public static Predicate<ColumnModel> isUnique() { return ColumnModel::isUnique; }
Matchers { public static Predicate<ColumnModel> isUnique() { return ColumnModel::isUnique; } }
Matchers { public static Predicate<ColumnModel> isUnique() { return ColumnModel::isUnique; } private Matchers(); }
Matchers { public static Predicate<ColumnModel> isUnique() { return ColumnModel::isUnique; } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> isUnique() { return ColumnModel::isUnique; } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void isPrimary() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); cm.setPartOfPrimaryKey(true); final ColumnModel cm2 = TestUtils.getCM("", "", "", String.class, false); cm2.setPartOfPrimaryKey(false); assertThat(Matchers.isPrimary()) .accepts(cm) .rejects(cm2); }
public static Predicate<ColumnModel> isPrimary() { return ColumnModel::isPartOfPrimaryKey; }
Matchers { public static Predicate<ColumnModel> isPrimary() { return ColumnModel::isPartOfPrimaryKey; } }
Matchers { public static Predicate<ColumnModel> isPrimary() { return ColumnModel::isPartOfPrimaryKey; } private Matchers(); }
Matchers { public static Predicate<ColumnModel> isPrimary() { return ColumnModel::isPartOfPrimaryKey; } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> isPrimary() { return ColumnModel::isPartOfPrimaryKey; } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void allOf() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); cm.setPartOfPrimaryKey(true); cm.setUnique(true); final ColumnModel cm2 = TestUtils.getCM("", "", "", String.class, false); cm2.setPartOfPrimaryKey(false); cm2.setUnique(false); final ColumnModel cm3 = TestUtils.getCM("", "", "", String.class, false); cm3.setPartOfPrimaryKey(true); cm3.setUnique(false); final ColumnModel cm4 = TestUtils.getCM("", "", "", String.class, false); cm4.setPartOfPrimaryKey(false); cm4.setUnique(true); assertThat(Matchers.allOf(Matchers.isPrimary(), Matchers.isUnique())) .accepts(cm) .rejects(cm2, cm3, cm4); }
@Deprecated public static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .allMatch(c -> c.test(cM)); }
Matchers { @Deprecated public static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .allMatch(c -> c.test(cM)); } }
Matchers { @Deprecated public static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .allMatch(c -> c.test(cM)); } private Matchers(); }
Matchers { @Deprecated public static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .allMatch(c -> c.test(cM)); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { @Deprecated public static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .allMatch(c -> c.test(cM)); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void anyOf() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); cm.setPartOfPrimaryKey(true); cm.setUnique(true); final ColumnModel cm2 = TestUtils.getCM("", "", "", String.class, false); cm2.setPartOfPrimaryKey(false); cm2.setUnique(false); final ColumnModel cm3 = TestUtils.getCM("", "", "", String.class, false); cm3.setPartOfPrimaryKey(true); cm3.setUnique(false); final ColumnModel cm4 = TestUtils.getCM("", "", "", String.class, false); cm4.setPartOfPrimaryKey(false); cm4.setUnique(true); assertThat(Matchers.anyOf(Matchers.isPrimary(), Matchers.isUnique())) .accepts(cm, cm3, cm4) .rejects(cm2); }
@Deprecated public static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .anyMatch(c -> c.test(cM)); }
Matchers { @Deprecated public static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .anyMatch(c -> c.test(cM)); } }
Matchers { @Deprecated public static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .anyMatch(c -> c.test(cM)); } private Matchers(); }
Matchers { @Deprecated public static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .anyMatch(c -> c.test(cM)); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { @Deprecated public static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .anyMatch(c -> c.test(cM)); } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void oneOf() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); cm.setPartOfPrimaryKey(true); cm.setUnique(true); final ColumnModel cm2 = TestUtils.getCM("", "", "", String.class, false); cm2.setPartOfPrimaryKey(false); cm2.setUnique(false); final ColumnModel cm3 = TestUtils.getCM("", "", "", String.class, false); cm3.setPartOfPrimaryKey(true); cm3.setUnique(false); final ColumnModel cm4 = TestUtils.getCM("", "", "", String.class, false); cm4.setPartOfPrimaryKey(false); cm4.setUnique(true); assertThat(Matchers.oneOf(Matchers.isPrimary(), Matchers.isUnique())) .accepts(cm3, cm4) .rejects(cm2, cm); }
public static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .map(c -> c.test(cM)).filter(b -> b).count() == 1; }
Matchers { public static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .map(c -> c.test(cM)).filter(b -> b).count() == 1; } }
Matchers { public static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .map(c -> c.test(cM)).filter(b -> b).count() == 1; } private Matchers(); }
Matchers { public static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .map(c -> c.test(cM)).filter(b -> b).count() == 1; } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
Matchers { public static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions) { return (cM) -> Arrays.stream(conditions) .map(c -> c.test(cM)).filter(b -> b).count() == 1; } private Matchers(); static Predicate<ColumnModel> tableName(final Predicate<String> condition); static Predicate<ColumnModel> fullTableName(final Predicate<String> condition); static Predicate<ColumnModel> columnName(final Predicate<String> condition); static Predicate<ColumnModel> type(final Predicate<Class<?>> condition); static Predicate<ColumnModel> notNull(final Predicate<Boolean> condition); static Predicate<ColumnModel> isNotNull(); static Predicate<ColumnModel> isUnique(); static Predicate<ColumnModel> isPrimary(); @Deprecated static Predicate<ColumnModel> allOf(final Predicate<ColumnModel>... conditions); @Deprecated static Predicate<ColumnModel> anyOf(final Predicate<ColumnModel>... conditions); static Predicate<ColumnModel> oneOf(final Predicate<ColumnModel>... conditions); }
@Test public void eq() { assertThat(Conditions.eq("A")) .accepts("A") .rejects("B", "C"); }
public static <T> Predicate<T> eq(T value) { return value::equals; }
Conditions { public static <T> Predicate<T> eq(T value) { return value::equals; } }
Conditions { public static <T> Predicate<T> eq(T value) { return value::equals; } private Conditions(); }
Conditions { public static <T> Predicate<T> eq(T value) { return value::equals; } private Conditions(); static Predicate<T> eq(T value); static Predicate<T> neq(T value); static Predicate<String> contains(String value); static Predicate<String> matchesRegex(String regex); }
Conditions { public static <T> Predicate<T> eq(T value) { return value::equals; } private Conditions(); static Predicate<T> eq(T value); static Predicate<T> neq(T value); static Predicate<String> contains(String value); static Predicate<String> matchesRegex(String regex); }
@Test public void neq() { assertThat(Conditions.neq("A")) .rejects("A") .accepts("B", "C"); }
public static <T> Predicate<T> neq(T value) { return (d) -> !value.equals(d); }
Conditions { public static <T> Predicate<T> neq(T value) { return (d) -> !value.equals(d); } }
Conditions { public static <T> Predicate<T> neq(T value) { return (d) -> !value.equals(d); } private Conditions(); }
Conditions { public static <T> Predicate<T> neq(T value) { return (d) -> !value.equals(d); } private Conditions(); static Predicate<T> eq(T value); static Predicate<T> neq(T value); static Predicate<String> contains(String value); static Predicate<String> matchesRegex(String regex); }
Conditions { public static <T> Predicate<T> neq(T value) { return (d) -> !value.equals(d); } private Conditions(); static Predicate<T> eq(T value); static Predicate<T> neq(T value); static Predicate<String> contains(String value); static Predicate<String> matchesRegex(String regex); }
@Test public void contains() { assertThat(Conditions.contains("A")) .accepts("A", "AB", "BA", "ABBA") .rejects("B", "BODO"); }
public static Predicate<String> contains(String value) { return (d) -> d.contains(value); }
Conditions { public static Predicate<String> contains(String value) { return (d) -> d.contains(value); } }
Conditions { public static Predicate<String> contains(String value) { return (d) -> d.contains(value); } private Conditions(); }
Conditions { public static Predicate<String> contains(String value) { return (d) -> d.contains(value); } private Conditions(); static Predicate<T> eq(T value); static Predicate<T> neq(T value); static Predicate<String> contains(String value); static Predicate<String> matchesRegex(String regex); }
Conditions { public static Predicate<String> contains(String value) { return (d) -> d.contains(value); } private Conditions(); static Predicate<T> eq(T value); static Predicate<T> neq(T value); static Predicate<String> contains(String value); static Predicate<String> matchesRegex(String regex); }
@Test public void testGetMethodNameForForeignKeyColumn() throws Exception { Assert.assertEquals("refEntity2Id2", provider.getMethodNameForForeignKeyColumn( getForeignKey("REFERENCEDENTITY1", "REFENTITY2_ID_2"), getColumn("REF_ENTITY_2", "ID_2"), getColumn("REFERENCEDENTITY1", "REFENTITY2_ID_2")) ); Assert.assertEquals("referencedEntity2WithExpliciteJoinColumnsId2", provider.getMethodNameForForeignKeyColumn( getForeignKey("REFERENCEDENTITY1", "REF_2_ID2"), getColumn("REF_ENTITY_2", "ID_2"), getColumn("REFERENCEDENTITY1", "REF_2_ID2")) ); }
@Override public String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn) { String referenceMethodName = getMethodNameForReference(foreignKey); String primaryKeyColumnName = foreignKey.getColumnReferences().stream() .filter(columnReference -> columnReference.getPrimaryKeyColumn().getName().equals(primaryKeyColumn.getName())) .map(columnReference -> columnReference.getPrimaryKeyColumn().getName()) .findFirst().orElse("asdf"); return referenceMethodName + NameUtils.firstCharacterToUpperCase(DefaultNameProvider.convertToJavaName(primaryKeyColumnName)); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn) { String referenceMethodName = getMethodNameForReference(foreignKey); String primaryKeyColumnName = foreignKey.getColumnReferences().stream() .filter(columnReference -> columnReference.getPrimaryKeyColumn().getName().equals(primaryKeyColumn.getName())) .map(columnReference -> columnReference.getPrimaryKeyColumn().getName()) .findFirst().orElse("asdf"); return referenceMethodName + NameUtils.firstCharacterToUpperCase(DefaultNameProvider.convertToJavaName(primaryKeyColumnName)); } }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn) { String referenceMethodName = getMethodNameForReference(foreignKey); String primaryKeyColumnName = foreignKey.getColumnReferences().stream() .filter(columnReference -> columnReference.getPrimaryKeyColumn().getName().equals(primaryKeyColumn.getName())) .map(columnReference -> columnReference.getPrimaryKeyColumn().getName()) .findFirst().orElse("asdf"); return referenceMethodName + NameUtils.firstCharacterToUpperCase(DefaultNameProvider.convertToJavaName(primaryKeyColumnName)); } JpaMetamodelRedGProvider(Metamodel metaModel); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn) { String referenceMethodName = getMethodNameForReference(foreignKey); String primaryKeyColumnName = foreignKey.getColumnReferences().stream() .filter(columnReference -> columnReference.getPrimaryKeyColumn().getName().equals(primaryKeyColumn.getName())) .map(columnReference -> columnReference.getPrimaryKeyColumn().getName()) .findFirst().orElse("asdf"); return referenceMethodName + NameUtils.firstCharacterToUpperCase(DefaultNameProvider.convertToJavaName(primaryKeyColumnName)); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn) { String referenceMethodName = getMethodNameForReference(foreignKey); String primaryKeyColumnName = foreignKey.getColumnReferences().stream() .filter(columnReference -> columnReference.getPrimaryKeyColumn().getName().equals(primaryKeyColumn.getName())) .map(columnReference -> columnReference.getPrimaryKeyColumn().getName()) .findFirst().orElse("asdf"); return referenceMethodName + NameUtils.firstCharacterToUpperCase(DefaultNameProvider.convertToJavaName(primaryKeyColumnName)); } JpaMetamodelRedGProvider(Metamodel metaModel); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName, String hibernateDialect); static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName); @Override String getClassNameForTable(Table table); @Override String getMethodNameForColumn(schemacrawler.schema.Column column); @Override String getMethodNameForForeignKeyColumn(ForeignKey foreignKey, schemacrawler.schema.Column primaryKeyColumn, schemacrawler.schema.Column foreignKeyColumn); @Override String getMethodNameForReference(ForeignKey foreignKey); @Override String getMethodNameForIncomingForeignKey(ForeignKey foreignKey); @Override String getCanonicalDataTypeName(schemacrawler.schema.Column column); void setFallbackNameProvider(NameProvider fallbackNameProvider); void setFallbackDataTypeProvider(DataTypeProvider fallbackDataTypeProvider); }
@Test public void matchesRegex() { assertThat(Conditions.matchesRegex("Hallo.+")) .accepts("Hallo Welt", "Hallo BTC") .rejects("Hello World"); }
public static Predicate<String> matchesRegex(String regex) { return (d) -> d.matches(regex); }
Conditions { public static Predicate<String> matchesRegex(String regex) { return (d) -> d.matches(regex); } }
Conditions { public static Predicate<String> matchesRegex(String regex) { return (d) -> d.matches(regex); } private Conditions(); }
Conditions { public static Predicate<String> matchesRegex(String regex) { return (d) -> d.matches(regex); } private Conditions(); static Predicate<T> eq(T value); static Predicate<T> neq(T value); static Predicate<String> contains(String value); static Predicate<String> matchesRegex(String regex); }
Conditions { public static Predicate<String> matchesRegex(String regex) { return (d) -> d.matches(regex); } private Conditions(); static Predicate<T> eq(T value); static Predicate<T> neq(T value); static Predicate<String> contains(String value); static Predicate<String> matchesRegex(String regex); }
@Test public void testMatchAll() throws Exception { ConditionalProvider provider = new ConditionalProvider(new DefaultDefaultValueProvider(), ".*", ".*", ".*"); assertThat(provider.willProvide(getModel("A", "B", "C.B"))).isTrue(); assertThat(provider.willProvide(getModel("X", "Y", "Z.Y"))).isTrue(); }
@Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testMatchPrefix() throws Exception { ConditionalProvider provider = new ConditionalProvider(new DefaultDefaultValueProvider(), ".*\\.REDG.*", "REDG.*", "REDG.*"); assertThat(provider.willProvide(getModel("A", "B", "C.B"))).isFalse(); assertThat(provider.willProvide(getModel("X", "Y", "Z.Y"))).isFalse(); assertThat(provider.willProvide(getModel("REDG_A", "REDG_B", "C.REDG_B"))).isTrue(); assertThat(provider.willProvide(getModel("A", "REDG_B", "C.REDG_B"))).isFalse(); assertThat(provider.willProvide(getModel("REDG_A", "A", "C.REDG_B"))).isFalse(); assertThat(provider.willProvide(getModel("REDG_A", "REDG_B", "C.B"))).isFalse(); assertThat(provider.willProvide(getModel("REDG_A", "B", "C.B"))).isFalse(); assertThat(provider.willProvide(getModel("A", "REDG_B", "C.B"))).isFalse(); assertThat(provider.willProvide(getModel("A", "B", "C.REDG_B"))).isFalse(); }
@Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testMatchFullTable() throws Exception { ConditionalProvider provider = new ConditionalProvider(new DefaultDefaultValueProvider(), ".*\\.REDG.*", null, null); assertThat(provider.willProvide(getModel("A", "B", "C.B"))).isFalse(); assertThat(provider.willProvide(getModel("X", "Y", "Z.Y"))).isFalse(); assertThat(provider.willProvide(getModel("REDG_A", "REDG_B", "C.REDG_B"))).isTrue(); assertThat(provider.willProvide(getModel("A", "B", "C.REDG_B"))).isTrue(); assertThat(provider.willProvide(getModel("C", "D", "F.REDG_A"))).isTrue(); }
@Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testMatchTable() throws Exception { ConditionalProvider provider = new ConditionalProvider(new DefaultDefaultValueProvider(), null, "REDG.*", null); assertThat(provider.willProvide(getModel("A", "B", "C.B"))).isFalse(); assertThat(provider.willProvide(getModel("X", "Y", "Z.Y"))).isFalse(); assertThat(provider.willProvide(getModel("REDG_A", "REDG_B", "C.REDG_B"))).isTrue(); assertThat(provider.willProvide(getModel("A", "REDG_B", "C.B"))).isTrue(); assertThat(provider.willProvide(getModel("C", "REDG_D", "F.A"))).isTrue(); }
@Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testMatchColumn() throws Exception { ConditionalProvider provider = new ConditionalProvider(new DefaultDefaultValueProvider(), null, null, "REDG.*"); assertThat(provider.willProvide(getModel("A", "B", "C.B"))).isFalse(); assertThat(provider.willProvide(getModel("X", "Y", "Z.Y"))).isFalse(); assertThat(provider.willProvide(getModel("REDG_A", "REDG_B", "C.REDG_B"))).isTrue(); assertThat(provider.willProvide(getModel("REDG_A", "B", "C.B"))).isTrue(); assertThat(provider.willProvide(getModel("REDG_C", "D", "F.A"))).isTrue(); }
@Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { if (this.fullTablePattern != null && !this.fullTablePattern.matcher(columnModel.getDbFullTableName()).matches()) { return false; } else if (this.tablePattern != null && !this.tablePattern.matcher(columnModel.getDbTableName()).matches()) { return false; } else if (this.columnPattern != null && !this.columnPattern.matcher(columnModel.getDbName()).matches()) { return false; } else { return internalProvider.willProvide(columnModel); } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testGetDefaultValue() { ConditionalProvider provider = new ConditionalProvider(new NoProvider(), null, null, null); assertThat(provider.getDefaultValue(getModel("A", "B", "C.B"), String.class)).isNull(); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (willProvide(columnModel)) { return internalProvider.getDefaultValue(columnModel, type); } else { return null; } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (willProvide(columnModel)) { return internalProvider.getDefaultValue(columnModel, type); } else { return null; } } }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (willProvide(columnModel)) { return internalProvider.getDefaultValue(columnModel, type); } else { return null; } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (willProvide(columnModel)) { return internalProvider.getDefaultValue(columnModel, type); } else { return null; } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
ConditionalProvider implements PluggableDefaultValueProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { if (willProvide(columnModel)) { return internalProvider.getDefaultValue(columnModel, type); } else { return null; } } ConditionalProvider(final PluggableDefaultValueProvider internalProvider, final String fullTableRegex, final String tableRegex, final String columnRegex); @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void willProvide() { assertThat(new DefaultDefaultValueProvider().willProvide(null)).isTrue(); assertThat(new DefaultDefaultValueProvider().willProvide(mock(ColumnModel.class))).isTrue(); }
@Override public boolean willProvide(final ColumnModel columnModel) { return true; }
DefaultDefaultValueProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { return true; } }
DefaultDefaultValueProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { return true; } }
DefaultDefaultValueProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { return true; } @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueProvider implements PluggableDefaultValueProvider { @Override public boolean willProvide(final ColumnModel columnModel) { return true; } @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void getDefaultValue() { DefaultDefaultValueProvider provider = new DefaultDefaultValueProvider(); ColumnModel columnModel = new ColumnModel(); columnModel.setNotNull(false); assertThat(provider.getDefaultValue(columnModel, String.class)).isNull(); DefaultDefaultValueStrategyTest.defaultMappings.forEach((key, value) -> { final ColumnModel cm = new ColumnModel(); cm.setNotNull(true); cm.setJavaTypeName(key.getName()); assertEquals(value, provider.getDefaultValue(cm, key)); }); }
@Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return valueStrategy.getDefaultValue(columnModel, type); }
DefaultDefaultValueProvider implements PluggableDefaultValueProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return valueStrategy.getDefaultValue(columnModel, type); } }
DefaultDefaultValueProvider implements PluggableDefaultValueProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return valueStrategy.getDefaultValue(columnModel, type); } }
DefaultDefaultValueProvider implements PluggableDefaultValueProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return valueStrategy.getDefaultValue(columnModel, type); } @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
DefaultDefaultValueProvider implements PluggableDefaultValueProvider { @Override public <T> T getDefaultValue(final ColumnModel columnModel, final Class<T> type) { return valueStrategy.getDefaultValue(columnModel, type); } @Override boolean willProvide(final ColumnModel columnModel); @Override T getDefaultValue(final ColumnModel columnModel, final Class<T> type); }
@Test public void testGetEntities() throws Exception { MockRedG mockRedG = new MockRedG(); RedGEntity e = new MockEntity1(); mockRedG.addEntity(e); assertThat(mockRedG.getEntities()).containsExactly(e); }
public List<RedGEntity> getEntities() { return Collections.unmodifiableList(entities); }
AbstractRedG { public List<RedGEntity> getEntities() { return Collections.unmodifiableList(entities); } }
AbstractRedG { public List<RedGEntity> getEntities() { return Collections.unmodifiableList(entities); } }
AbstractRedG { public List<RedGEntity> getEntities() { return Collections.unmodifiableList(entities); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
AbstractRedG { public List<RedGEntity> getEntities() { return Collections.unmodifiableList(entities); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
@Test public void testDeserializeXml() throws Exception { InputStream stream = this.getClass().getResourceAsStream("XmlFileDataTypeProviderTest.xml"); InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); TypeMappings mappings = XmlFileDataTypeProvider.deserializeXml(reader); Assert.assertEquals(mappings.getTableTypeMappings().size(), 1); TableTypeMapping tableTypeMapping = mappings.getTableTypeMappings().get(0); Assert.assertEquals(tableTypeMapping.getTableName(), "MY_TABLE"); Assert.assertEquals(tableTypeMapping.getColumnTypeMappings().size(), 1); ColumnTypeMapping columnTypeMapping = tableTypeMapping.getColumnTypeMappings().get(0); Assert.assertEquals(columnTypeMapping.getColumnName(), "MY_FLAG"); Assert.assertEquals(columnTypeMapping.getJavaType(), "java.lang.Boolean"); Assert.assertEquals(mappings.getDefaultTypeMappings().size(), 1); DefaultTypeMapping defaultTypeMapping = mappings.getDefaultTypeMappings().get(0); Assert.assertEquals(defaultTypeMapping.getSqlType(), "DECIMAL(1)"); Assert.assertEquals(defaultTypeMapping.getJavaType(), "java.lang.Boolean"); }
static TypeMappings deserializeXml(Reader xmlReader) { TypeMappings typeMappings; XStream xStream = createXStream(); typeMappings = (TypeMappings) xStream.fromXML(xmlReader, new TypeMappings()); return typeMappings; }
XmlFileDataTypeProvider implements DataTypeProvider { static TypeMappings deserializeXml(Reader xmlReader) { TypeMappings typeMappings; XStream xStream = createXStream(); typeMappings = (TypeMappings) xStream.fromXML(xmlReader, new TypeMappings()); return typeMappings; } }
XmlFileDataTypeProvider implements DataTypeProvider { static TypeMappings deserializeXml(Reader xmlReader) { TypeMappings typeMappings; XStream xStream = createXStream(); typeMappings = (TypeMappings) xStream.fromXML(xmlReader, new TypeMappings()); return typeMappings; } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); }
XmlFileDataTypeProvider implements DataTypeProvider { static TypeMappings deserializeXml(Reader xmlReader) { TypeMappings typeMappings; XStream xStream = createXStream(); typeMappings = (TypeMappings) xStream.fromXML(xmlReader, new TypeMappings()); return typeMappings; } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
XmlFileDataTypeProvider implements DataTypeProvider { static TypeMappings deserializeXml(Reader xmlReader) { TypeMappings typeMappings; XStream xStream = createXStream(); typeMappings = (TypeMappings) xStream.fromXML(xmlReader, new TypeMappings()); return typeMappings; } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
@Test public void testSetDummyFactory() throws Exception { MockRedG mockRedG = new MockRedG(); DummyFactory df = new DefaultDummyFactory(); mockRedG.setDummyFactory(df); assertThat(mockRedG.getDummyFactory()).isEqualTo(df); mockRedG.setDummyFactory(null); assertThat(mockRedG.getDummyFactory()).isInstanceOf(DefaultDummyFactory.class); }
public void setDummyFactory(final DummyFactory dummyFactory) { if (entities.size() > 0) { throw new IllegalStateException("The dummy factory cannot be changed after an entity was generated!"); } if (dummyFactory == null) { this.dummyFactory = new DefaultDummyFactory(); } else { this.dummyFactory = dummyFactory; } }
AbstractRedG { public void setDummyFactory(final DummyFactory dummyFactory) { if (entities.size() > 0) { throw new IllegalStateException("The dummy factory cannot be changed after an entity was generated!"); } if (dummyFactory == null) { this.dummyFactory = new DefaultDummyFactory(); } else { this.dummyFactory = dummyFactory; } } }
AbstractRedG { public void setDummyFactory(final DummyFactory dummyFactory) { if (entities.size() > 0) { throw new IllegalStateException("The dummy factory cannot be changed after an entity was generated!"); } if (dummyFactory == null) { this.dummyFactory = new DefaultDummyFactory(); } else { this.dummyFactory = dummyFactory; } } }
AbstractRedG { public void setDummyFactory(final DummyFactory dummyFactory) { if (entities.size() > 0) { throw new IllegalStateException("The dummy factory cannot be changed after an entity was generated!"); } if (dummyFactory == null) { this.dummyFactory = new DefaultDummyFactory(); } else { this.dummyFactory = dummyFactory; } } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
AbstractRedG { public void setDummyFactory(final DummyFactory dummyFactory) { if (entities.size() > 0) { throw new IllegalStateException("The dummy factory cannot be changed after an entity was generated!"); } if (dummyFactory == null) { this.dummyFactory = new DefaultDummyFactory(); } else { this.dummyFactory = dummyFactory; } } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
@Test public void testFindSingleEntity() { MockRedG mockRedG = new MockRedG(); MockEntity1 entity1 = new MockEntity1(); MockEntity2 entity2 = new MockEntity2(); mockRedG.addEntity(entity1); mockRedG.addEntity(entity2); assertEquals(entity1, mockRedG.findSingleEntity(MockEntity1.class, e -> e.toString().equals("MockEntity1"))); assertEquals(entity2, mockRedG.findSingleEntity(MockEntity2.class, e -> e.toString().equals("MockEntity2"))); boolean exceptionThrown = false; try { assertNull(mockRedG.findSingleEntity(MockEntity1.class, e -> false)); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); }
public <T extends RedGEntity> T findSingleEntity(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Could not find an entity that satisfies the filter!")); }
AbstractRedG { public <T extends RedGEntity> T findSingleEntity(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Could not find an entity that satisfies the filter!")); } }
AbstractRedG { public <T extends RedGEntity> T findSingleEntity(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Could not find an entity that satisfies the filter!")); } }
AbstractRedG { public <T extends RedGEntity> T findSingleEntity(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Could not find an entity that satisfies the filter!")); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
AbstractRedG { public <T extends RedGEntity> T findSingleEntity(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Could not find an entity that satisfies the filter!")); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
@Test public void testFindAllObjects() { MockRedG mockRedG = new MockRedG(); List<MockEntity1> entities = IntStream.rangeClosed(1, 20).mapToObj(i -> new MockEntity1()).collect(Collectors.toList()); entities.forEach(mockRedG::addEntity); assertEquals(entities, mockRedG.findEntities(MockEntity1.class, e -> true)); assertTrue(mockRedG.findEntities(MockEntity2.class, e -> true).isEmpty()); }
public <T extends RedGEntity> List<T> findEntities(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .collect(Collectors.toList()); }
AbstractRedG { public <T extends RedGEntity> List<T> findEntities(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .collect(Collectors.toList()); } }
AbstractRedG { public <T extends RedGEntity> List<T> findEntities(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .collect(Collectors.toList()); } }
AbstractRedG { public <T extends RedGEntity> List<T> findEntities(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .collect(Collectors.toList()); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
AbstractRedG { public <T extends RedGEntity> List<T> findEntities(final Class<T> type, final Predicate<T> filter) { return this.entities.stream() .filter(obj -> Objects.equals(type, obj.getClass())) .map(type::cast) .filter(filter) .collect(Collectors.toList()); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
@Test public void testGenerateInsertStatements() { MockRedG mockRedG = new MockRedG(); List<MockEntity1> entities = IntStream.rangeClosed(1, 20).mapToObj(i -> new MockEntity1()).collect(Collectors.toList()); List<String> results = IntStream.rangeClosed(1, 20).mapToObj(i -> "INSERT").collect(Collectors.toList()); entities.forEach(mockRedG::addEntity); assertEquals(results, mockRedG.generateSQLStatements()); }
public List<String> generateSQLStatements() { return getEntitiesSortedForInsert().stream() .map(RedGEntity::getSQLString) .collect(Collectors.toList()); }
AbstractRedG { public List<String> generateSQLStatements() { return getEntitiesSortedForInsert().stream() .map(RedGEntity::getSQLString) .collect(Collectors.toList()); } }
AbstractRedG { public List<String> generateSQLStatements() { return getEntitiesSortedForInsert().stream() .map(RedGEntity::getSQLString) .collect(Collectors.toList()); } }
AbstractRedG { public List<String> generateSQLStatements() { return getEntitiesSortedForInsert().stream() .map(RedGEntity::getSQLString) .collect(Collectors.toList()); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
AbstractRedG { public List<String> generateSQLStatements() { return getEntitiesSortedForInsert().stream() .map(RedGEntity::getSQLString) .collect(Collectors.toList()); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
@Test public void testInsertConnection() throws Exception { Connection connection = getConnection("conn"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); List<MockEntity1> gObjects = IntStream.rangeClosed(1, 20).mapToObj(i -> new MockEntity1()).collect(Collectors.toList()); MockRedG mockRedG = new MockRedG(); gObjects.forEach(mockRedG::addEntity); mockRedG.insertDataIntoDatabase(connection); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM TEST"); rs.next(); assertEquals(20, rs.getInt(1)); }
public void insertDataIntoDatabase(final Connection connection) { RedGDatabaseUtil.insertDataIntoDatabase(getEntitiesSortedForInsert(), connection, preparedStatementParameterSetter); }
AbstractRedG { public void insertDataIntoDatabase(final Connection connection) { RedGDatabaseUtil.insertDataIntoDatabase(getEntitiesSortedForInsert(), connection, preparedStatementParameterSetter); } }
AbstractRedG { public void insertDataIntoDatabase(final Connection connection) { RedGDatabaseUtil.insertDataIntoDatabase(getEntitiesSortedForInsert(), connection, preparedStatementParameterSetter); } }
AbstractRedG { public void insertDataIntoDatabase(final Connection connection) { RedGDatabaseUtil.insertDataIntoDatabase(getEntitiesSortedForInsert(), connection, preparedStatementParameterSetter); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
AbstractRedG { public void insertDataIntoDatabase(final Connection connection) { RedGDatabaseUtil.insertDataIntoDatabase(getEntitiesSortedForInsert(), connection, preparedStatementParameterSetter); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); void setSqlValuesFormatter(final SQLValuesFormatter sqlValuesFormatter); PreparedStatementParameterSetter getPreparedStatementParameterSetter(); void setPreparedStatementParameterSetter(final PreparedStatementParameterSetter preparedStatementParameterSetter); DummyFactory getDummyFactory(); void setDummyFactory(final DummyFactory dummyFactory); List<String> generateSQLStatements(); void insertDataIntoDatabase(final Connection connection); T findSingleEntity(final Class<T> type, final Predicate<T> filter); List<T> findEntities(final Class<T> type, final Predicate<T> filter); List<RedGEntity> getEntities(); List<RedGEntity> getEntitiesSortedForInsert(); abstract String getVisualizationJson(); }
@Test public void testParseInstant() throws Exception { assertEquals(EXPECTED_DATETIME, DateConverter.parseInstant("2017-01-02T03:04:05.000Z", ZoneOffset.UTC).atOffset(ZoneOffset.UTC)); assertEquals(EXPECTED_DATETIME, DateConverter.parseInstant("2017-01-02T03:04:05", ZoneOffset.UTC).atOffset(ZoneOffset.UTC)); assertEquals(EXPECTED_DATE, DateConverter.parseInstant("2017-01-02", ZoneOffset.UTC).atOffset(ZoneOffset.UTC)); assertEquals(EXPECTED_DATETIME2, DateConverter.parseInstant("2017-01-02-03:00", ZoneOffset.UTC).atOffset(ZoneOffset.UTC)); }
static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } }
DateConverter { static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } } }
DateConverter { static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } } private DateConverter(); }
DateConverter { static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } } private DateConverter(); static T convertDate(String string, Class<T> type); static T convertDateFallbackToDefaultTimeZone(String string, Class<T> type); }
DateConverter { static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } } private DateConverter(); static T convertDate(String string, Class<T> type); static T convertDateFallbackToDefaultTimeZone(String string, Class<T> type); static final DateFormat ISO8601_DATE_TIME_FORMAT; static final DateFormat ISO8601_DATE_FORMAT; static final DateTimeFormatter ORACLE_LIKE_DATE; }
@Test public void testParseInstantWithNonIsoDate() throws Exception { assertEquals(EXPECTED_DATETIME, DateConverter.parseInstant("2017-01-02 03:04:05.000", ZoneOffset.UTC).atOffset(ZoneOffset.UTC)); }
static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } }
DateConverter { static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } } }
DateConverter { static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } } private DateConverter(); }
DateConverter { static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } } private DateConverter(); static T convertDate(String string, Class<T> type); static T convertDateFallbackToDefaultTimeZone(String string, Class<T> type); }
DateConverter { static Instant parseInstant(String string, ZoneId fallbackZoneId) { if (string.contains("T")) { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE_TIME.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return Instant.from(temporalAccessor); } else { return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } } else if (string.contains(" ")) { TemporalAccessor temporalAccessor = ORACLE_LIKE_DATE.parse(string); return LocalDateTime.from(temporalAccessor).atZone(fallbackZoneId).toInstant(); } else { TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_DATE.parse(string); if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) { return LocalDate.from(temporalAccessor).atTime(0, 0).atOffset(ZoneOffset.from(temporalAccessor)).toInstant(); } else { return LocalDate.from(temporalAccessor).atTime(0, 0).atZone(fallbackZoneId).toInstant(); } } } private DateConverter(); static T convertDate(String string, Class<T> type); static T convertDateFallbackToDefaultTimeZone(String string, Class<T> type); static final DateFormat ISO8601_DATE_TIME_FORMAT; static final DateFormat ISO8601_DATE_FORMAT; static final DateTimeFormatter ORACLE_LIKE_DATE; }
@Test public void testConvertDate() { assertEquals(new java.util.Date(0), DateConverter.convertDate("1970-01-01T00:00:00Z", java.util.Date.class)); assertEquals(new java.sql.Date(0), DateConverter.convertDate("1970-01-01T00:00:00Z", java.sql.Date.class)); assertEquals(new Time(0), DateConverter.convertDate("1970-01-01T00:00:00Z", Time.class)); assertEquals(new Timestamp(0), DateConverter.convertDate("1970-01-01T00:00:00Z", Timestamp.class)); assertEquals(LocalTime.of(0, 0, 0), DateConverter.convertDate("00:00:00", LocalTime.class)); assertEquals(LocalDate.of(1970, 1, 1), DateConverter.convertDate("1970-01-01", LocalDate.class)); assertEquals(LocalDateTime.of(1970, 1, 1, 0, 0, 0, 0), DateConverter.convertDate("1970-01-01T00:00:00", LocalDateTime.class)); assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC), DateConverter.convertDate("1970-01-01T00:00:00Z", ZonedDateTime.class)); assertEquals(OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC), DateConverter.convertDate("1970-01-01T00:00:00Z", OffsetDateTime.class)); assertEquals(OffsetTime.of(0, 0, 0, 0, ZoneOffset.UTC), DateConverter.convertDate("00:00:00Z", OffsetTime.class)); assertNull(DateConverter.convertDate("asdf", String.class)); assertEquals(new java.util.Date(0), DateConverter.convertDateFallbackToDefaultTimeZone("1970-01-01T00:00:00Z", java.util.Date.class)); }
public static <T> T convertDate(String string, Class<T> type) { return convertDateInternal(string, type, ZoneId.of("UTC")); }
DateConverter { public static <T> T convertDate(String string, Class<T> type) { return convertDateInternal(string, type, ZoneId.of("UTC")); } }
DateConverter { public static <T> T convertDate(String string, Class<T> type) { return convertDateInternal(string, type, ZoneId.of("UTC")); } private DateConverter(); }
DateConverter { public static <T> T convertDate(String string, Class<T> type) { return convertDateInternal(string, type, ZoneId.of("UTC")); } private DateConverter(); static T convertDate(String string, Class<T> type); static T convertDateFallbackToDefaultTimeZone(String string, Class<T> type); }
DateConverter { public static <T> T convertDate(String string, Class<T> type) { return convertDateInternal(string, type, ZoneId.of("UTC")); } private DateConverter(); static T convertDate(String string, Class<T> type); static T convertDateFallbackToDefaultTimeZone(String string, Class<T> type); static final DateFormat ISO8601_DATE_TIME_FORMAT; static final DateFormat ISO8601_DATE_FORMAT; static final DateTimeFormatter ORACLE_LIKE_DATE; }
@Test public void testFormatter() { DefaultSQLValuesFormatter formatter = new DefaultSQLValuesFormatter(); assertEquals("NULL", formatter.formatValue(null, "WHATEVER", "", "", "")); assertEquals("'Test'", formatter.formatValue("Test", "VARCHAR2", "", "", "")); assertEquals("'Here''s another test'", formatter.formatValue("Here's another test", "VARCHAR2", "", "", "")); assertEquals("1234", formatter.formatValue(1234, "DECIMAL", "", "", "")); assertEquals("1234.567", formatter.formatValue(1234.567, "DECIMAL", "", "", "")); assertEquals("123456789101112", formatter.formatValue(123456789101112L, "DECIMAL", "", "", "")); assertEquals("1", formatter.formatValue(true, "DECIMAL", "", "", "")); assertEquals("0", formatter.formatValue(false, "DECIMAL", "", "", "")); Date date = new Timestamp(448383839000L); assertEquals("TO_TIMESTAMP('" + date.toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF')", formatter.formatValue(date, "TIMESTAMP", "", "", "")); LocalDateTime time = LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC); assertEquals("TO_TIMESTAMP('1984-03-17 15:03:59.0', 'YYYY-MM-DD HH24:MI:SS.FF')", formatter.formatValue(time, "TIMESTAMP", "", "", "")); Object obj = new Object(); assertEquals(obj.toString(), formatter.formatValue(obj, "WHATEVER", "", "", "")); }
@Override public <T> String formatValue(final T value, final String sqlDataType, final String fullTableName, final String tableName, final String columnName) { if (value == null) { return "NULL"; } switch (sqlDataType) { case "VARCHAR": case "VARCHAR2": return "'" + value.toString().replace("'", "''") + "'"; case "DECIMAL": case "NUMBER": if (value instanceof Boolean) { return (Boolean) value ? "1" : "0"; } return value.toString(); default: break; } if (value instanceof java.util.Date) { Date d = (Date) value; Timestamp t = new Timestamp(d.getTime()); return "TO_TIMESTAMP('" + t.toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } if (value instanceof TemporalAccessor) { TemporalAccessor temporalAccessor = (TemporalAccessor) value; String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").format(temporalAccessor); return "TO_TIMESTAMP('" + s + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } LOG.warn("No mapping for {}. Returning result of toString()", sqlDataType); return value.toString(); }
DefaultSQLValuesFormatter implements SQLValuesFormatter { @Override public <T> String formatValue(final T value, final String sqlDataType, final String fullTableName, final String tableName, final String columnName) { if (value == null) { return "NULL"; } switch (sqlDataType) { case "VARCHAR": case "VARCHAR2": return "'" + value.toString().replace("'", "''") + "'"; case "DECIMAL": case "NUMBER": if (value instanceof Boolean) { return (Boolean) value ? "1" : "0"; } return value.toString(); default: break; } if (value instanceof java.util.Date) { Date d = (Date) value; Timestamp t = new Timestamp(d.getTime()); return "TO_TIMESTAMP('" + t.toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } if (value instanceof TemporalAccessor) { TemporalAccessor temporalAccessor = (TemporalAccessor) value; String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").format(temporalAccessor); return "TO_TIMESTAMP('" + s + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } LOG.warn("No mapping for {}. Returning result of toString()", sqlDataType); return value.toString(); } }
DefaultSQLValuesFormatter implements SQLValuesFormatter { @Override public <T> String formatValue(final T value, final String sqlDataType, final String fullTableName, final String tableName, final String columnName) { if (value == null) { return "NULL"; } switch (sqlDataType) { case "VARCHAR": case "VARCHAR2": return "'" + value.toString().replace("'", "''") + "'"; case "DECIMAL": case "NUMBER": if (value instanceof Boolean) { return (Boolean) value ? "1" : "0"; } return value.toString(); default: break; } if (value instanceof java.util.Date) { Date d = (Date) value; Timestamp t = new Timestamp(d.getTime()); return "TO_TIMESTAMP('" + t.toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } if (value instanceof TemporalAccessor) { TemporalAccessor temporalAccessor = (TemporalAccessor) value; String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").format(temporalAccessor); return "TO_TIMESTAMP('" + s + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } LOG.warn("No mapping for {}. Returning result of toString()", sqlDataType); return value.toString(); } }
DefaultSQLValuesFormatter implements SQLValuesFormatter { @Override public <T> String formatValue(final T value, final String sqlDataType, final String fullTableName, final String tableName, final String columnName) { if (value == null) { return "NULL"; } switch (sqlDataType) { case "VARCHAR": case "VARCHAR2": return "'" + value.toString().replace("'", "''") + "'"; case "DECIMAL": case "NUMBER": if (value instanceof Boolean) { return (Boolean) value ? "1" : "0"; } return value.toString(); default: break; } if (value instanceof java.util.Date) { Date d = (Date) value; Timestamp t = new Timestamp(d.getTime()); return "TO_TIMESTAMP('" + t.toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } if (value instanceof TemporalAccessor) { TemporalAccessor temporalAccessor = (TemporalAccessor) value; String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").format(temporalAccessor); return "TO_TIMESTAMP('" + s + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } LOG.warn("No mapping for {}. Returning result of toString()", sqlDataType); return value.toString(); } @Override String formatValue(final T value, final String sqlDataType, final String fullTableName, final String tableName, final String columnName); }
DefaultSQLValuesFormatter implements SQLValuesFormatter { @Override public <T> String formatValue(final T value, final String sqlDataType, final String fullTableName, final String tableName, final String columnName) { if (value == null) { return "NULL"; } switch (sqlDataType) { case "VARCHAR": case "VARCHAR2": return "'" + value.toString().replace("'", "''") + "'"; case "DECIMAL": case "NUMBER": if (value instanceof Boolean) { return (Boolean) value ? "1" : "0"; } return value.toString(); default: break; } if (value instanceof java.util.Date) { Date d = (Date) value; Timestamp t = new Timestamp(d.getTime()); return "TO_TIMESTAMP('" + t.toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } if (value instanceof TemporalAccessor) { TemporalAccessor temporalAccessor = (TemporalAccessor) value; String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").format(temporalAccessor); return "TO_TIMESTAMP('" + s + "', 'YYYY-MM-DD HH24:MI:SS.FF')"; } LOG.warn("No mapping for {}. Returning result of toString()", sqlDataType); return value.toString(); } @Override String formatValue(final T value, final String sqlDataType, final String fullTableName, final String tableName, final String columnName); }
@Test public void testBuilder_AllDefault() { MyRedG redG = new RedGBuilder<>(MyRedG.class) .build(); assertTrue(redG.getDefaultValueStrategy() instanceof DefaultDefaultValueStrategy); assertTrue(redG.getDummyFactory() instanceof DefaultDummyFactory); assertTrue(redG.getSqlValuesFormatter() instanceof DefaultSQLValuesFormatter); assertTrue(redG.getPreparedStatementParameterSetter() instanceof DefaultPreparedStatementParameterSetter); }
public T build() { final T inst = instance; instance = null; return inst; }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); RedGBuilder<T> withDefaultValueStrategy(final DefaultValueStrategy strategy); RedGBuilder<T> withPreparedStatementParameterSetter(final PreparedStatementParameterSetter setter); RedGBuilder<T> withSqlValuesFormatter(final SQLValuesFormatter formatter); RedGBuilder<T> withDummyFactory(final DummyFactory dummyFactory); T build(); }
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); RedGBuilder<T> withDefaultValueStrategy(final DefaultValueStrategy strategy); RedGBuilder<T> withPreparedStatementParameterSetter(final PreparedStatementParameterSetter setter); RedGBuilder<T> withSqlValuesFormatter(final SQLValuesFormatter formatter); RedGBuilder<T> withDummyFactory(final DummyFactory dummyFactory); T build(); }
@Test public void testXStream() throws IOException { TypeMappings typeMappings = new TypeMappings(); TableTypeMapping tableTypeMapping = new TableTypeMapping(); tableTypeMapping.setTableName("MY_TABLE"); ColumnTypeMapping columnTypeMapping = new ColumnTypeMapping(); columnTypeMapping.setColumnName("MY_FLAG"); columnTypeMapping.setJavaType("java.lang.Boolean"); tableTypeMapping.setColumnTypeMappings(new ArrayList<>(Collections.singletonList(columnTypeMapping))); typeMappings.setTableTypeMappings(new ArrayList<>(Collections.singletonList(tableTypeMapping))); DefaultTypeMapping defaultTypeMapping = new DefaultTypeMapping(); defaultTypeMapping.setSqlType("DECIMAL(1)"); defaultTypeMapping.setJavaType("java.lang.Boolean"); typeMappings.setDefaultTypeMappings(new ArrayList<>(Collections.singletonList(defaultTypeMapping))); String serializedConfig = XmlFileDataTypeProvider.createXStream().toXML(typeMappings); assertEqualsIgnoreXmlWhiteSpaces(readResource("XmlFileDataTypeProviderTest.xml"), serializedConfig); }
static XStream createXStream() { XStream xStream = new XStream(); xStream.processAnnotations(new Class[]{ ColumnTypeMapping.class, DefaultTypeMapping.class, TableTypeMapping.class, TypeMappings.class }); xStream.useAttributeFor(TableTypeMapping.class, "tableName"); xStream.addDefaultImplementation(ArrayList.class, List.class); return xStream; }
XmlFileDataTypeProvider implements DataTypeProvider { static XStream createXStream() { XStream xStream = new XStream(); xStream.processAnnotations(new Class[]{ ColumnTypeMapping.class, DefaultTypeMapping.class, TableTypeMapping.class, TypeMappings.class }); xStream.useAttributeFor(TableTypeMapping.class, "tableName"); xStream.addDefaultImplementation(ArrayList.class, List.class); return xStream; } }
XmlFileDataTypeProvider implements DataTypeProvider { static XStream createXStream() { XStream xStream = new XStream(); xStream.processAnnotations(new Class[]{ ColumnTypeMapping.class, DefaultTypeMapping.class, TableTypeMapping.class, TypeMappings.class }); xStream.useAttributeFor(TableTypeMapping.class, "tableName"); xStream.addDefaultImplementation(ArrayList.class, List.class); return xStream; } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); }
XmlFileDataTypeProvider implements DataTypeProvider { static XStream createXStream() { XStream xStream = new XStream(); xStream.processAnnotations(new Class[]{ ColumnTypeMapping.class, DefaultTypeMapping.class, TableTypeMapping.class, TypeMappings.class }); xStream.useAttributeFor(TableTypeMapping.class, "tableName"); xStream.addDefaultImplementation(ArrayList.class, List.class); return xStream; } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
XmlFileDataTypeProvider implements DataTypeProvider { static XStream createXStream() { XStream xStream = new XStream(); xStream.processAnnotations(new Class[]{ ColumnTypeMapping.class, DefaultTypeMapping.class, TableTypeMapping.class, TypeMappings.class }); xStream.useAttributeFor(TableTypeMapping.class, "tableName"); xStream.addDefaultImplementation(ArrayList.class, List.class); return xStream; } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }
@Test public void getInstance() throws Exception { }
public static HotFragment getInstance() { return new HotFragment(); }
HotFragment extends BaseFragment<HotPresenterImp> implements HotView { public static HotFragment getInstance() { return new HotFragment(); } }
HotFragment extends BaseFragment<HotPresenterImp> implements HotView { public static HotFragment getInstance() { return new HotFragment(); } }
HotFragment extends BaseFragment<HotPresenterImp> implements HotView { public static HotFragment getInstance() { return new HotFragment(); } static HotFragment getInstance(); @Override void onBindPage(); @OnClick({R.id.tv_city, R.id.dcl_search}) void onViewClicked(View view); @Override void onActivityResult(int requestCode, int resultCode, Intent data); }
HotFragment extends BaseFragment<HotPresenterImp> implements HotView { public static HotFragment getInstance() { return new HotFragment(); } static HotFragment getInstance(); @Override void onBindPage(); @OnClick({R.id.tv_city, R.id.dcl_search}) void onViewClicked(View view); @Override void onActivityResult(int requestCode, int resultCode, Intent data); static final String TAG; @BindView(R.id.ll_search) public LinearLayout llSearch; @BindView(R.id.ll_search_main) public LinearLayout llSearchMain; @BindView(R.id.fl_search) public FrameLayout flSearch; @BindView(R.id.tv_city) public TextView tvCity; }