method2testcases
stringlengths 118
6.63k
|
---|
### Question:
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); }### Answer:
@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))); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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()); } } } |
### Question:
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); }### Answer:
@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", "", ""); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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]"); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
ClassAvailabilityChecker { public boolean isAvailable() { return available; } ClassAvailabilityChecker(String fqcn); boolean isAvailable(); }### Answer:
@Test public void testHappyPaths() throws Exception { Assert.assertTrue(new ClassAvailabilityChecker("java.util.HashMap").isAvailable()); Assert.assertFalse(new ClassAvailabilityChecker("no.java.util.HashMap").isAvailable()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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"))); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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"))); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test public void eq() { assertThat(Conditions.eq("A")) .accepts("A") .rejects("B", "C"); } |
### Question:
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); }### Answer:
@Test public void neq() { assertThat(Conditions.neq("A")) .rejects("A") .accepts("B", "C"); } |
### Question:
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); }### Answer:
@Test public void contains() { assertThat(Conditions.contains("A")) .accepts("A", "AB", "BA", "ABBA") .rejects("B", "BODO"); } |
### Question:
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); }### Answer:
@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")) ); } |
### Question:
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); }### Answer:
@Test public void matchesRegex() { assertThat(Conditions.matchesRegex("Hallo.+")) .accepts("Hallo Welt", "Hallo BTC") .rejects("Hello World"); } |
### Question:
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); }### Answer:
@Test public void testGetDefaultValue() { ConditionalProvider provider = new ConditionalProvider(new NoProvider(), null, null, null); assertThat(provider.getDefaultValue(getModel("A", "B", "C.B"), String.class)).isNull(); } |
### Question:
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); }### Answer:
@Test public void willProvide() { assertThat(new DefaultDefaultValueProvider().willProvide(null)).isTrue(); assertThat(new DefaultDefaultValueProvider().willProvide(mock(ColumnModel.class))).isTrue(); } |
### Question:
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); }### Answer:
@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)); }); } |
### Question:
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(); }### Answer:
@Test public void testGetEntities() throws Exception { MockRedG mockRedG = new MockRedG(); RedGEntity e = new MockEntity1(); mockRedG.addEntity(e); assertThat(mockRedG.getEntities()).containsExactly(e); } |
### Question:
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); }### Answer:
@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"); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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", "", "", "")); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; }### Answer:
@Test public void getInstance() throws Exception { } |
### Question:
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; }### Answer:
@Test public void getLayoutId() throws Exception { } |
### Question:
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; }### Answer:
@Test public void initView() throws Exception { } |
### Question:
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); }### Answer:
@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 )")); } |
### Question:
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); }### Answer:
@Test public void placeholders() { assertThat(SqlStringUtils.placeholders(1), is("?")); assertThat(SqlStringUtils.placeholders(5).replaceAll(" ", ""), is("?,?,?,?,?")); } |
### Question:
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); }### Answer:
@Test public void placeholderRows() { assertThat(SqlStringUtils.placeholderRows(3, 2).replaceAll(" ", ""), is("(?,?),(?,?),(?,?)")); } |
### Question:
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); }### Answer:
@Test public void literal() { assertThat(SqlStringUtils.literal("foo"), is("'foo'")); } |
### Question:
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); }### Answer:
@Test public void setExpressionWithPlaceholders() { assertThat( SqlStringUtils.setExpressionWithPlaceholders(asList("CITY", "ADDRESS")).toString() .replaceAll(" ", ""), is("CITY=?,ADDRESS=?") ); } |
### Question:
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); }### Answer:
@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=?") ); } |
### Question:
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); }### Answer:
@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) ); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@Test public void changePageSize() { store.changePageSize(new ChangePageSize(42), NoopChannel.INSTANCE); assertEquals(42, store.pageSize); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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); }### Answer:
@Test(expected = AssertionError.class) public void nil() { AddressTemplate.of(null); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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])); } |
### Question:
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); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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]); } } |
### Question:
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); }### Answer:
@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)); } |
### Question:
Key { protected java.security.Key getSigningKeySpec() { return new SecretKeySpec(getSigningKey(), getSigningAlgorithm()); } 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); }### Answer:
@Test public void testGetSigningKeySpec() { final Key key = new Key("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="); final java.security.Key result = key.getSigningKeySpec(); assertEquals("HmacSHA256", result.getAlgorithm()); } |
### Question:
Key { protected SecretKeySpec getEncryptionKeySpec() { return new SecretKeySpec(getEncryptionKey(), getEncryptionAlgorithm()); } 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); }### Answer:
@Test public void testGetEncryptionKeySpec() { final Key key = new Key("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="); final SecretKeySpec result = key.getEncryptionKeySpec(); assertEquals("AES", result.getAlgorithm()); } |
### Question:
Key { @SuppressWarnings("PMD.LawOfDemeter") public String serialise() { try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(fernetKeyBytes)) { writeTo(byteStream); return getEncoder().encodeToString(byteStream.toByteArray()); } catch (final IOException ioe) { throw new IllegalStateException(ioe.getMessage(), ioe); } } 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); }### Answer:
@Test public void testSerialise() { final Key key = new Key(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, new byte[] {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}); final String result = key.serialise(); assertEquals("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=", result); } |
### Question:
TokenHeaderUtility { public Token getXAuthorizationToken(final ContainerRequest request) { final String xAuthorizationString = request.getHeaderString("X-Authorization"); if (xAuthorizationString != null && !"".equals(xAuthorizationString)) { return Token.fromString(xAuthorizationString.trim()); } return null; } @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") Token getAuthorizationToken(final ContainerRequest request); Token getXAuthorizationToken(final ContainerRequest request); }### Answer:
@Test public final void verifyGetXAuthorizationTokenDeserialisesToken() { 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.getXAuthorizationToken(request); assertEquals(token.serialise(), result.serialise()); }
@Test public final void verifyGetXAuthorizationTokenIgnoresBearer() { 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.getXAuthorizationToken(request); assertNull(result); } |
### Question:
TokenValidationExceptionMapper implements ExceptionMapper<TokenValidationException> { public Response toResponse(final TokenValidationException exception) { if (exception instanceof PayloadValidationException) { return status(FORBIDDEN).entity("Request could not be validated.").type(TEXT_PLAIN_TYPE).build(); } return new NotAuthorizedException("Bearer error=\"invalid_token\"").getResponse(); } Response toResponse(final TokenValidationException exception); }### Answer:
@Test public final void verifyToResponseGeneratesForbidden() { final PayloadValidationException exception = new PayloadValidationException("Invalid payload"); final Response response = mapper.toResponse(exception); assertEquals(403, response.getStatus()); }
@Test public final void verifyToResponseGeneratesUnauthorized() { final TokenValidationException exception = new TokenExpiredException("token expired"); final Response response = mapper.toResponse(exception); assertEquals(401, response.getStatus()); final String challenge = response.getHeaderString("WWW-Authenticate"); assertTrue(challenge.startsWith("Bearer ")); } |
### Question:
MemoryOverwritingRequestHandler extends RequestHandler2 { public void afterResponse(final Request<?> request, final Response<?> response) { final Object requestObject = request.getOriginalRequestObject(); if (requestObject instanceof PutSecretValueRequest) { final PutSecretValueRequest putRequest = (PutSecretValueRequest) requestObject; overwriteSecret(putRequest); } } MemoryOverwritingRequestHandler(final SecureRandom random); void afterResponse(final Request<?> request, final Response<?> response); void afterError(final Request<?> request, final Response<?> response, final Exception exception); }### Answer:
@Test public void verifyAfterResponseClearsSecret() { final ByteBuffer secretBinary = ByteBuffer.wrap(new byte[] { 1, 1, 2, 3, 5, 8 }); assertTrue(Arrays.equals(secretBinary.array(), new byte[] { 1, 1, 2, 3, 5, 8})); final PutSecretValueRequest originalRequest = new PutSecretValueRequest(); originalRequest.setSecretBinary(secretBinary); final Request<PutSecretValueRequest> request = new DefaultRequest<PutSecretValueRequest>(originalRequest, "AWSSecretsManager"); final PutSecretValueResult result = mock(PutSecretValueResult.class); final HttpResponse httpResponse = mock(HttpResponse.class); final Response<PutSecretValueResult> response = new Response<PutSecretValueResult>(result, httpResponse); handler.afterResponse(request, response); assertFalse(Arrays.equals(secretBinary.array(), new byte[] { 1, 1, 2, 3, 5, 8})); } |
### Question:
MemoryOverwritingRequestHandler extends RequestHandler2 { public void afterError(final Request<?> request, final Response<?> response, final Exception exception) { final Object requestObject = request.getOriginalRequestObject(); if (requestObject instanceof PutSecretValueRequest) { final PutSecretValueRequest putRequest = (PutSecretValueRequest) requestObject; overwriteSecret(putRequest); } } MemoryOverwritingRequestHandler(final SecureRandom random); void afterResponse(final Request<?> request, final Response<?> response); void afterError(final Request<?> request, final Response<?> response, final Exception exception); }### Answer:
@Test public void verifyAfterErrorClearsSecret() { final ByteBuffer secretBinary = ByteBuffer.wrap(new byte[] { 1, 1, 2, 3, 5, 8 }); assertTrue(Arrays.equals(secretBinary.array(), new byte[] { 1, 1, 2, 3, 5, 8})); final PutSecretValueRequest originalRequest = new PutSecretValueRequest(); originalRequest.setSecretBinary(secretBinary); final Request<PutSecretValueRequest> request = new DefaultRequest<PutSecretValueRequest>(originalRequest, "AWSSecretsManager"); final PutSecretValueResult result = mock(PutSecretValueResult.class); final HttpResponse httpResponse = mock(HttpResponse.class); final Response<PutSecretValueResult> response = new Response<PutSecretValueResult>(result, httpResponse); handler.afterError(request, response, new Exception()); assertFalse(Arrays.equals(secretBinary.array(), new byte[] { 1, 1, 2, 3, 5, 8})); } |
### Question:
Team { public String getId() { return Integer.toString(id); } Team(final int id, final String name); String getId(); String getName(); void setName(final String name); boolean isScrumTeam(); void setScrumTeam(final boolean isScrumTeam); List<Employee> getEmployees(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); }### Answer:
@Test public void testId() { Team team1 = new Team(1, null); assertNotNull(team1.getId()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.