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 : ...
@Test public void testCanHandleMissingTableTypeMappings() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setDefaultTypeMappings(Collections.emptyList()); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEqu...
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.ge...
@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...
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForColumn(schemacrawler.schema.Column column) { String tableName = column.getParent().getName().toUpperCase(); SingularAttribute singularAttribute = singularAttributesByColumnName.get(new QualifiedColumnName(tableN...
@Test public void testGetMethodNameForColumnJoined() throws Exception { Assert.assertEquals("superJoinedImpliciteNameColumn", provider.getMethodNameForColumn(getColumn("MANAGEDSUPERCLASSJOINED", "SUPERJOINEDIMPLICITENAMECOLUMN"))); Assert.assertEquals("superJoinedExpliciteNameColumn", provider.getMethodNameForColumn(ge...
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().getParen...
@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.executePrepara...
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(tab...
@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.executePreparationScri...
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().getNa...
@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 mo...
XmlFileConvenienceSetterProvider implements ConvenienceSetterProvider { @Override public List<ConvenienceSetterModel> getConvenienceSetters(Column column, String javaDataTypeName) { return this.convenienceSetterConfig.getConvenienceSetterConfigs().stream() .filter(dataTypeConvenienceSetterConfig -> dataTypeConvenienceS...
@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);...
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 Lis...
@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.exec...
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 ...
@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 { throw...
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 firstC...
@Test public void testFirstCharacterToLowerCase() { assertEquals("hello", NameUtils.firstCharacterToLowerCase("hello")); assertEquals("hello", NameUtils.firstCharacterToLowerCase("Hello")); assertEquals("hELLO", NameUtils.firstCharacterToLowerCase("HELLO")); assertEquals("4heLLo", NameUtils.firstCharacterToLowerCase("4...
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 firstC...
@Test public void testFirstCharacterToUpperCase() { assertEquals("Hello", NameUtils.firstCharacterToUpperCase("hello")); assertEquals("Hello", NameUtils.firstCharacterToUpperCase("Hello")); assertEquals("HELLO", NameUtils.firstCharacterToUpperCase("HELLO")); assertEquals("4heLLo", NameUtils.firstCharacterToUpperCase("4...
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, Str...
@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 = ne...
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(Obj...
@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(n...
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 expli...
@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(connect...
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...
@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.executePrep...
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("Filli...
@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.executePrepa...
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...
@Test public void testTransform() throws Exception { PreparedStatement preparedStatementMock = Mockito.mock(PreparedStatement.class); DefaultPreparedStatementParameterSetter parameterSetter = new DefaultPreparedStatementParameterSetter(); parameterSetter.setParameter(preparedStatementMock, 1, "test", createMockAttribut...
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 setFallbackStra...
@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(); Asse...
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 setFallbackStrat...
@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....
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 setFallbackStrateg...
@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.ge...
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getMethodNameForReference(ForeignKey foreignKey) { ForeignKeyRelation foreignKeyRelation = toForeignKeyRelation(foreignKey); SingularAttribute singularAttribute = singularAttributesByForeignKeyRelation.get(foreignKeyRelation); ...
@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", "REF...
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 setFal...
@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> ty...
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() + "." + colu...
@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...
JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getCanonicalDataTypeName(schemacrawler.schema.Column column) { SingularAttribute singularAttribute; if (column.isPartOfForeignKey()) { Optional<ForeignKeyColumnReference> foreignKeyColumnReferenceOptional = column.getParent().g...
@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.getCan...
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 Cla...
@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(...
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> condit...
@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...
@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)...
@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> condi...
@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); ...
@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 P...
@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 Pre...
@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> columnNam...
@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> fullTableN...
@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(""...
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> fullTableN...
@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(""...
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>...
@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(""...
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 pr...
@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(...
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...
@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...
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 PluggableDefaultValu...
@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 ...
@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((k...
AbstractRedG { public List<RedGEntity> getEntities() { return Collections.unmodifiableList(entities); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(final DefaultValueStrategy defaultValueStrategy); SQLValuesFormatter getSqlValuesFormatter(); voi...
@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, DataTy...
@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.g...
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 = dummyF...
@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(DefaultDummy...
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 tha...
@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("MockEnti...
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); DefaultValueS...
@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)); assert...
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 defa...
@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()); entiti...
AbstractRedG { public void insertDataIntoDatabase(final Connection connection) { RedGDatabaseUtil.insertDataIntoDatabase(getEntitiesSortedForInsert(), connection, preparedStatementParameterSetter); } void addEntity(final RedGEntity entity); DefaultValueStrategy getDefaultValueStrategy(); void setDefaultValueStrategy(f...
@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(Coll...
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 LocalD...
@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)); assertEqu...
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...
@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-01T...
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 "...
@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.formatValu...
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"); ...
@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"); columnTyp...
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 reques...
@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 requ...
@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...
@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() - join...
@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...
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 Strin...
@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 p...
@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 setEx...
@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 num...
@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); stati...
@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 (p...
@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(S...
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)...
@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 readLogFilesAndVerify...
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...
@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 o...
@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(...
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> w...
@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.replaceWildca...
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...
@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.appe...
@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 = n...
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(...
@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 ModelN...
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(); ...
@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", "Tabl...
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 ...
@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 TestProcedu...
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); dis...
@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()...
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 " + ac...
@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(...
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 LogS...
@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...
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 = read...
@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.setFol...
@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(activeL...
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 LogSto...
@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.getActi...
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 LogS...
@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.getActiveLog...
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(); AddressTempl...
@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> build...
@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> specializ...
TokenHeaderUtility { @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") public Token getAuthorizationToken(final ContainerRequest request) { String authorizationString = request.getHeaderString("Authorization"); if (authorizationString != null && !"".equals(authorizationString)) { authorizationString = authorizationSt...
@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.se...
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("Fe...
@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.getSecretVersi...
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(...
@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() {...
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 GenerateRando...
@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(randomResul...
SecretsManager { public void assertCurrentStageExists(final String secretId) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionStage(CURRENT.getAwsName()); getDelegate().getSecretValue(getSecretValueRequest); }...
@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")); assertThro...
SecretsManager { public DescribeSecretResult describeSecret(final String secretId) { final DescribeSecretRequest describeSecretRequest = new DescribeSecretRequest(); describeSecretRequest.setSecretId(secretId); return getDelegate().describeSecret(describeSecretRequest); } SecretsManager(final AWSSecretsManager delegate...
@Test public final void verifyDescribeSecretPassesThrough() { final DescribeSecretRequest request = new DescribeSecretRequest(); request.setSecretId("secret"); final DescribeSecretResult sampleResult = new DescribeSecretResult(); sampleResult.setRotationEnabled(true); sampleResult.addVersionIdsToStagesEntry("version", ...
SecretsManager { public ByteBuffer getSecretVersion(final String secretId, final String clientRequestToken) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionId(clientRequestToken); final GetSecretValueResult r...
@Test public final void verifyGetSecretVersionRetrievesBinary() throws UnsupportedEncodingException { final GetSecretValueRequest request = new GetSecretValueRequest(); request.setSecretId("secret"); request.setVersionId("version"); final GetSecretValueResult response = new GetSecretValueResult(); response.setSecretBin...
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 = getDe...
@Test public final void verifyGetSecretStageRetrievesBinary() throws UnsupportedEncodingException { final GetSecretValueRequest request = new GetSecretValueRequest(); request.setSecretId("secret"); request.setVersionStage("AWSPENDING"); final GetSecretValueResult response = new GetSecretValueResult(); response.setSecre...
SecretsManager { public void rotateSecret(final String secretId, final String clientRequestToken, final String currentVersion) { final UpdateSecretVersionStageRequest updateSecretVersionStageRequest = new UpdateSecretVersionStageRequest(); updateSecretVersionStageRequest.setSecretId(secretId); updateSecretVersionStageR...
@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.se...
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...
@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); ...
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[] cipher...
@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...
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, ...
@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); f...
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 IllegalS...
@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, ...
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 I...
@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(deterministicR...
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, ...
@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(resul...