src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
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 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())); }
@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())); } |
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 getDataTypeBoolean() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "boolean"); Assert.assertEquals("java.lang.Boolean", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Test public void getDataTypeCharacter() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "char"); Assert.assertEquals("java.lang.Character", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Test public void getDataTypeByte() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "byte"); Assert.assertEquals("java.lang.Byte", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Test public void getDataTypeShort() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "short"); Assert.assertEquals("java.lang.Short", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Test public void getDataTypeInteger() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "int"); Assert.assertEquals("java.lang.Integer", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Test public void getDataTypeLong() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "long"); Assert.assertEquals("java.lang.Long", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Test public void getDataTypeFloat() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "float"); Assert.assertEquals("java.lang.Float", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@Test public void getDataTypeDouble() throws Exception { NoPrimitiveTypesDataTypeProviderWrapper provider = new NoPrimitiveTypesDataTypeProviderWrapper(column -> "double"); Assert.assertEquals("java.lang.Double", provider.getCanonicalDataTypeName(Mockito.mock(Column.class))); }
@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))); } |
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 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"))); }
@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"))); }
@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"))); } |
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 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()); } |
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 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()); }
@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()); } |
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 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()); }
@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()); }
@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()); } |
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 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()); } |
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 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()); } } } |
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_H2Success() throws Exception { Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h2:mem:redg", "", ""); assertNotNull(connection); assertTrue(connection.isValid(10)); }
@Test public void testConnectToDatabase_InvalidDriver() throws Exception { thrown.expect(ClassNotFoundException.class); DatabaseManager.connectToDatabase("does.not.exist.Driver", "jdbc:dne:mem:redg", "", ""); }
@Test public void testConnectToDatabase_FailedConnection() throws Exception { thrown.expect(SQLException.class); Connection connection = DatabaseManager.connectToDatabase("org.h2.Driver", "jdbc:h4:invalid:redg", "", ""); } |
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 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)); } |
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 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)); } |
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 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]"); } |
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 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(); } |
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_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)); }
@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); }
@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); } |
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 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(); }
@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(); } |
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 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(); }
@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(); } |
ClassAvailabilityChecker { public boolean isAvailable() { return available; } ClassAvailabilityChecker(String fqcn); boolean isAvailable(); } | @Test public void testHappyPaths() throws Exception { Assert.assertTrue(new ClassAvailabilityChecker("java.util.HashMap").isAvailable()); Assert.assertFalse(new ClassAvailabilityChecker("no.java.util.HashMap").isAvailable()); } |
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 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); } |
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 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()); } |
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 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)); } |
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 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)); } |
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 testGetMethodNameForForeignKey() throws Exception { Assert.assertEquals("subJoinedManyToOne", provider.getMethodNameForReference(getForeignKey("SUB_ENTITY_JOINED_1", "SUBJOINEDMANYTOONE_ID"))); Assert.assertEquals("refEntity2", provider.getMethodNameForReference(getForeignKey("REFERENCEDENTITY1", "REFENTITY2_ID1"))); } |
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 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)); } |
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() { 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)); }); }
@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()); }
@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); }
@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)); } }
@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)); } }
@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); }
@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); }
@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()); } }
@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)); } }
@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); }
@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)); } }
@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); }
@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); }
@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); } |
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 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"))); }
@Test public void testGetDataTypeForEmbedded() throws Exception { Assert.assertEquals("long", provider.getCanonicalDataTypeName(getColumn("REFERENCEDENTITY1", "EMBEDDEDLONGATTRIBUTE"))); } |
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 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()); } |
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 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); } |
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 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); } |
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 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); } |
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 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); } |
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 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); } |
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 isNotNull() { final ColumnModel cm = TestUtils.getCM("", "", "", String.class, true); final ColumnModel cm2 = TestUtils.getCM("", "", "", String.class, false); assertThat(Matchers.isNotNull()) .accepts(cm) .rejects(cm2); } |
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 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); } |
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 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); } |
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 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); } |
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 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); } |
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 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); } |
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 eq() { assertThat(Conditions.eq("A")) .accepts("A") .rejects("B", "C"); } |
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 neq() { assertThat(Conditions.neq("A")) .rejects("A") .accepts("B", "C"); } |
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 contains() { assertThat(Conditions.contains("A")) .accepts("A", "AB", "BA", "ABBA") .rejects("B", "BODO"); } |
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 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")) ); } |
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 matchesRegex() { assertThat(Conditions.matchesRegex("Hallo.+")) .accepts("Hallo Welt", "Hallo BTC") .rejects("Hello World"); } |
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 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(); }
@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(); }
@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(); }
@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(); }
@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(); } |
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 testGetDefaultValue() { ConditionalProvider provider = new ConditionalProvider(new NoProvider(), null, null, null); assertThat(provider.getDefaultValue(getModel("A", "B", "C.B"), String.class)).isNull(); } |
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 willProvide() { assertThat(new DefaultDefaultValueProvider().willProvide(null)).isTrue(); assertThat(new DefaultDefaultValueProvider().willProvide(mock(ColumnModel.class))).isTrue(); } |
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 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)); }); } |
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 testGetEntities() throws Exception { MockRedG mockRedG = new MockRedG(); RedGEntity e = new MockEntity1(); mockRedG.addEntity(e); assertThat(mockRedG.getEntities()).containsExactly(e); } |
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 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"); } |
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 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); } |
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 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); } |
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 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()); } |
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 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()); } |
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 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)); } |
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 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)); }
@Test public void testParseInstantWithNonIsoDate() throws Exception { assertEquals(EXPECTED_DATETIME, DateConverter.parseInstant("2017-01-02 03:04:05.000", ZoneOffset.UTC).atOffset(ZoneOffset.UTC)); } |
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 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)); } |
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 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", "", "", "")); } |
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 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); } |
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; } | @Test public void getInstance() throws Exception { } |
HotFragment extends BaseFragment<HotPresenterImp> implements HotView { @Override protected int getLayoutId() { return R.layout.fragment_hot; } 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; } | @Test public void getLayoutId() throws Exception { } |
HotFragment extends BaseFragment<HotPresenterImp> implements HotView { @Override protected void initView() { mainActivity = (MainActivity) getActivity(); mPresent = new HotPresenterImp(this, getChildFragmentManager()); mHotTl.setTabMode(TabLayout.MODE_FIXED); mPresent.initPage(mHotVp); } 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; } | @Test public void initView() throws Exception { } |
SqlStringUtils { public static <A> void union(StringBuilder b, Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll) { String joinClause = unionAll ? " UNION ALL " : " UNION "; for (A x : xs) { b.append("( "); singleSql.f(x, b); b.append(" )"); b.append(joinClause); } int replaceIdx = b.length() - joinClause.length(); if (replaceIdx < 1) { return; } b.replace(replaceIdx, b.length(), ""); } static String placeholders(int length); static StringBuilder placeholdersBuilder(int length, StringBuilder sb); static String placeholderRows(int numRows, int numColumns); static String literal(String str); static StringBuilder setExpressionWithPlaceholders(Iterable<String> colNames); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames, LogicalOperator op); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames); static StatementKind getStatementKind(String sql); static void union(StringBuilder b, Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); static StringBuilder union(Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); } | @Test public void union() { StringBuilder result = SqlStringUtils.<String>union(list(), (x, b) -> b.append("hi " + x), true); assertThat(result.toString(), is("")); result = SqlStringUtils.union(list("a"), (x, b) -> b.append("hi " + x), true); assertThat(result.toString(), is("( hi a )")); result = SqlStringUtils.union(list("a", "b", "c"), (x, b) -> b.append("hi " + x), false); assertThat(result.toString(), is("( hi a ) UNION ( hi b ) UNION ( hi c )")); result = SqlStringUtils.union(list("x", "y"), (x, b) -> b.append("hi " + x), true); assertThat(result.toString(), is("( hi x ) UNION ALL ( hi y )")); } |
SqlStringUtils { public static String placeholders(int length) { return placeholdersBuilder(length, new StringBuilder()).toString(); } static String placeholders(int length); static StringBuilder placeholdersBuilder(int length, StringBuilder sb); static String placeholderRows(int numRows, int numColumns); static String literal(String str); static StringBuilder setExpressionWithPlaceholders(Iterable<String> colNames); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames, LogicalOperator op); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames); static StatementKind getStatementKind(String sql); static void union(StringBuilder b, Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); static StringBuilder union(Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); } | @Test public void placeholders() { assertThat(SqlStringUtils.placeholders(1), is("?")); assertThat(SqlStringUtils.placeholders(5).replaceAll(" ", ""), is("?,?,?,?,?")); } |
SqlStringUtils { public static String placeholderRows(int numRows, int numColumns) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < numRows; i++) { sb.append("("); sb = placeholdersBuilder(numColumns, sb); sb.append("), "); } sb.delete(sb.length() - 2, sb.length()); return sb.toString(); } static String placeholders(int length); static StringBuilder placeholdersBuilder(int length, StringBuilder sb); static String placeholderRows(int numRows, int numColumns); static String literal(String str); static StringBuilder setExpressionWithPlaceholders(Iterable<String> colNames); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames, LogicalOperator op); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames); static StatementKind getStatementKind(String sql); static void union(StringBuilder b, Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); static StringBuilder union(Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); } | @Test public void placeholderRows() { assertThat(SqlStringUtils.placeholderRows(3, 2).replaceAll(" ", ""), is("(?,?),(?,?),(?,?)")); } |
SqlStringUtils { public static String literal(String str) { return "'" + str + "'"; } static String placeholders(int length); static StringBuilder placeholdersBuilder(int length, StringBuilder sb); static String placeholderRows(int numRows, int numColumns); static String literal(String str); static StringBuilder setExpressionWithPlaceholders(Iterable<String> colNames); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames, LogicalOperator op); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames); static StatementKind getStatementKind(String sql); static void union(StringBuilder b, Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); static StringBuilder union(Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); } | @Test public void literal() { assertThat(SqlStringUtils.literal("foo"), is("'foo'")); } |
SqlStringUtils { public static StringBuilder setExpressionWithPlaceholders(Iterable<String> colNames) { return expressionWithPlaceholders(colNames, ", "); } static String placeholders(int length); static StringBuilder placeholdersBuilder(int length, StringBuilder sb); static String placeholderRows(int numRows, int numColumns); static String literal(String str); static StringBuilder setExpressionWithPlaceholders(Iterable<String> colNames); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames, LogicalOperator op); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames); static StatementKind getStatementKind(String sql); static void union(StringBuilder b, Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); static StringBuilder union(Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); } | @Test public void setExpressionWithPlaceholders() { assertThat( SqlStringUtils.setExpressionWithPlaceholders(asList("CITY", "ADDRESS")).toString() .replaceAll(" ", ""), is("CITY=?,ADDRESS=?") ); } |
SqlStringUtils { public static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames, LogicalOperator op) { return expressionWithPlaceholders(colNames, format(" {0} ", op.name()) ); } static String placeholders(int length); static StringBuilder placeholdersBuilder(int length, StringBuilder sb); static String placeholderRows(int numRows, int numColumns); static String literal(String str); static StringBuilder setExpressionWithPlaceholders(Iterable<String> colNames); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames, LogicalOperator op); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames); static StatementKind getStatementKind(String sql); static void union(StringBuilder b, Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); static StringBuilder union(Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); } | @Test public void whereExpressionWithPlaceholders() { assertThat( SqlStringUtils.whereExpressionWithPlaceholders(asList("CITY", "ADDRESS"), AND).toString(), is("CITY=? AND ADDRESS=?") ); assertThat( SqlStringUtils.whereExpressionWithPlaceholders(asList("X", "Y", "Z"), OR).toString(), is("X=? OR Y=? OR Z=?") ); } |
SqlStringUtils { public static StatementKind getStatementKind(String sql) { String prefix = sql.trim(); prefix = prefix.length() < 10 ? prefix : prefix.substring(0, 10); prefix = prefix.toLowerCase(); if (prefix.startsWith("select")) { return SELECT; } else if (prefix.startsWith("insert")) { return INSERT; } else if (prefix.startsWith("update")) { return UPDATE; } else if (prefix.startsWith("delete")) { return DELETE; } else { return UNKNOWN; } } static String placeholders(int length); static StringBuilder placeholdersBuilder(int length, StringBuilder sb); static String placeholderRows(int numRows, int numColumns); static String literal(String str); static StringBuilder setExpressionWithPlaceholders(Iterable<String> colNames); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames, LogicalOperator op); static StringBuilder whereExpressionWithPlaceholders(Iterable<String> colNames); static StatementKind getStatementKind(String sql); static void union(StringBuilder b, Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); static StringBuilder union(Iterable<A> xs, Effect2<A, StringBuilder> singleSql, boolean unionAll); } | @Test public void statementKind() { assertThat( SqlStringUtils.getStatementKind(" SELECT * FROM FOO"), is(SELECT) ); assertThat( SqlStringUtils.getStatementKind("insert into alabalanicafoorbar values ()"), is(INSERT) ); assertThat(SqlStringUtils.getStatementKind("update x set y=? where z=?"), is(UPDATE) ); assertThat(SqlStringUtils.getStatementKind("DELETE from x"), is(DELETE) ); assertThat(SqlStringUtils.getStatementKind("DROP SCHEMA TAXES"), is(UNKNOWN) ); } |
LogStore extends ChangeSupport { @Process(actionType = ReadLogFiles.class) public void readLogFiles(final Dispatcher.Channel channel) { final ModelNode op = listLogFilesOp(); dispatcher.execute(new DMRAction(op), new AsyncCallback<DMRResponse>() { @Override public void onFailure(Throwable caught) { channel.nack(caught); } @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if (response.isFailure()) { channel.nack(new RuntimeException("Failed to read list of log files using " + op + ": " + response.getFailureDescription())); } else { logFiles.clear(); activeLogFile = null; List<Property> properties = response.get(RESULT).asPropertyList(); for (Property property : properties) { ModelNode node = property.getValue(); node.get(FILE_NAME).set(property.getName()); logFiles.add(node); } Set<String> names = new HashSet<>(); for (ModelNode logFile : logFiles) { names.add(logFile.get(FILE_NAME).asString()); } for (Map.Entry<String, LogFile> entry : states.entrySet()) { if (!names.contains(entry.getKey())) { entry.getValue().setStale(true); } } channel.ack(); } } }); } @Inject LogStore(ServerStore serverStore, DispatchAsync dispatcher, Scheduler scheduler, BootstrapContext bootstrap); @Process(actionType = ReadLogFiles.class) void readLogFiles(final Dispatcher.Channel channel); @Process(actionType = ReadLogFilesForRefresh.class) void readLogFilesForRefresh(final Dispatcher.Channel channel); @Process(actionType = OpenLogFile.class) void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel); @Process(actionType = StreamLogFile.class) void streamLogFile(final StreamLogFile action, final Dispatcher.Channel channel); @Process(actionType = RefreshLogFile.class) void refreshLogFile(final RefreshLogFile action, final Dispatcher.Channel channel); @Process(actionType = DownloadLogFile.class) void downloadLogFile(final DownloadLogFile action, final Dispatcher.Channel channel); @Process(actionType = CloseLogFile.class) void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel); @Process(actionType = SelectLogFile.class) void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel); @Process(actionType = NavigateInLogFile.class) void navigate(final NavigateInLogFile action, final Dispatcher.Channel channel); @Process(actionType = ChangePageSize.class) void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel); @Process(actionType = FollowLogFile.class) void follow(final Dispatcher.Channel channel); @Process(actionType = PauseFollowLogFile.class) void pauseFollow(final Dispatcher.Channel channel); @Process(actionType = UnFollowLogFile.class) void unFollow(final Dispatcher.Channel channel); List<ModelNode> getLogFiles(); LogFile getActiveLogFile(); boolean isOpen(final String name); PendingStreamingRequest getPendingStreamingRequest(); final static String FILE_NAME; final static String FILE_SIZE; final static String LAST_MODIFIED_TIMESTAMP; } | @Test public void readLogFiles() { dispatcher.push(StaticDmrResponse.ok(logFileNodes("server.log", "server.log.2014.-08-01", "server.log.2014.-08-02"))); store.readLogFiles(NoopChannel.INSTANCE); assertNull(store.getActiveLogFile()); assertEquals(3, store.getLogFiles().size()); }
@Test public void readLogFilesAndVerifyStale() { LogFile stale = new LogFile("stale.log", Collections.<String>emptyList(), 0); store.states.put(stale.getName(), stale); dispatcher.push(StaticDmrResponse.ok(logFileNodes("server.log"))); store.readLogFiles(NoopChannel.INSTANCE); assertTrue(store.states.get(stale.getName()).isStale()); } |
AddressTemplate { public AddressTemplate append(String template) { String slashTemplate = template.startsWith("/") ? template : "/" + template; return AddressTemplate.of(this.template + slashTemplate); } private AddressTemplate(String template); static AddressTemplate of(String template); int getNumTokens(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); AddressTemplate append(String template); AddressTemplate subTemplate(int fromIndex, int toIndex); AddressTemplate replaceWildcards(String wildcard, String... wildcards); String getResourceType(); String getTemplate(); boolean isOptional(); ResourceAddress resolve(StatementContext context, List<String> wildcards); ResourceAddress resolve(StatementContext context, String... wildcards); String resolveAsKey(StatementContext context, String... wildcards); } | @Test public void append() { AddressTemplate at = AddressTemplate.of("a=b"); at = at.append("c=d"); assertEquals("a=b/c=d", at.getTemplate()); at = AddressTemplate.of("a=b"); at = at.append("/c=d"); assertEquals("a=b/c=d", at.getTemplate()); } |
AddressTemplate { public AddressTemplate subTemplate(int fromIndex, int toIndex) { LinkedList<Token> subTokens = new LinkedList<>(); subTokens.addAll(this.tokens.subList(fromIndex, toIndex)); return AddressTemplate.of(join(this.optional, subTokens)); } private AddressTemplate(String template); static AddressTemplate of(String template); int getNumTokens(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); AddressTemplate append(String template); AddressTemplate subTemplate(int fromIndex, int toIndex); AddressTemplate replaceWildcards(String wildcard, String... wildcards); String getResourceType(); String getTemplate(); boolean isOptional(); ResourceAddress resolve(StatementContext context, List<String> wildcards); ResourceAddress resolve(StatementContext context, String... wildcards); String resolveAsKey(StatementContext context, String... wildcards); } | @Test public void subTemplate() { AddressTemplate at = AddressTemplate.of("{a}/b=c/{d}=e/f=g"); assertEquals("", at.subTemplate(0, 0).getTemplate()); assertEquals("", at.subTemplate(2, 2).getTemplate()); assertEquals("b=c", at.subTemplate(1, 2).getTemplate()); assertEquals("{d}=e/f=g", at.subTemplate(2, 4).getTemplate()); assertEquals(at, at.subTemplate(0, 4)); } |
AddressTemplate { public AddressTemplate replaceWildcards(String wildcard, String... wildcards) { List<String> allWildcards = new ArrayList<>(); allWildcards.add(wildcard); if (wildcards != null) { allWildcards.addAll(Arrays.asList(wildcards)); } LinkedList<Token> replacedTokens = new LinkedList<>(); Iterator<String> wi = allWildcards.iterator(); for (Token token : tokens) { if (wi.hasNext() && token.hasKey() && "*".equals(token.getValue())) { replacedTokens.add(new Token(token.getKey(), wi.next())); } else { replacedTokens.add(new Token(token.key, token.value)); } } return AddressTemplate.of(join(this.optional, replacedTokens)); } private AddressTemplate(String template); static AddressTemplate of(String template); int getNumTokens(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); AddressTemplate append(String template); AddressTemplate subTemplate(int fromIndex, int toIndex); AddressTemplate replaceWildcards(String wildcard, String... wildcards); String getResourceType(); String getTemplate(); boolean isOptional(); ResourceAddress resolve(StatementContext context, List<String> wildcards); ResourceAddress resolve(StatementContext context, String... wildcards); String resolveAsKey(StatementContext context, String... wildcards); } | @Test public void replaceWildcards() { AddressTemplate at = AddressTemplate.of("a=b"); at = at.replaceWildcards(null); assertEquals("a=b", at.getTemplate()); at = AddressTemplate.of("a=b"); at = at.replaceWildcards(null, null); assertEquals("a=b", at.getTemplate()); at = AddressTemplate.of("a=b"); at = at.replaceWildcards("foo"); assertEquals("a=b", at.getTemplate()); at = AddressTemplate.of("{a}/b={c}"); at = at.replaceWildcards("foo"); assertEquals("{a}/b={c}", at.getTemplate()); at = AddressTemplate.of("a=*/c=*"); at = at.replaceWildcards("b"); assertEquals("a=b/c=*", at.getTemplate()); at = AddressTemplate.of("a=*/c=*"); at = at.replaceWildcards("b", null); assertEquals("a=b/c=*", at.getTemplate()); at = AddressTemplate.of("a=*/c=*"); at = at.replaceWildcards("b", "d"); assertEquals("a=b/c=d", at.getTemplate()); at = AddressTemplate.of("a=*/c=*"); at = at.replaceWildcards("b", "d", "foo"); assertEquals("a=b/c=d", at.getTemplate()); at = AddressTemplate.of("a=*/c={d}"); at = at.replaceWildcards("b", "d", "foo"); assertEquals("a=b/c={d}", at.getTemplate()); } |
AddressTemplate { public ResourceAddress resolve(StatementContext context, List<String> wildcards) { Resolution<ModelNode> resolution = new Resolution<ModelNode>() { private ModelNode modelNode; @Override public void init() { this.modelNode = new ModelNode(); } @Override public void addKeyValue(String key, String value) { this.modelNode.add(key, value); } @Override public ModelNode getResult() { return modelNode; } }; _resolve(context, wildcards, resolution); return new ResourceAddress(resolution.getResult()); } private AddressTemplate(String template); static AddressTemplate of(String template); int getNumTokens(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); AddressTemplate append(String template); AddressTemplate subTemplate(int fromIndex, int toIndex); AddressTemplate replaceWildcards(String wildcard, String... wildcards); String getResourceType(); String getTemplate(); boolean isOptional(); ResourceAddress resolve(StatementContext context, List<String> wildcards); ResourceAddress resolve(StatementContext context, String... wildcards); String resolveAsKey(StatementContext context, String... wildcards); } | @Test public void resolve() { AddressTemplate at = AddressTemplate.of("{a}/b={c}"); ResourceAddress resolved = at.resolve(new EchoContext()); assertResolved(new String[][]{{"a", "a"}, {"b", "c"}}, resolved); } |
AddressUtils { public static String toString(ModelNode address, boolean fq) { List<Property> tuples = address.asPropertyList(); StringBuilder sb = new StringBuilder(); int i=0; for (final Property tuple : tuples) { if(i>0) sb.append("/"); sb.append(tuple.getName()); sb.append("="); if(i==tuples.size()-1) if(fq) sb.append(escapeValue(tuple.getValue().asString())); else sb.append("*"); else sb.append(escapeValue(tuple.getValue().asString())); i++; } return sb.toString(); } static ModelNode toFqAddress(ModelNode address, String resourceName); static ModelNode fromFqAddress(ModelNode address); static String getDenominatorType(List<Property> addressTuple); static String toString(ModelNode address, boolean fq); static String asKey(ModelNode address, boolean fq); } | @Test public void testToString() { ModelNode address = new ModelNode(); address.add("subsystem", "test"); address.add("resource", "name"); String s = AddressUtils.toString(address, true); Assert.assertEquals("subsystem=test/resource=name", s); }
@Test public void testToStringValueContainsSlash() { ModelNode address = new ModelNode(); address.add("subsystem", "test"); address.add("resource", "java:/global/a"); String s = AddressUtils.toString(address, true); Assert.assertEquals("subsystem=test/resource=java\\:\\/global\\/a", s); } |
AddressUtils { public static String asKey(ModelNode address, boolean fq) { List<Property> tuples = address.asPropertyList(); StringBuilder sb = new StringBuilder(); int i=0; for (final Property tuple : tuples) { if(i>0) sb.append("/"); sb.append(tuple.getName()); sb.append("="); if(i==tuples.size()-1) if(fq) sb.append(escapeValue(tuple.getValue().asString())); else sb.append("*"); else sb.append(escapeValue(tuple.getValue().asString())); i++; } return sb.toString(); } static ModelNode toFqAddress(ModelNode address, String resourceName); static ModelNode fromFqAddress(ModelNode address); static String getDenominatorType(List<Property> addressTuple); static String toString(ModelNode address, boolean fq); static String asKey(ModelNode address, boolean fq); } | @Test public void testAsKey() { ModelNode address = new ModelNode(); address.add("subsystem", "test"); address.add("resource", "name"); String s = AddressUtils.asKey(address, true); Assert.assertEquals("subsystem=test/resource=name", s); }
@Test public void testAsKeyValueContainsSlash() { ModelNode address = new ModelNode(); address.add("subsystem", "test"); address.add("resource", "java:/global/a"); String s = AddressUtils.asKey(address, true); Assert.assertEquals("subsystem=test/resource=java\\:\\/global\\/a", s); } |
InteractionUnit implements Consumer, Producer { public <T extends Mapping> T findMapping(MappingType type) { return (T) this.findMapping(type, DEFAULT_PREDICATE); } protected InteractionUnit(QName id, final String label); protected InteractionUnit(final QName id, final String label, S stereotype); S getStereotype(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); void addMapping(Mapping mapping); boolean hasMapping(MappingType type); T getMapping(MappingType type); T findMapping(MappingType type); T findMapping(MappingType type, Predicate<T> predicate); @Override Set<Resource<ResourceType>> getInputs(); @Override boolean doesConsume(Resource<ResourceType> event); void accept(InteractionUnitVisitor visitor); Container getParent(); boolean hasParent(); QName getId(); String getLabel(); void setLabel(final String label); @Override boolean doesConsume(); @Override boolean doesProduce(); boolean doesProduce(Resource<ResourceType> resource); @Override void setOutputs(Resource<ResourceType>... resource); @Override void setInputs(Resource<ResourceType>... resource); Set<Resource<ResourceType>> getOutputs(); Integer getScopeId(); void setScopeId(Integer scopeId); } | @Test public void findMapping() { Container basicAttributes = new Container(NAMESPACE, "basicAttributes", "Basic Attributes"); InteractionUnit root = new Builder() .start(new Container(NAMESPACE, "root", "Root", OrderIndependance)) .mappedBy(new DMRMapping().setAddress("root")) .add(new Select(NAMESPACE, "table", "Table")) .start(new Container(NAMESPACE, "forms", "Forms", Choice)) .add(basicAttributes) .mappedBy(new DMRMapping().setAddress("basicAttributes")) .add(new Container(NAMESPACE, "extendedAttributes", "Basic Attributes")) .end() .end().build(); DMRMapping mapping = (DMRMapping) basicAttributes.findMapping(DMR, new Predicate<DMRMapping>() { @Override public boolean appliesTo(DMRMapping candidate) { return true; } }); assertNotNull(mapping); assertEquals("basicAttributes", mapping.getAddress()); mapping = (DMRMapping) basicAttributes.findMapping(DMR, new Predicate<DMRMapping>() { @Override public boolean appliesTo(final DMRMapping candidate) { return "root".equals(candidate.getAddress()); } }); assertNotNull(mapping); assertEquals("root", mapping.getAddress()); } |
InteractionUnit implements Consumer, Producer { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof InteractionUnit)) { return false; } InteractionUnit that = (InteractionUnit) o; if (!id.equals(that.id)) { return false; } return true; } protected InteractionUnit(QName id, final String label); protected InteractionUnit(final QName id, final String label, S stereotype); S getStereotype(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); void addMapping(Mapping mapping); boolean hasMapping(MappingType type); T getMapping(MappingType type); T findMapping(MappingType type); T findMapping(MappingType type, Predicate<T> predicate); @Override Set<Resource<ResourceType>> getInputs(); @Override boolean doesConsume(Resource<ResourceType> event); void accept(InteractionUnitVisitor visitor); Container getParent(); boolean hasParent(); QName getId(); String getLabel(); void setLabel(final String label); @Override boolean doesConsume(); @Override boolean doesProduce(); boolean doesProduce(Resource<ResourceType> resource); @Override void setOutputs(Resource<ResourceType>... resource); @Override void setInputs(Resource<ResourceType>... resource); Set<Resource<ResourceType>> getOutputs(); Integer getScopeId(); void setScopeId(Integer scopeId); } | @Test public void testProcedureEquality() { Procedure proc1 = new TestProcedure(QName.valueOf("foo.bar:proc")) {}; Procedure proc2 = new TestProcedure(QName.valueOf("foo.bar:proc")) {}; Procedure proc3 = new TestProcedure(QName.valueOf("foo.bar:proc"), QName.valueOf("some:origin")) {}; Procedure proc4 = new TestProcedure(QName.valueOf("foo.bar:proc2")) {}; Procedure proc5 = new TestProcedure(QName.valueOf("foo.bar:proc"), QName.valueOf("some:origin")) {}; assertEquals(proc1, proc2); assertFalse(proc2.equals(proc3)); assertFalse(proc1.equals(proc4)); assertEquals(proc3, proc5); } |
LogStore extends ChangeSupport { @Process(actionType = OpenLogFile.class) public void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel) { final LogFile logFile = states.get(action.getName()); if (logFile == null) { final ModelNode op = readLogFileOp(action.getName()); op.get("tail").set(true); dispatcher.execute(new DMRAction(wrapInComposite(op)), new AsyncCallback<DMRResponse>() { @Override public void onFailure(Throwable caught) { channel.nack(caught); } @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if (response.isFailure()) { channel.nack(new RuntimeException("Failed to open " + action.getName() + " using " + op + ": " + response.getFailureDescription())); } else { ModelNode compResult = response.get(RESULT); LogFile newLogFile = new LogFile(action.getName(), readLines(compResult), readFileSize(action.getName(), compResult)); newLogFile.setFollow(true); states.put(action.getName(), newLogFile); activate(newLogFile); channel.ack(); } } }); } else { activate(logFile); channel.ack(); } } @Inject LogStore(ServerStore serverStore, DispatchAsync dispatcher, Scheduler scheduler, BootstrapContext bootstrap); @Process(actionType = ReadLogFiles.class) void readLogFiles(final Dispatcher.Channel channel); @Process(actionType = ReadLogFilesForRefresh.class) void readLogFilesForRefresh(final Dispatcher.Channel channel); @Process(actionType = OpenLogFile.class) void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel); @Process(actionType = StreamLogFile.class) void streamLogFile(final StreamLogFile action, final Dispatcher.Channel channel); @Process(actionType = RefreshLogFile.class) void refreshLogFile(final RefreshLogFile action, final Dispatcher.Channel channel); @Process(actionType = DownloadLogFile.class) void downloadLogFile(final DownloadLogFile action, final Dispatcher.Channel channel); @Process(actionType = CloseLogFile.class) void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel); @Process(actionType = SelectLogFile.class) void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel); @Process(actionType = NavigateInLogFile.class) void navigate(final NavigateInLogFile action, final Dispatcher.Channel channel); @Process(actionType = ChangePageSize.class) void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel); @Process(actionType = FollowLogFile.class) void follow(final Dispatcher.Channel channel); @Process(actionType = PauseFollowLogFile.class) void pauseFollow(final Dispatcher.Channel channel); @Process(actionType = UnFollowLogFile.class) void unFollow(final Dispatcher.Channel channel); List<ModelNode> getLogFiles(); LogFile getActiveLogFile(); boolean isOpen(final String name); PendingStreamingRequest getPendingStreamingRequest(); final static String FILE_NAME; final static String FILE_SIZE; final static String LAST_MODIFIED_TIMESTAMP; } | @Test public void openLogFile() { dispatcher.push(StaticDmrResponse.ok(comp(logFileNodes("server.log"), linesNode(2)))); store.logFiles.add(logFileNode("server.log")); store.openLogFile(new OpenLogFile("server.log"), NoopChannel.INSTANCE); assertFalse(store.pauseFollow); LogFile activeLogFile = store.getActiveLogFile(); assertNotNull(activeLogFile); assertEquals("server.log", activeLogFile.getName()); assertLines(activeLogFile.getContent(), 0, 1); assertFalse(activeLogFile.isHead()); assertTrue(activeLogFile.isTail()); assertEquals(Position.TAIL, activeLogFile.getReadFrom()); assertEquals(0, activeLogFile.getSkipped()); assertTrue(activeLogFile.isFollow()); assertFalse(activeLogFile.isStale()); } |
LogStore extends ChangeSupport { @Process(actionType = SelectLogFile.class) public void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel) { final LogFile logFile = states.get(action.getName()); if (logFile == null) { channel.nack(new IllegalStateException("Cannot select unknown log file " + action.getName() + ". " + "Please open the log file first!")); return; } activate(logFile); channel.ack(); } @Inject LogStore(ServerStore serverStore, DispatchAsync dispatcher, Scheduler scheduler, BootstrapContext bootstrap); @Process(actionType = ReadLogFiles.class) void readLogFiles(final Dispatcher.Channel channel); @Process(actionType = ReadLogFilesForRefresh.class) void readLogFilesForRefresh(final Dispatcher.Channel channel); @Process(actionType = OpenLogFile.class) void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel); @Process(actionType = StreamLogFile.class) void streamLogFile(final StreamLogFile action, final Dispatcher.Channel channel); @Process(actionType = RefreshLogFile.class) void refreshLogFile(final RefreshLogFile action, final Dispatcher.Channel channel); @Process(actionType = DownloadLogFile.class) void downloadLogFile(final DownloadLogFile action, final Dispatcher.Channel channel); @Process(actionType = CloseLogFile.class) void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel); @Process(actionType = SelectLogFile.class) void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel); @Process(actionType = NavigateInLogFile.class) void navigate(final NavigateInLogFile action, final Dispatcher.Channel channel); @Process(actionType = ChangePageSize.class) void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel); @Process(actionType = FollowLogFile.class) void follow(final Dispatcher.Channel channel); @Process(actionType = PauseFollowLogFile.class) void pauseFollow(final Dispatcher.Channel channel); @Process(actionType = UnFollowLogFile.class) void unFollow(final Dispatcher.Channel channel); List<ModelNode> getLogFiles(); LogFile getActiveLogFile(); boolean isOpen(final String name); PendingStreamingRequest getPendingStreamingRequest(); final static String FILE_NAME; final static String FILE_SIZE; final static String LAST_MODIFIED_TIMESTAMP; } | @Test public void selectLogFile() { LogFile logFile = new LogFile("server.log", lines(0), 0); store.states.put(logFile.getName(), logFile); store.activate(logFile); assertFalse(store.pauseFollow); store.selectLogFile(new SelectLogFile("server.log"), NoopChannel.INSTANCE); LogFile activeLogFile = store.getActiveLogFile(); assertSame(logFile, activeLogFile); } |
LogStore extends ChangeSupport { @Process(actionType = CloseLogFile.class) public void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel) { LogFile removed = states.remove(action.getName()); if (removed == activeLogFile) { activeLogFile = null; pauseFollow = true; } channel.ack(); } @Inject LogStore(ServerStore serverStore, DispatchAsync dispatcher, Scheduler scheduler, BootstrapContext bootstrap); @Process(actionType = ReadLogFiles.class) void readLogFiles(final Dispatcher.Channel channel); @Process(actionType = ReadLogFilesForRefresh.class) void readLogFilesForRefresh(final Dispatcher.Channel channel); @Process(actionType = OpenLogFile.class) void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel); @Process(actionType = StreamLogFile.class) void streamLogFile(final StreamLogFile action, final Dispatcher.Channel channel); @Process(actionType = RefreshLogFile.class) void refreshLogFile(final RefreshLogFile action, final Dispatcher.Channel channel); @Process(actionType = DownloadLogFile.class) void downloadLogFile(final DownloadLogFile action, final Dispatcher.Channel channel); @Process(actionType = CloseLogFile.class) void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel); @Process(actionType = SelectLogFile.class) void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel); @Process(actionType = NavigateInLogFile.class) void navigate(final NavigateInLogFile action, final Dispatcher.Channel channel); @Process(actionType = ChangePageSize.class) void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel); @Process(actionType = FollowLogFile.class) void follow(final Dispatcher.Channel channel); @Process(actionType = PauseFollowLogFile.class) void pauseFollow(final Dispatcher.Channel channel); @Process(actionType = UnFollowLogFile.class) void unFollow(final Dispatcher.Channel channel); List<ModelNode> getLogFiles(); LogFile getActiveLogFile(); boolean isOpen(final String name); PendingStreamingRequest getPendingStreamingRequest(); final static String FILE_NAME; final static String FILE_SIZE; final static String LAST_MODIFIED_TIMESTAMP; } | @Test public void closeLogFile() { LogFile foo = new LogFile("foo.log", Collections.<String>emptyList(), 0); LogFile bar = new LogFile("bar.log", Collections.<String>emptyList(), 0); store.states.put(foo.getName(), foo); store.states.put(bar.getName(), bar); store.activate(foo); store.closeLogFile(new CloseLogFile("bar.log"), NoopChannel.INSTANCE); assertFalse(store.pauseFollow); LogFile activeLogFile = store.getActiveLogFile(); assertNotNull(activeLogFile); assertSame(foo, activeLogFile); assertEquals(1, store.states.size()); assertSame(foo, store.states.values().iterator().next()); } |
LogStore extends ChangeSupport { @Process(actionType = ChangePageSize.class) public void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel) { if (action.getPageSize() == pageSize) { channel.ack(); } else { pageSize = action.getPageSize(); if (activeLogFile != null) { final ModelNode op = readLogFileOp(activeLogFile.getName()); switch (activeLogFile.getPosition()) { case HEAD: op.get("tail").set(false); break; case LINE_NUMBER: op.get("skip").set(activeLogFile.getSkipped()); break; case TAIL: op.get("tail").set(true); break; } dispatcher.execute(new DMRAction(wrapInComposite(op)), new AsyncCallback<DMRResponse>() { @Override public void onFailure(Throwable caught) { channel.nack(caught); } @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if (response.isFailure()) { channel.nack(new RuntimeException("Failed to change page size to " + pageSize + " for " + activeLogFile + " using " + op + ": " + response.getFailureDescription())); } else { ModelNode compResult = response.get(RESULT); int fileSize = readFileSize(activeLogFile.getName(), compResult); List<String> lines = readLines(compResult); activeLogFile.setFileSize(fileSize); activeLogFile.setLines(lines); channel.ack(); } } }); } } } @Inject LogStore(ServerStore serverStore, DispatchAsync dispatcher, Scheduler scheduler, BootstrapContext bootstrap); @Process(actionType = ReadLogFiles.class) void readLogFiles(final Dispatcher.Channel channel); @Process(actionType = ReadLogFilesForRefresh.class) void readLogFilesForRefresh(final Dispatcher.Channel channel); @Process(actionType = OpenLogFile.class) void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel); @Process(actionType = StreamLogFile.class) void streamLogFile(final StreamLogFile action, final Dispatcher.Channel channel); @Process(actionType = RefreshLogFile.class) void refreshLogFile(final RefreshLogFile action, final Dispatcher.Channel channel); @Process(actionType = DownloadLogFile.class) void downloadLogFile(final DownloadLogFile action, final Dispatcher.Channel channel); @Process(actionType = CloseLogFile.class) void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel); @Process(actionType = SelectLogFile.class) void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel); @Process(actionType = NavigateInLogFile.class) void navigate(final NavigateInLogFile action, final Dispatcher.Channel channel); @Process(actionType = ChangePageSize.class) void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel); @Process(actionType = FollowLogFile.class) void follow(final Dispatcher.Channel channel); @Process(actionType = PauseFollowLogFile.class) void pauseFollow(final Dispatcher.Channel channel); @Process(actionType = UnFollowLogFile.class) void unFollow(final Dispatcher.Channel channel); List<ModelNode> getLogFiles(); LogFile getActiveLogFile(); boolean isOpen(final String name); PendingStreamingRequest getPendingStreamingRequest(); final static String FILE_NAME; final static String FILE_SIZE; final static String LAST_MODIFIED_TIMESTAMP; } | @Test public void changePageSize() { store.changePageSize(new ChangePageSize(42), NoopChannel.INSTANCE); assertEquals(42, store.pageSize); } |
LogStore extends ChangeSupport { @Process(actionType = FollowLogFile.class) public void follow(final Dispatcher.Channel channel) { if (activeLogFile == null) { channel.nack(new IllegalStateException("Unable to follow: No active log file!")); return; } navigate(new NavigateInLogFile(TAIL), channel); activeLogFile.setFollow(true); startFollowing(activeLogFile); } @Inject LogStore(ServerStore serverStore, DispatchAsync dispatcher, Scheduler scheduler, BootstrapContext bootstrap); @Process(actionType = ReadLogFiles.class) void readLogFiles(final Dispatcher.Channel channel); @Process(actionType = ReadLogFilesForRefresh.class) void readLogFilesForRefresh(final Dispatcher.Channel channel); @Process(actionType = OpenLogFile.class) void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel); @Process(actionType = StreamLogFile.class) void streamLogFile(final StreamLogFile action, final Dispatcher.Channel channel); @Process(actionType = RefreshLogFile.class) void refreshLogFile(final RefreshLogFile action, final Dispatcher.Channel channel); @Process(actionType = DownloadLogFile.class) void downloadLogFile(final DownloadLogFile action, final Dispatcher.Channel channel); @Process(actionType = CloseLogFile.class) void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel); @Process(actionType = SelectLogFile.class) void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel); @Process(actionType = NavigateInLogFile.class) void navigate(final NavigateInLogFile action, final Dispatcher.Channel channel); @Process(actionType = ChangePageSize.class) void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel); @Process(actionType = FollowLogFile.class) void follow(final Dispatcher.Channel channel); @Process(actionType = PauseFollowLogFile.class) void pauseFollow(final Dispatcher.Channel channel); @Process(actionType = UnFollowLogFile.class) void unFollow(final Dispatcher.Channel channel); List<ModelNode> getLogFiles(); LogFile getActiveLogFile(); boolean isOpen(final String name); PendingStreamingRequest getPendingStreamingRequest(); final static String FILE_NAME; final static String FILE_SIZE; final static String LAST_MODIFIED_TIMESTAMP; } | @Test public void follow() { LogFile logFile = new LogFile("server.log", Collections.<String>emptyList(), 0); store.states.put(logFile.getName(), logFile); store.activate(logFile); store.follow(NoopChannel.INSTANCE); assertFalse(store.pauseFollow); LogFile activeLogFile = store.getActiveLogFile(); assertNotNull(activeLogFile); assertTrue(activeLogFile.isFollow()); } |
LogStore extends ChangeSupport { @Process(actionType = PauseFollowLogFile.class) public void pauseFollow(final Dispatcher.Channel channel) { if (activeLogFile == null) { channel.nack(new IllegalStateException("Unable to pause follow: No active log file!")); return; } pauseFollow = true; channel.ack(); } @Inject LogStore(ServerStore serverStore, DispatchAsync dispatcher, Scheduler scheduler, BootstrapContext bootstrap); @Process(actionType = ReadLogFiles.class) void readLogFiles(final Dispatcher.Channel channel); @Process(actionType = ReadLogFilesForRefresh.class) void readLogFilesForRefresh(final Dispatcher.Channel channel); @Process(actionType = OpenLogFile.class) void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel); @Process(actionType = StreamLogFile.class) void streamLogFile(final StreamLogFile action, final Dispatcher.Channel channel); @Process(actionType = RefreshLogFile.class) void refreshLogFile(final RefreshLogFile action, final Dispatcher.Channel channel); @Process(actionType = DownloadLogFile.class) void downloadLogFile(final DownloadLogFile action, final Dispatcher.Channel channel); @Process(actionType = CloseLogFile.class) void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel); @Process(actionType = SelectLogFile.class) void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel); @Process(actionType = NavigateInLogFile.class) void navigate(final NavigateInLogFile action, final Dispatcher.Channel channel); @Process(actionType = ChangePageSize.class) void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel); @Process(actionType = FollowLogFile.class) void follow(final Dispatcher.Channel channel); @Process(actionType = PauseFollowLogFile.class) void pauseFollow(final Dispatcher.Channel channel); @Process(actionType = UnFollowLogFile.class) void unFollow(final Dispatcher.Channel channel); List<ModelNode> getLogFiles(); LogFile getActiveLogFile(); boolean isOpen(final String name); PendingStreamingRequest getPendingStreamingRequest(); final static String FILE_NAME; final static String FILE_SIZE; final static String LAST_MODIFIED_TIMESTAMP; } | @Test public void pauseFollow() { LogFile logFile = new LogFile("server.log", Collections.<String>emptyList(), 0); logFile.setFollow(true); store.states.put(logFile.getName(), logFile); store.activate(logFile); store.pauseFollow(NoopChannel.INSTANCE); assertTrue(store.pauseFollow); LogFile activeLogFile = store.getActiveLogFile(); assertNotNull(activeLogFile); assertTrue(activeLogFile.isFollow()); } |
LogStore extends ChangeSupport { @Process(actionType = UnFollowLogFile.class) public void unFollow(final Dispatcher.Channel channel) { if (activeLogFile == null) { channel.nack(new IllegalStateException("Unable to unfollow: No active log file!")); return; } activeLogFile.setFollow(false); channel.ack(); } @Inject LogStore(ServerStore serverStore, DispatchAsync dispatcher, Scheduler scheduler, BootstrapContext bootstrap); @Process(actionType = ReadLogFiles.class) void readLogFiles(final Dispatcher.Channel channel); @Process(actionType = ReadLogFilesForRefresh.class) void readLogFilesForRefresh(final Dispatcher.Channel channel); @Process(actionType = OpenLogFile.class) void openLogFile(final OpenLogFile action, final Dispatcher.Channel channel); @Process(actionType = StreamLogFile.class) void streamLogFile(final StreamLogFile action, final Dispatcher.Channel channel); @Process(actionType = RefreshLogFile.class) void refreshLogFile(final RefreshLogFile action, final Dispatcher.Channel channel); @Process(actionType = DownloadLogFile.class) void downloadLogFile(final DownloadLogFile action, final Dispatcher.Channel channel); @Process(actionType = CloseLogFile.class) void closeLogFile(final CloseLogFile action, final Dispatcher.Channel channel); @Process(actionType = SelectLogFile.class) void selectLogFile(final SelectLogFile action, final Dispatcher.Channel channel); @Process(actionType = NavigateInLogFile.class) void navigate(final NavigateInLogFile action, final Dispatcher.Channel channel); @Process(actionType = ChangePageSize.class) void changePageSize(final ChangePageSize action, final Dispatcher.Channel channel); @Process(actionType = FollowLogFile.class) void follow(final Dispatcher.Channel channel); @Process(actionType = PauseFollowLogFile.class) void pauseFollow(final Dispatcher.Channel channel); @Process(actionType = UnFollowLogFile.class) void unFollow(final Dispatcher.Channel channel); List<ModelNode> getLogFiles(); LogFile getActiveLogFile(); boolean isOpen(final String name); PendingStreamingRequest getPendingStreamingRequest(); final static String FILE_NAME; final static String FILE_SIZE; final static String LAST_MODIFIED_TIMESTAMP; } | @Test public void unFollow() { LogFile logFile = new LogFile("server.log", Collections.<String>emptyList(), 0); logFile.setFollow(true); store.states.put(logFile.getName(), logFile); store.activate(logFile); store.unFollow(NoopChannel.INSTANCE); assertFalse(store.pauseFollow); LogFile activeLogFile = store.getActiveLogFile(); assertNotNull(activeLogFile); assertFalse(activeLogFile.isFollow()); } |
AddressTemplate { public static AddressTemplate of(String template) { return new AddressTemplate(template); } private AddressTemplate(String template); static AddressTemplate of(String template); int getNumTokens(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); AddressTemplate append(String template); AddressTemplate subTemplate(int fromIndex, int toIndex); AddressTemplate replaceWildcards(String wildcard, String... wildcards); String getResourceType(); String getTemplate(); boolean isOptional(); ResourceAddress resolve(StatementContext context, List<String> wildcards); ResourceAddress resolve(StatementContext context, String... wildcards); String resolveAsKey(StatementContext context, String... wildcards); } | @Test(expected = AssertionError.class) public void nil() { AddressTemplate.of(null); } |
LoggerRegistry { public <T extends LogEvent> Logger<T> getLogger(Supplier<?> supplier, Function<? super LoggerKey, ? extends Logger> builder) { final String name = getLoggerName(); return getLogger(name, supplier, builder); } Logger<T> getLogger(Supplier<?> supplier, Function<? super LoggerKey, ? extends Logger> builder); Logger<T> getLogger(String name, Supplier<?> supplier, Function<? super LoggerKey, ? extends Logger> builder); } | @Test public void testDifferentLoggerSuppliersSameNameExplicit(TestInfo info) { final String loggerName = info.getDisplayName(); final Logger logEventLogger = LoggerFactory.getLogger(loggerName); logEventLogger.debug(e -> String.format("Logger %s for LogEvents", loggerName)); final Logger<SpecializedLogEvent> specializedLogEventLogger = LoggerFactory.getLogger(loggerName, new SpecializedLogEventSupplier()); assertFalse(logEventLogger == specializedLogEventLogger); specializedLogEventLogger.debug(e -> { e.name = "Special"; e.version = 2; return String.format("Logger %s for SpecializedLogEvents", loggerName); }); final Logger originalLogger = LoggerFactory.getLogger(loggerName); assertTrue(logEventLogger == originalLogger); }
@Test public void testDifferentLoggerSuppliersSameNameImplicit() { final Logger logEventLogger = LoggerFactory.getLogger(); logEventLogger.debug(e -> String.format("Logger %s ", logEventLogger.getName())); final Logger<SpecializedLogEvent> specializedLogEventLogger = LoggerFactory.getLogger(new SpecializedLogEventSupplier()); assertFalse(logEventLogger == specializedLogEventLogger); specializedLogEventLogger.debug(e -> { e.name = "Special"; e.version = 2; return String.format("Logger %s for SpecializedLogEvents", specializedLogEventLogger.getName()); }); final Logger originalLogger = LoggerFactory.getLogger(); assertTrue(logEventLogger == originalLogger); } |
TokenHeaderUtility { @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") public Token getAuthorizationToken(final ContainerRequest request) { String authorizationString = request.getHeaderString("Authorization"); if (authorizationString != null && !"".equals(authorizationString)) { authorizationString = authorizationString.trim(); final String[] components = authorizationString.split("\\s"); if (components.length != 2) { throw new NotAuthorizedException(authenticationType); } final String scheme = components[0]; if (!authenticationType.equalsIgnoreCase(scheme)) { throw new NotAuthorizedException(authenticationType); } final String tokenString = components[1]; return Token.fromString(tokenString); } return null; } @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") Token getAuthorizationToken(final ContainerRequest request); Token getXAuthorizationToken(final ContainerRequest request); } | @Test public final void verifyGetAuthorizationTokenDeserialisesBearerToken() { final Key key = Key.generateKey(random); final Token token = Token.generate(random, key, "hello"); final ContainerRequest request = mock(ContainerRequest.class); given(request.getHeaderString("Authorization")).willReturn("Bearer " + token.serialise()); final Token result = utility.getAuthorizationToken(request); assertEquals(token.serialise(), result.serialise()); }
@Test public final void verifyGetAuthorizationTokenRejectsMalformedHeader() { final ContainerRequest request = mock(ContainerRequest.class); given(request.getHeaderString("Authorization")).willReturn("Basic YWxpY2U6cGFzc3dvcmQ= 76bd6d14-0148-43c4-8ea0-8368336ce9f1"); assertThrows(NotAuthorizedException.class, () -> utility.getAuthorizationToken(request)); }
@Test public final void verifyGetAuthorizationTokenRejectsInvalidScheme() { final ContainerRequest request = mock(ContainerRequest.class); given(request.getHeaderString("Authorization")).willReturn("Basic YWxpY2U6cGFzc3dvcmQ="); assertThrows(NotAuthorizedException.class, () -> utility.getAuthorizationToken(request)); }
@Test public final void verifyGetAuthorizationTokenIgnoresX() { final Key key = Key.generateKey(random); final Token token = Token.generate(random, key, "hello"); final ContainerRequest request = mock(ContainerRequest.class); given(request.getHeaderString("X-Authorization")).willReturn(token.serialise()); final Token result = utility.getAuthorizationToken(request); assertNull(result); } |
SimpleFernetKeyRotator extends AbstractFernetKeyRotator { protected void testSecret(final String secretId, final String clientRequestToken) { final ByteBuffer buffer = getSecretsManager().getSecretVersion(secretId, clientRequestToken); try { if (buffer.remaining() != fernetKeySize) { throw new IllegalStateException("Fernet key must be exactly " + fernetKeySize + " bytes"); } final byte[] signingKey = new byte[16]; buffer.get(signingKey); final byte[] encryptionKey = new byte[16]; buffer.get(encryptionKey); if (buffer.hasRemaining()) { throw new IllegalStateException("Encountered extra bytes."); } new Key(signingKey, encryptionKey); wipe(signingKey); wipe(encryptionKey); } finally { wipe(buffer); } getLogger().info("testSecret: Successfully validated Fernet Key for ARN {} and version {}.", secretId, clientRequestToken); } protected SimpleFernetKeyRotator(final SecretsManager secretsManager, final AWSKMS kms, final SecureRandom random); protected SimpleFernetKeyRotator(final SecureRandom random); SimpleFernetKeyRotator(); } | @Test public final void verifyTestClearsIntermediateSecret() { final byte[] secretBytes = new byte[32]; for (byte i = 32; --i >= 0; secretBytes[i] = i); final ByteBuffer secretByteBuffer = ByteBuffer.wrap(secretBytes); assertTrue(Arrays.equals(secretByteBuffer.array(), secretBytes)); given(secretsManager.getSecretVersion("secretId", "clientRequestToken")).willReturn(secretByteBuffer); rotator.testSecret("secretId", "clientRequestToken"); final byte[] modifiedBytes = secretByteBuffer.array(); assertEquals(32, modifiedBytes.length); for (int i = modifiedBytes.length; --i >= 0; assertEquals(0, modifiedBytes[i])); } |
AbstractFernetKeyRotator implements RequestStreamHandler { @SuppressWarnings("PMD.DataflowAnomalyAnalysis") protected void finishSecret(final String secretId, final String clientRequestToken, final Map<String, List<String>> versions) { final Entry<? extends String, ?> currentEntry = versions.entrySet().stream().filter(entry -> { final Collection<? extends String> versionStages = entry.getValue(); return versionStages.contains(CURRENT.getAwsName() ); }).findFirst().orElseThrow(() -> new IllegalStateException("No AWSCURRENT secret set for " + secretId + ".")); final String currentVersion = currentEntry.getKey(); if (currentVersion.equalsIgnoreCase(clientRequestToken)) { getLogger().warn("finishSecret: Version {} already marked as AWSCURRENT for {}", currentVersion, secretId); return; } getSecretsManager().rotateSecret(secretId, clientRequestToken, currentVersion); getLogger().info("finishSecret: Successfully set AWSCURRENT stage to version {} for secret {}.", clientRequestToken, secretId); } protected AbstractFernetKeyRotator(final SecretsManager secretsManager, final AWSKMS kms,
final SecureRandom random); protected AbstractFernetKeyRotator(final ObjectMapper mapper, final SecretsManager secretsManager, final AWSKMS kms,
final SecureRandom random); void handleRequest(final InputStream input, final OutputStream output, final Context context); } | @Test public final void verifyFinishSecretDoesNothing() { final Map<String, List<String>> versions = new HashMap<>(); versions.put("version", singletonList("AWSCURRENT")); rotator.finishSecret("secret", "version", versions); verifyNoMoreInteractions(secretsManager); }
@Test public final void verifyFinishSecretFails() { final Map<String, List<String>> versions = new HashMap<>(); versions.put("version", singletonList("AWSPENDING")); assertThrows(RuntimeException.class, () -> rotator.finishSecret("secret", "version", versions)); }
@Test public final void verifyFinishSecretRotatesSecret() { final Map<String, List<String>> versions = new HashMap<>(); versions.put("newVersion", singletonList("AWSPENDING")); versions.put("oldVersion", singletonList("AWSCURRENT")); rotator.finishSecret("secret", "newVersion", versions); verify(secretsManager).rotateSecret("secret", "newVersion", "oldVersion"); } |
AbstractFernetKeyRotator implements RequestStreamHandler { protected void seed() { if (!seeded.get()) { synchronized (random) { if (!seeded.get()) { getLogger().debug("Seeding random number generator"); final GenerateRandomRequest request = new GenerateRandomRequest(); request.setNumberOfBytes(512); final GenerateRandomResult result = getKms().generateRandom(request); final ByteBuffer randomBytes = result.getPlaintext(); final byte[] bytes = new byte[randomBytes.remaining()]; randomBytes.get(bytes); random.setSeed(bytes); seeded.set(true); getLogger().debug("Seeded random number generator"); } } } } protected AbstractFernetKeyRotator(final SecretsManager secretsManager, final AWSKMS kms,
final SecureRandom random); protected AbstractFernetKeyRotator(final ObjectMapper mapper, final SecretsManager secretsManager, final AWSKMS kms,
final SecureRandom random); void handleRequest(final InputStream input, final OutputStream output, final Context context); } | @Test public final void verifySeedOnlyRunsOnce() { final GenerateRandomResult randomResult = new GenerateRandomResult(); final byte[] bytes = new byte[512]; Arrays.fill(bytes, (byte)17); randomResult.setPlaintext(ByteBuffer.wrap(bytes)); given(kms.generateRandom(any(GenerateRandomRequest.class))).willReturn(randomResult); rotator.seed(); rotator.seed(); verify(random, times(1)).setSeed(bytes); } |
SecretsManager { public void assertCurrentStageExists(final String secretId) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionStage(CURRENT.getAwsName()); getDelegate().getSecretValue(getSecretValueRequest); } SecretsManager(final AWSSecretsManager delegate); void shutdown(); void assertCurrentStageExists(final String secretId); DescribeSecretResult describeSecret(final String secretId); ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken); ByteBuffer getSecretStage(final String secretId, final Stage stage); void rotateSecret(final String secretId, final String clientRequestToken,
final String currentVersion); void putSecretValue(final String secretId, final String clientRequestToken, final Key key, final Stage stage); void putSecretValue(final String secretId, final String clientRequestToken, final Collection<? extends Key> keys,
final Stage stage); } | @Test public final void verifyAssertCurrentStageExistsThrowsException() { final GetSecretValueRequest request = new GetSecretValueRequest(); request.setSecretId("secret"); request.setVersionStage("AWSCURRENT"); given(delegate.getSecretValue(eq(request))).willThrow(new ResourceNotFoundException("not found")); assertThrows(ResourceNotFoundException.class, () -> manager.assertCurrentStageExists("secret")); }
@Test public final void verifyAssertDoesNothing() { final GetSecretValueRequest request = new GetSecretValueRequest(); request.setSecretId("secret"); request.setVersionStage("AWSCURRENT"); given(delegate.getSecretValue(eq(request))).willReturn(new GetSecretValueResult()); manager.assertCurrentStageExists("secret"); } |
SecretsManager { public DescribeSecretResult describeSecret(final String secretId) { final DescribeSecretRequest describeSecretRequest = new DescribeSecretRequest(); describeSecretRequest.setSecretId(secretId); return getDelegate().describeSecret(describeSecretRequest); } SecretsManager(final AWSSecretsManager delegate); void shutdown(); void assertCurrentStageExists(final String secretId); DescribeSecretResult describeSecret(final String secretId); ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken); ByteBuffer getSecretStage(final String secretId, final Stage stage); void rotateSecret(final String secretId, final String clientRequestToken,
final String currentVersion); void putSecretValue(final String secretId, final String clientRequestToken, final Key key, final Stage stage); void putSecretValue(final String secretId, final String clientRequestToken, final Collection<? extends Key> keys,
final Stage stage); } | @Test public final void verifyDescribeSecretPassesThrough() { final DescribeSecretRequest request = new DescribeSecretRequest(); request.setSecretId("secret"); final DescribeSecretResult sampleResult = new DescribeSecretResult(); sampleResult.setRotationEnabled(true); sampleResult.addVersionIdsToStagesEntry("version", singletonList("AWSPREVIOUS")); given(delegate.describeSecret(eq(request))).willReturn(sampleResult); final DescribeSecretResult result = manager.describeSecret("secret"); assertTrue(result.isRotationEnabled()); assertTrue(result.getVersionIdsToStages().get("version").contains("AWSPREVIOUS")); } |
SecretsManager { public ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionId(clientRequestToken); final GetSecretValueResult result = getDelegate().getSecretValue(getSecretValueRequest); return result.getSecretBinary(); } SecretsManager(final AWSSecretsManager delegate); void shutdown(); void assertCurrentStageExists(final String secretId); DescribeSecretResult describeSecret(final String secretId); ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken); ByteBuffer getSecretStage(final String secretId, final Stage stage); void rotateSecret(final String secretId, final String clientRequestToken,
final String currentVersion); void putSecretValue(final String secretId, final String clientRequestToken, final Key key, final Stage stage); void putSecretValue(final String secretId, final String clientRequestToken, final Collection<? extends Key> keys,
final Stage stage); } | @Test public final void verifyGetSecretVersionRetrievesBinary() throws UnsupportedEncodingException { final GetSecretValueRequest request = new GetSecretValueRequest(); request.setSecretId("secret"); request.setVersionId("version"); final GetSecretValueResult response = new GetSecretValueResult(); response.setSecretBinary(ByteBuffer.wrap("expected".getBytes("UTF-8"))); given(delegate.getSecretValue(eq(request))).willReturn(response); final ByteBuffer result = manager.getSecretVersion("secret", "version"); final byte[] buffer = new byte[result.remaining()]; result.get(buffer); assertEquals("expected", new String(buffer, "UTF-8")); } |
SecretsManager { public ByteBuffer getSecretStage(final String secretId, final Stage stage) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionStage(stage.getAwsName()); final GetSecretValueResult result = getDelegate().getSecretValue(getSecretValueRequest); return result.getSecretBinary(); } SecretsManager(final AWSSecretsManager delegate); void shutdown(); void assertCurrentStageExists(final String secretId); DescribeSecretResult describeSecret(final String secretId); ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken); ByteBuffer getSecretStage(final String secretId, final Stage stage); void rotateSecret(final String secretId, final String clientRequestToken,
final String currentVersion); void putSecretValue(final String secretId, final String clientRequestToken, final Key key, final Stage stage); void putSecretValue(final String secretId, final String clientRequestToken, final Collection<? extends Key> keys,
final Stage stage); } | @Test public final void verifyGetSecretStageRetrievesBinary() throws UnsupportedEncodingException { final GetSecretValueRequest request = new GetSecretValueRequest(); request.setSecretId("secret"); request.setVersionStage("AWSPENDING"); final GetSecretValueResult response = new GetSecretValueResult(); response.setSecretBinary(ByteBuffer.wrap("expected".getBytes("UTF-8"))); given(delegate.getSecretValue(eq(request))).willReturn(response); final ByteBuffer result = manager.getSecretStage("secret", PENDING); final byte[] buffer = new byte[result.remaining()]; result.get(buffer); assertEquals("expected", new String(buffer, "UTF-8")); } |
SecretsManager { public void rotateSecret(final String secretId, final String clientRequestToken, final String currentVersion) { final UpdateSecretVersionStageRequest updateSecretVersionStageRequest = new UpdateSecretVersionStageRequest(); updateSecretVersionStageRequest.setSecretId(secretId); updateSecretVersionStageRequest.setVersionStage(CURRENT.getAwsName()); updateSecretVersionStageRequest.setMoveToVersionId(clientRequestToken); updateSecretVersionStageRequest.setRemoveFromVersionId(currentVersion); getDelegate().updateSecretVersionStage(updateSecretVersionStageRequest); } SecretsManager(final AWSSecretsManager delegate); void shutdown(); void assertCurrentStageExists(final String secretId); DescribeSecretResult describeSecret(final String secretId); ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken); ByteBuffer getSecretStage(final String secretId, final Stage stage); void rotateSecret(final String secretId, final String clientRequestToken,
final String currentVersion); void putSecretValue(final String secretId, final String clientRequestToken, final Key key, final Stage stage); void putSecretValue(final String secretId, final String clientRequestToken, final Collection<? extends Key> keys,
final Stage stage); } | @Test public final void verifyRotateSecretTagsNewKeyAndUntagsOldKey() { manager.rotateSecret("secret", "new", "old"); final UpdateSecretVersionStageRequest request = new UpdateSecretVersionStageRequest(); request.setSecretId("secret"); request.setVersionStage("AWSCURRENT"); request.setMoveToVersionId("new"); request.setRemoveFromVersionId("old"); verify(delegate).updateSecretVersionStage(eq(request)); } |
SecretsManager { public void putSecretValue(final String secretId, final String clientRequestToken, final Key key, final Stage stage) { putSecretValue(secretId, clientRequestToken, singletonList(key), stage); } SecretsManager(final AWSSecretsManager delegate); void shutdown(); void assertCurrentStageExists(final String secretId); DescribeSecretResult describeSecret(final String secretId); ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken); ByteBuffer getSecretStage(final String secretId, final Stage stage); void rotateSecret(final String secretId, final String clientRequestToken,
final String currentVersion); void putSecretValue(final String secretId, final String clientRequestToken, final Key key, final Stage stage); void putSecretValue(final String secretId, final String clientRequestToken, final Collection<? extends Key> keys,
final Stage stage); } | @Test public final void verifyPutSecretValueStoresKey() throws IOException { final String expected = "expected"; final Key key = mock(Key.class); final Answer<?> answer = new Answer<Void>() { public Void answer(final InvocationOnMock invocation) throws Throwable { final OutputStream stream = invocation.getArgument(0); stream.write(expected.getBytes("UTF-8")); return null; } }; doAnswer(answer).when(key).writeTo(any(OutputStream.class)); manager.putSecretValue("secret", "version", key, PREVIOUS); final PutSecretValueRequest request = new PutSecretValueRequest(); request.setSecretId("secret"); request.setClientRequestToken("version"); request.setVersionStages(singleton("AWSPREVIOUS")); request.setSecretBinary(ByteBuffer.wrap(expected.getBytes("UTF-8"))); verify(delegate).putSecretValue(eq(request)); }
@Test public final void verifyPutSecretValueStoresKeys() throws IOException { final String expected = "expected"; final Key key0 = mock(Key.class); final Key key1 = mock(Key.class); final Answer<?> answer = new Answer<Void>() { public Void answer(final InvocationOnMock invocation) throws Throwable { final OutputStream stream = invocation.getArgument(0); stream.write(expected.getBytes("UTF-8")); return null; } }; doAnswer(answer).when(key0).writeTo(any(OutputStream.class)); doAnswer(answer).when(key1).writeTo(any(OutputStream.class)); manager.putSecretValue("secret", "version", asList(key0, key1), PREVIOUS); final PutSecretValueRequest request = new PutSecretValueRequest(); request.setSecretId("secret"); request.setClientRequestToken("version"); request.setVersionStages(singleton("AWSPREVIOUS")); request.setSecretBinary(ByteBuffer.wrap((expected + expected).getBytes("UTF-8"))); verify(delegate).putSecretValue(eq(request)); } |
Token { public static Token fromString(final String string) { return fromBytes(decoder.decode(string)); } @SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"}) protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac); @SuppressWarnings({"PMD.PrematureDeclaration", "PMD.DataflowAnomalyAnalysis"}) static Token fromBytes(final byte[] bytes); static Token fromString(final String string); static Token generate(final Key key, final String plainText); static Token generate(final SecureRandom random, final Key key, final String plainText); static Token generate(final Key key, final byte[] payload); static Token generate(final SecureRandom random, final Key key, final byte[] payload); @SuppressWarnings("PMD.LawOfDemeter") T validateAndDecrypt(final Key key, final Validator<T> validator); @SuppressWarnings("PMD.LawOfDemeter") T validateAndDecrypt(final Collection<? extends Key> keys, final Validator<T> validator); @SuppressWarnings("PMD.LawOfDemeter") String serialise(); @SuppressWarnings("PMD.LawOfDemeter") void writeTo(final OutputStream outputStream); byte getVersion(); Instant getTimestamp(); IvParameterSpec getInitializationVector(); String toString(); boolean isValidSignature(final Key key); } | @Test public void testFromString() { final String string = "gAAAAAAdwJ6wAAECAwQFBgcICQoLDA0ODy021cpGVWKZ_eEwCGM4BLLF_5CV9dOPmrhuVUPgJobwOz7JcbmrR64jVmpU4IwqDA=="; final Token result = Token.fromString(string); assertEquals((byte) 0x80, result.getVersion()); assertEquals(Instant.from(formatter.parse("1985-10-26T01:20:00-07:00")), result.getTimestamp()); assertArrayEquals(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, result.getInitializationVector().getIV()); } |
Token { public static Token generate(final Key key, final String plainText) { return generate(new SecureRandom(), key, plainText); } @SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"}) protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac); @SuppressWarnings({"PMD.PrematureDeclaration", "PMD.DataflowAnomalyAnalysis"}) static Token fromBytes(final byte[] bytes); static Token fromString(final String string); static Token generate(final Key key, final String plainText); static Token generate(final SecureRandom random, final Key key, final String plainText); static Token generate(final Key key, final byte[] payload); static Token generate(final SecureRandom random, final Key key, final byte[] payload); @SuppressWarnings("PMD.LawOfDemeter") T validateAndDecrypt(final Key key, final Validator<T> validator); @SuppressWarnings("PMD.LawOfDemeter") T validateAndDecrypt(final Collection<? extends Key> keys, final Validator<T> validator); @SuppressWarnings("PMD.LawOfDemeter") String serialise(); @SuppressWarnings("PMD.LawOfDemeter") void writeTo(final OutputStream outputStream); byte getVersion(); Instant getTimestamp(); IvParameterSpec getInitializationVector(); String toString(); boolean isValidSignature(final Key key); } | @Test public void testGenerate() { final SecureRandom deterministicRandom = new SecureRandom() { private static final long serialVersionUID = 3075400891983079965L; public void nextBytes(final byte[] bytes) { for (int i = bytes.length; --i >= 0; bytes[i] = 1); } }; final Key key = Key.generateKey(deterministicRandom); final Token result = Token.generate(deterministicRandom, key, "Hello, world!"); final String plainText = result.validateAndDecrypt(key, validator); assertEquals("Hello, world!", plainText); } |
Token { @SuppressWarnings("PMD.LawOfDemeter") public String serialise() { try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream( tokenStaticBytes + getCipherText().length)) { writeTo(byteStream); return getEncoder().encodeToString(byteStream.toByteArray()); } catch (final IOException e) { throw new IllegalStateException(e.getMessage(), e); } } @SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"}) protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac); @SuppressWarnings({"PMD.PrematureDeclaration", "PMD.DataflowAnomalyAnalysis"}) static Token fromBytes(final byte[] bytes); static Token fromString(final String string); static Token generate(final Key key, final String plainText); static Token generate(final SecureRandom random, final Key key, final String plainText); static Token generate(final Key key, final byte[] payload); static Token generate(final SecureRandom random, final Key key, final byte[] payload); @SuppressWarnings("PMD.LawOfDemeter") T validateAndDecrypt(final Key key, final Validator<T> validator); @SuppressWarnings("PMD.LawOfDemeter") T validateAndDecrypt(final Collection<? extends Key> keys, final Validator<T> validator); @SuppressWarnings("PMD.LawOfDemeter") String serialise(); @SuppressWarnings("PMD.LawOfDemeter") void writeTo(final OutputStream outputStream); byte getVersion(); Instant getTimestamp(); IvParameterSpec getInitializationVector(); String toString(); boolean isValidSignature(final Key key); } | @Test public void testSerialise() { final IvParameterSpec initializationVector = new IvParameterSpec( new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); final Token invalidToken = new Token((byte) 0x80, Instant.ofEpochSecond(0), initializationVector, new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}); final String result = invalidToken.serialise(); assertEquals( "gAAAAAAAAAAAAQIDBAUGBwgJCgsMDQ4PEAECAwQFBgcICQoLDA0ODxABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fIA==", result); } |
Key { public static Key generateKey() { return generateKey(new SecureRandom()); } Key(final byte[] signingKey, final byte[] encryptionKey); Key(final byte[] concatenatedKeys); Key(final String string); static Key generateKey(); static Key generateKey(final SecureRandom random); byte[] sign(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText); @SuppressWarnings("PMD.LawOfDemeter") byte[] encrypt(final byte[] payload, final IvParameterSpec initializationVector); @SuppressWarnings("PMD.LawOfDemeter") String serialise(); void writeTo(final OutputStream outputStream); int hashCode(); @SuppressWarnings("PMD.LawOfDemeter") boolean equals(final Object obj); } | @Test public void testGenerateKey() { final SecureRandom deterministicRandom = new SecureRandom() { private static final long serialVersionUID = 6548702184401342900L; public void nextBytes(final byte[] bytes) { for (int i = signingKeyBytes; --i >= 0; bytes[i] = 1); } }; final Key result = Key.generateKey(deterministicRandom); final byte[] signingKey = result.getSigningKeySpec().getEncoded(); for (int i = signingKeyBytes; --i >= 0;) { assertEquals(1, signingKey[i]); } final byte[] encryptionKey = result.getEncryptionKeySpec().getEncoded(); for (int i = encryptionKeyBytes; --i >= 0;) { assertEquals(1, encryptionKey[i]); } } |
Key { public byte[] sign(final byte version, final Instant timestamp, final IvParameterSpec initializationVector, final byte[] cipherText) { try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream( getTokenPrefixBytes() + cipherText.length)) { return sign(version, timestamp, initializationVector, cipherText, byteStream); } catch (final IOException e) { throw new IllegalStateException(e.getMessage(), e); } } Key(final byte[] signingKey, final byte[] encryptionKey); Key(final byte[] concatenatedKeys); Key(final String string); static Key generateKey(); static Key generateKey(final SecureRandom random); byte[] sign(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText); @SuppressWarnings("PMD.LawOfDemeter") byte[] encrypt(final byte[] payload, final IvParameterSpec initializationVector); @SuppressWarnings("PMD.LawOfDemeter") String serialise(); void writeTo(final OutputStream outputStream); int hashCode(); @SuppressWarnings("PMD.LawOfDemeter") boolean equals(final Object obj); } | @Test public void testGetHmac() { final Key key = new Key("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="); final byte[] result = key.sign((byte) 0x80, Instant.ofEpochSecond(1), new IvParameterSpec(new byte[] {2}), new byte[] {3}); assertEquals("WvLIvt4MSCQKgeLyvltUqN8O7mvcozhsEAgIiytxypw=", encoder.encodeToString(result)); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.