method2testcases
stringlengths
118
6.63k
### Question: SignedScanner implements Scanner { @Override public Range getRange() { return valueScanner.getRange(); } SignedScanner(Connector connector, String tableName, Authorizations authorizations, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); @Override void disableIsolation(); @Override void enableIsolation(); @Override int getBatchSize(); @Override Range getRange(); @Override long getReadaheadThreshold(); @Override @SuppressWarnings("deprecation") int getTimeOut(); @Override void setBatchSize(int size); @Override void setRange(Range range); @Override void setReadaheadThreshold(long batches); @Override @SuppressWarnings("deprecation") void setTimeOut(int timeOut); }### Answer: @Test public void getRangeTest() throws Exception { Range range = new Range("test"); when(mockConnector.createScanner(TEST_TABLE, authorizations)).thenReturn(mockScanner); when(mockScanner.getRange()).thenReturn(range); Range value = new SignedScanner(mockConnector, TEST_TABLE, authorizations, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .getRange(); verify(mockScanner).getRange(); assertThat("correct range returned", value, equalTo(range)); }
### Question: SignedScanner implements Scanner { @Override public void setReadaheadThreshold(long batches) { valueScanner.setReadaheadThreshold(batches); if (signatureScanner != null) { signatureScanner.setReadaheadThreshold(batches); } } SignedScanner(Connector connector, String tableName, Authorizations authorizations, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); @Override void disableIsolation(); @Override void enableIsolation(); @Override int getBatchSize(); @Override Range getRange(); @Override long getReadaheadThreshold(); @Override @SuppressWarnings("deprecation") int getTimeOut(); @Override void setBatchSize(int size); @Override void setRange(Range range); @Override void setReadaheadThreshold(long batches); @Override @SuppressWarnings("deprecation") void setTimeOut(int timeOut); }### Answer: @Test public void setReadaheadThresholdTest() throws Exception { when(mockConnector.createScanner(TEST_TABLE, authorizations)).thenReturn(mockScanner); new SignedScanner(mockConnector, TEST_TABLE, authorizations, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setReadaheadThreshold(5L); verify(mockScanner).setReadaheadThreshold(5L); } @Test public void setReadaheadThresholdExternalTest() throws Exception { when(mockConnector.createScanner(TEST_TABLE, authorizations)).thenReturn(mockScanner); when(mockConnector.createScanner(SIG_TABLE, authorizations)).thenReturn(mockSignatureScanner); new SignedScanner(mockConnector, TEST_TABLE, authorizations, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setReadaheadThreshold(5L); verify(mockScanner).setReadaheadThreshold(5L); verify(mockSignatureScanner).setReadaheadThreshold(5L); }
### Question: SignedScanner implements Scanner { @Override public long getReadaheadThreshold() { return valueScanner.getReadaheadThreshold(); } SignedScanner(Connector connector, String tableName, Authorizations authorizations, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); @Override void disableIsolation(); @Override void enableIsolation(); @Override int getBatchSize(); @Override Range getRange(); @Override long getReadaheadThreshold(); @Override @SuppressWarnings("deprecation") int getTimeOut(); @Override void setBatchSize(int size); @Override void setRange(Range range); @Override void setReadaheadThreshold(long batches); @Override @SuppressWarnings("deprecation") void setTimeOut(int timeOut); }### Answer: @Test public void getReadaheadThresholdTest() throws Exception { when(mockConnector.createScanner(TEST_TABLE, authorizations)).thenReturn(mockScanner); when(mockScanner.getReadaheadThreshold()).thenReturn(5L); long value = new SignedScanner(mockConnector, TEST_TABLE, authorizations, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .getReadaheadThreshold(); verify(mockScanner).getReadaheadThreshold(); assertThat("correct threshold returned", value, is(5L)); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void addScanIterator(IteratorSetting cfg) { valueScanner.addScanIterator(cfg); if (signatureScanner != null) { signatureScanner.addScanIterator(cfg); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void addScanIteratorTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); IteratorSetting test = new IteratorSetting(10, "test", "test2"); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .addScanIterator(test); verify(mockScanner).addScanIterator(test); } @Test public void addScanIteratorExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); IteratorSetting test = new IteratorSetting(10, "test", "test2"); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .addScanIterator(test); verify(mockScanner).addScanIterator(test); verify(mockSignatureScanner).addScanIterator(test); }
### Question: SignedScanner implements Scanner { @Override public void addScanIterator(IteratorSetting cfg) { valueScanner.addScanIterator(cfg); if (signatureScanner != null) { signatureScanner.addScanIterator(cfg); } } SignedScanner(Connector connector, String tableName, Authorizations authorizations, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); @Override void disableIsolation(); @Override void enableIsolation(); @Override int getBatchSize(); @Override Range getRange(); @Override long getReadaheadThreshold(); @Override @SuppressWarnings("deprecation") int getTimeOut(); @Override void setBatchSize(int size); @Override void setRange(Range range); @Override void setReadaheadThreshold(long batches); @Override @SuppressWarnings("deprecation") void setTimeOut(int timeOut); }### Answer: @Test public void addScanIteratorTest() throws Exception { when(mockConnector.createScanner(TEST_TABLE, authorizations)).thenReturn(mockScanner); IteratorSetting test = new IteratorSetting(10, "test", "test2"); new SignedScanner(mockConnector, TEST_TABLE, authorizations, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).addScanIterator(test); verify(mockScanner).addScanIterator(test); } @Test public void addScanIteratorExternalTest() throws Exception { when(mockConnector.createScanner(TEST_TABLE, authorizations)).thenReturn(mockScanner); when(mockConnector.createScanner(SIG_TABLE, authorizations)).thenReturn(mockSignatureScanner); IteratorSetting test = new IteratorSetting(10, "test", "test2"); new SignedScanner(mockConnector, TEST_TABLE, authorizations, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).addScanIterator(test); verify(mockScanner).addScanIterator(test); verify(mockSignatureScanner).addScanIterator(test); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void clearColumns() { valueScanner.clearColumns(); if (signatureScanner != null) { signatureScanner.clearColumns(); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void clearColumns() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).clearColumns(); verify(mockScanner).clearColumns(); } @Test public void clearExternalColumns() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).clearColumns(); verify(mockScanner).clearColumns(); verify(mockSignatureScanner).clearColumns(); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void clearScanIterators() { valueScanner.clearScanIterators(); if (signatureScanner != null) { signatureScanner.clearScanIterators(); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void clearScanIteratorsTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .clearScanIterators(); verify(mockScanner).clearScanIterators(); } @Test public void clearScanIteratorsExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .clearScanIterators(); verify(mockScanner).clearScanIterators(); verify(mockSignatureScanner).clearScanIterators(); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void setRanges(Collection<Range> collection) { valueScanner.setRanges(collection); if (signatureScanner != null) { signatureScanner.setRanges(collection); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void setRangesTest() throws Exception { Collection<Range> ranges = Collections.singletonList(new Range("test")); when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setRanges(ranges); verify(mockScanner).setRanges(ranges); } @Test public void setRangesExternalTest() throws Exception { Collection<Range> ranges = Collections.singletonList(new Range("test")); when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setRanges(ranges); verify(mockScanner).setRanges(ranges); verify(mockSignatureScanner).setRanges(ranges); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void close() { valueScanner.close(); if (signatureScanner != null) { signatureScanner.close(); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void closeTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).close(); verify(mockScanner).close(); } @Test public void closeExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).close(); verify(mockScanner).close(); verify(mockSignatureScanner).close(); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void fetchColumn(Column column) { valueScanner.fetchColumn(column); if (signatureScanner != null) { signatureScanner.fetchColumn(column); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void fetchColumnTest() throws Exception { Column column = new Column(new Text(new byte[] {1}), new Text(new byte[] {2})); when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .fetchColumn(column); verify(mockScanner).fetchColumn(column); } @Test public void fetchColumnExternalTest() throws Exception { Column column = new Column(new Text(new byte[] {1}), new Text(new byte[] {2})); when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .fetchColumn(column); verify(mockScanner).fetchColumn(column); verify(mockSignatureScanner).fetchColumn(column); } @Test public void fetchColumn2Test() throws Exception { Text colF = new Text(new byte[] {1}), colQ = new Text(new byte[] {2}); when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).fetchColumn( colF, colQ); verify(mockScanner).fetchColumn(colF, colQ); } @Test public void fetchColumn2ExternalTest() throws Exception { Text colF = new Text(new byte[] {1}), colQ = new Text(new byte[] {2}); when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).fetchColumn( colF, colQ); verify(mockScanner).fetchColumn(colF, colQ); verify(mockSignatureScanner).fetchColumn(colF, colQ); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void fetchColumnFamily(Text col) { valueScanner.fetchColumnFamily(col); if (signatureScanner != null) { signatureScanner.fetchColumnFamily(col); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void fetchColumnFamilyTest() throws Exception { Text colF = new Text(new byte[] {1}); when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .fetchColumnFamily(colF); verify(mockScanner).fetchColumnFamily(colF); } @Test public void fetchColumnFamilyExternalTest() throws Exception { Text colF = new Text(new byte[] {1}); when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .fetchColumnFamily(colF); verify(mockScanner).fetchColumnFamily(colF); verify(mockSignatureScanner).fetchColumnFamily(colF); }
### Question: SignedBatchScanner implements BatchScanner { @Override public Authorizations getAuthorizations() { return valueScanner.getAuthorizations(); } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void getAuthorizationsTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockScanner.getAuthorizations()).thenReturn(authorizations); Authorizations auths = new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).getAuthorizations(); verify(mockScanner).getAuthorizations(); assertThat("correct authorizations returned", auths, equalTo(authorizations)); }
### Question: SignedBatchScanner implements BatchScanner { @Override public SamplerConfiguration getSamplerConfiguration() { return valueScanner.getSamplerConfiguration(); } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void getSamplerConfigurationTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); SamplerConfiguration config = new SamplerConfiguration("test"); when(mockScanner.getSamplerConfiguration()).thenReturn(config); SamplerConfiguration value = new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).getSamplerConfiguration(); verify(mockScanner).getSamplerConfiguration(); assertThat("correct config returned", value, equalTo(config)); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void setSamplerConfiguration(SamplerConfiguration samplerConfiguration) { valueScanner.setSamplerConfiguration(samplerConfiguration); if (signatureScanner != null) { signatureScanner.setSamplerConfiguration(samplerConfiguration); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void setSamplerConfigurationTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); SamplerConfiguration config = new SamplerConfiguration("test"); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setSamplerConfiguration(config); verify(mockScanner).setSamplerConfiguration(config); } @Test public void setSamplerConfigurationExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); SamplerConfiguration config = new SamplerConfiguration("test"); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setSamplerConfiguration(config); verify(mockScanner).setSamplerConfiguration(config); verify(mockSignatureScanner).setSamplerConfiguration(config); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void clearSamplerConfiguration() { valueScanner.clearSamplerConfiguration(); if (signatureScanner != null) { signatureScanner.clearSamplerConfiguration(); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void clearSamplerConfigurationTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .clearSamplerConfiguration(); verify(mockScanner).clearSamplerConfiguration(); } @Test public void clearSamplerConfigurationExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .clearSamplerConfiguration(); verify(mockScanner).clearSamplerConfiguration(); verify(mockSignatureScanner).clearSamplerConfiguration(); }
### Question: SignedScanner implements Scanner { @Override public void clearColumns() { valueScanner.clearColumns(); if (signatureScanner != null) { signatureScanner.clearColumns(); } } SignedScanner(Connector connector, String tableName, Authorizations authorizations, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); @Override void disableIsolation(); @Override void enableIsolation(); @Override int getBatchSize(); @Override Range getRange(); @Override long getReadaheadThreshold(); @Override @SuppressWarnings("deprecation") int getTimeOut(); @Override void setBatchSize(int size); @Override void setRange(Range range); @Override void setReadaheadThreshold(long batches); @Override @SuppressWarnings("deprecation") void setTimeOut(int timeOut); }### Answer: @Test public void clearColumns() throws Exception { when(mockConnector.createScanner(TEST_TABLE, authorizations)).thenReturn(mockScanner); new SignedScanner(mockConnector, TEST_TABLE, authorizations, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).clearColumns(); verify(mockScanner).clearColumns(); } @Test public void clearExternalColumns() throws Exception { when(mockConnector.createScanner(TEST_TABLE, authorizations)).thenReturn(mockScanner); when(mockConnector.createScanner(SIG_TABLE, authorizations)).thenReturn(mockSignatureScanner); new SignedScanner(mockConnector, TEST_TABLE, authorizations, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).clearColumns(); verify(mockScanner).clearColumns(); verify(mockSignatureScanner).clearColumns(); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void setBatchTimeout(long l, TimeUnit timeUnit) { valueScanner.setBatchTimeout(l, timeUnit); if (signatureScanner != null) { signatureScanner.setBatchTimeout(l, timeUnit); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void setBatchTimeoutTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setBatchTimeout(5L, TimeUnit.DAYS); verify(mockScanner).setBatchTimeout(5L, TimeUnit.DAYS); } @Test public void setBatchTimeoutExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setBatchTimeout(5L, TimeUnit.DAYS); verify(mockScanner).setBatchTimeout(5L, TimeUnit.DAYS); verify(mockSignatureScanner).setBatchTimeout(5L, TimeUnit.DAYS); }
### Question: SignedBatchScanner implements BatchScanner { @Override public long getBatchTimeout(TimeUnit timeUnit) { return valueScanner.getBatchTimeout(timeUnit); } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void getBatchTimeoutTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockScanner.getBatchTimeout(TimeUnit.DAYS)).thenReturn(5L); long value = new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .getBatchTimeout(TimeUnit.DAYS); verify(mockScanner).getBatchTimeout(TimeUnit.DAYS); assertThat("correct timeout returned", value, is(5L)); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void setClassLoaderContext(String s) { valueScanner.setClassLoaderContext(s); if (signatureScanner != null) { signatureScanner.setClassLoaderContext(s); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void setClassLoaderContextTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setClassLoaderContext("test"); verify(mockScanner).setClassLoaderContext("test"); } @Test public void setClassLoaderContextExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .setClassLoaderContext("test"); verify(mockScanner).setClassLoaderContext("test"); verify(mockSignatureScanner).setClassLoaderContext("test"); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void clearClassLoaderContext() { valueScanner.clearClassLoaderContext(); if (signatureScanner != null) { signatureScanner.clearClassLoaderContext(); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void clearClassLoaderContextTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .clearClassLoaderContext(); verify(mockScanner).clearClassLoaderContext(); } @Test public void clearClassLoaderContextExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .clearClassLoaderContext(); verify(mockScanner).clearClassLoaderContext(); verify(mockSignatureScanner).clearClassLoaderContext(); }
### Question: SignedBatchScanner implements BatchScanner { @Override public String getClassLoaderContext() { return valueScanner.getClassLoaderContext(); } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void getClassLoaderContextTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockScanner.getClassLoaderContext()).thenReturn("test"); String value = new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .getClassLoaderContext(); verify(mockScanner).getClassLoaderContext(); assertThat("correct class loader context returned", value, is("test")); }
### Question: SignedBatchScanner implements BatchScanner { @Override public long getTimeout(TimeUnit timeUnit) { return valueScanner.getTimeout(timeUnit); } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void getTimeoutTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockScanner.getTimeout(TimeUnit.DAYS)).thenReturn(5L); Long value = new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .getTimeout(TimeUnit.DAYS); verify(mockScanner).getTimeout(TimeUnit.DAYS); assertThat("correct timeout returned", value, is(5L)); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void removeScanIterator(String iteratorName) { valueScanner.removeScanIterator(iteratorName); if (signatureScanner != null) { signatureScanner.removeScanIterator(iteratorName); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void removeScanIteratorTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .removeScanIterator("test"); verify(mockScanner).removeScanIterator("test"); } @Test public void removeScanIteratorExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .removeScanIterator("test"); verify(mockScanner).removeScanIterator("test"); verify(mockSignatureScanner).removeScanIterator("test"); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void updateScanIteratorOption(String iteratorName, String key, String value) { valueScanner.updateScanIteratorOption(iteratorName, key, value); if (signatureScanner != null) { signatureScanner.updateScanIteratorOption(iteratorName, key, value); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void updateScanIteratorOptionTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .updateScanIteratorOption("test", "a", "b"); verify(mockScanner).updateScanIteratorOption("test", "a", "b"); } @Test public void updateScanIteratorOptionExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)) .updateScanIteratorOption("test", "a", "b"); verify(mockScanner).updateScanIteratorOption("test", "a", "b"); verify(mockSignatureScanner).updateScanIteratorOption("test", "a", "b"); }
### Question: SignedBatchScanner implements BatchScanner { @Override public void setTimeout(long timeout, TimeUnit timeUnit) { valueScanner.setTimeout(timeout, timeUnit); if (signatureScanner != null) { signatureScanner.setTimeout(timeout, timeUnit); } } SignedBatchScanner(Connector connector, String tableName, Authorizations authorizations, int numQueryThreads, SignatureConfig signatureConfig, SignatureKeyContainer keys); @Override ItemProcessingIterator<Entry<Key,Value>> iterator(); @Override void addScanIterator(IteratorSetting cfg); @Override void clearColumns(); @Override void clearScanIterators(); @Override void setRanges(Collection<Range> collection); @Override void close(); @Override void fetchColumn(Column column); @Override void fetchColumn(Text colFam, Text colQual); @Override void fetchColumnFamily(Text col); @Override Authorizations getAuthorizations(); @Override void setSamplerConfiguration(SamplerConfiguration samplerConfiguration); @Override SamplerConfiguration getSamplerConfiguration(); @Override void clearSamplerConfiguration(); @Override void setBatchTimeout(long l, TimeUnit timeUnit); @Override long getBatchTimeout(TimeUnit timeUnit); @Override void setClassLoaderContext(String s); @Override void clearClassLoaderContext(); @Override String getClassLoaderContext(); @Override long getTimeout(TimeUnit timeUnit); @Override void removeScanIterator(String iteratorName); @Override void updateScanIteratorOption(String iteratorName, String key, String value); @Override void setTimeout(long timeout, TimeUnit timeUnit); }### Answer: @Test public void setTimeoutTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config1.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).setTimeout(5L, TimeUnit.DAYS); verify(mockScanner).setTimeout(5L, TimeUnit.DAYS); } @Test public void setTimeoutExternalTest() throws Exception { when(mockConnector.createBatchScanner(TEST_TABLE, authorizations, 1)).thenReturn(mockScanner); when(mockConnector.createBatchScanner(SIG_TABLE, authorizations, 1)).thenReturn(mockSignatureScanner); new SignedBatchScanner(mockConnector, TEST_TABLE, authorizations, 1, getConfig("config3.ini"), aliceKeyContainers.get(ValueSigner.RSA_PSS)).setTimeout(5L, TimeUnit.DAYS); verify(mockScanner).setTimeout(5L, TimeUnit.DAYS); verify(mockSignatureScanner).setTimeout(5L, TimeUnit.DAYS); }
### Question: AnnotationFinder { public static <T extends Annotation> T annotationFor(Package aPkg, Class< ? extends T> whichAnnotation) { T annotation = null; if ((annotation = aPkg.getAnnotation(whichAnnotation)) == null) { annotation = find(aPkg, whichAnnotation); } return annotation; } static T annotationFor(Package aPkg, Class< ? extends T> whichAnnotation); }### Answer: @Test public void testAnnotationForPackageShouldAcceptWildCardClass() throws Exception { Class<? extends RamlGenerators> input = RamlGenerators.class; RamlGenerators generators = annotationFor(TOP_PACKAGE, input); assertNotNull("Wildcard โ€” null return not expected", generators); } @Test public void testAnnotationForPackageShouldAcceptClassLiteral() throws Exception { RamlGenerators generators = annotationFor(TOP_PACKAGE, RamlGenerators.class); assertNotNull("Class literal โ€” null return not expected", generators); } @Test public void testAnnotationForPackageShouldAcceptTypeWitness() throws Exception { RamlGenerators generators = AnnotationFinder.<RamlGenerators>annotationFor(TOP_PACKAGE, RamlGenerators.class); assertNotNull("Type witness โ€” null return not expected", generators); }
### Question: SimpleTypeNodeHandler extends NodeHandler<SimpleTypeNode<?>> { @Override public boolean handleSafely(SimpleTypeNode<?> node, YamlEmitter emitter) throws IOException { emitter.writeValue(node); return true; } SimpleTypeNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(SimpleTypeNode<?> node, YamlEmitter emitter); }### Answer: @Test public void handleSafely() throws Exception { SimpleTypeNodeHandler rnh = new SimpleTypeNodeHandler(); rnh.handleSafely(goodNode, emitter); verify(emitter).writeValue(goodNode); }
### Question: DefaultNodeHandler extends NodeHandler<Node> { @Override public boolean handles(Node node) { return true; } @Override boolean handles(Node node); @Override boolean handleSafely(Node node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { DefaultNodeHandler handler = new DefaultNodeHandler(); assertTrue(handler.handles(node)); }
### Question: DefaultNodeHandler extends NodeHandler<Node> { @Override public boolean handleSafely(Node node, YamlEmitter emitter) { System.err.println("not handled: " + node.getClass() + ", " + Arrays.asList(node.getClass().getInterfaces())); return true; } @Override boolean handles(Node node); @Override boolean handleSafely(Node node, YamlEmitter emitter); }### Answer: @Test public void handleSafely() throws Exception { DefaultNodeHandler handler = new DefaultNodeHandler(); assertTrue(handler.handle(node, emitter)); verifyNoMoreInteractions(emitter); }
### Question: YamlEmitter { public void writeValue(SimpleTypeNode<?> node) throws IOException { if (node instanceof StringNode) { writeQuoted(node.getLiteralValue()); } else { writeNaked(node.getLiteralValue()); } } YamlEmitter(); YamlEmitter(Writer writer, int i); YamlEmitter indent(); YamlEmitter bulletListArray(); void writeTag(String tag); void writeValue(SimpleTypeNode<?> node); void writeObjectValue(String value); void writeSyntaxElement(String s); void writeIndent(); }### Answer: @Test public void writeValueClean() throws Exception { when(stringNode.getLiteralValue()).thenReturn("hello"); YamlEmitter emitter = new YamlEmitter(writer, 0); emitter.writeValue(stringNode); assertEquals("hello", writer.toString()); } @Test public void writeValue() throws Exception { when(stringNode.getLiteralValue()).thenReturn("hel@lo"); YamlEmitter emitter = new YamlEmitter(writer, 0); emitter.writeValue(stringNode); assertEquals("\"hel@lo\"", writer.toString()); } @Test public void writeMultilineValue() throws Exception { when(stringNode.getLiteralValue()).thenReturn("hello\nman"); YamlEmitter emitter = new YamlEmitter(writer, 0); emitter.writeValue(stringNode); assertEquals("|\n hello\n man", writer.toString()); } @Test public void writeMultilineValueBecauseOfQuote() throws Exception { when(stringNode.getLiteralValue()).thenReturn("hello\"man"); YamlEmitter emitter = new YamlEmitter(writer, 0); emitter.writeValue(stringNode); assertEquals("|\n hello\"man", writer.toString()); }
### Question: AllResourceSelector implements Selector<Resource> { @Override public FluentIterable<Resource> fromApi(Api api) { List<Resource> topResources = api.resources(); FluentIterable<Resource> fi = from(topResources); for (Resource resource : topResources) { fi = fi.append(fromResource(resource)); } return fi; } @Override FluentIterable<Resource> fromApi(Api api); @Override FluentIterable<Resource> fromResource(Resource topResource); }### Answer: @Test public void fromApi() throws Exception { when(api.resources()).thenReturn(Collections.singletonList(resource)); when(resource.resources()).thenReturn(Collections.singletonList(subResource)); AllResourceSelector allResourceSelector = new AllResourceSelector(); FluentIterable<Resource> apiElements = allResourceSelector.fromApi(api); assertThat(apiElements, containsInAnyOrder(resource, subResource)); verify(api).resources(); verify(resource).resources(); verify(subResource).resources(); }
### Question: AllResourceSelector implements Selector<Resource> { @Override public FluentIterable<Resource> fromResource(Resource topResource) { List<Resource> resources = topResource.resources(); FluentIterable<Resource> fi = from(resources); for (Resource resource : resources) { fi = fi.append(fromResource(resource)); } return fi; } @Override FluentIterable<Resource> fromApi(Api api); @Override FluentIterable<Resource> fromResource(Resource topResource); }### Answer: @Test public void fromResource() throws Exception { when(resource.resources()).thenReturn(Collections.singletonList(subResource)); AllResourceSelector allResourceSelector = new AllResourceSelector(); FluentIterable<Resource> apiElements = allResourceSelector.fromResource(resource); assertThat(apiElements, containsInAnyOrder(subResource)); verify(resource).resources(); verify(subResource).resources(); }
### Question: ApiQueryBaseHandler implements QueryBase { @Override public <B> FluentIterable<B> queryFor(Selector<B> selector) { return selector.fromApi(api); } ApiQueryBaseHandler(Api api); @Override FluentIterable<B> queryFor(Selector<B> selector); }### Answer: @Test public void queryFor() throws Exception { when(selector.fromApi(api)).thenReturn(fluentIterator); ApiQueryBaseHandler handler = new ApiQueryBaseHandler(api); FluentIterable<Resource> iterable = handler.queryFor(selector); assertNotNull(iterable); verify(selector).fromApi(api); }
### Question: ResourceQueryBaseHandler implements QueryBase { @Override public <B> FluentIterable<B> queryFor(Selector<B> selector) { return selector.fromResource(resource); } ResourceQueryBaseHandler(Resource resource); @Override FluentIterable<B> queryFor(Selector<B> selector); }### Answer: @Test public void queryFor() throws Exception { when(selector.fromResource(resource)).thenReturn(fluentIterator); ResourceQueryBaseHandler handler = new ResourceQueryBaseHandler(resource); FluentIterable<Resource> iterable = handler.queryFor(selector); assertNotNull(iterable); verify(selector).fromResource(resource); }
### Question: TopResourceSelector implements Selector<Resource> { @Override public FluentIterable<Resource> fromApi(Api api) { return from(api.resources()); } @Override FluentIterable<Resource> fromApi(Api api); @Override FluentIterable<Resource> fromResource(Resource resource); }### Answer: @Test public void fromApi() throws Exception { TopResourceSelector topResourceSelector = new TopResourceSelector(); FluentIterable<Resource> apiElements = topResourceSelector.fromApi(api); assertEquals(0, apiElements.size()); verify(api).resources(); }
### Question: TopResourceSelector implements Selector<Resource> { @Override public FluentIterable<Resource> fromResource(Resource resource) { return FluentIterable.from(resource.resources()); } @Override FluentIterable<Resource> fromApi(Api api); @Override FluentIterable<Resource> fromResource(Resource resource); }### Answer: @Test public void fromResource() throws Exception { TopResourceSelector topResourceSelector = new TopResourceSelector(); FluentIterable<Resource> resourceElements = topResourceSelector.fromResource(resource); assertEquals(0, resourceElements.size()); verify(resource).resources(); }
### Question: Query { public<T> FluentIterable<T> select(Selector<T> selector) { return queryBase.queryFor(selector); } Query(QueryBase queryBase); static Query from(Api api); static Query from(Resource resource); FluentIterable<T> select(Selector<T> selector); }### Answer: @Test public void select() throws Exception { when(base.queryFor(selector)).thenReturn(fluentList); Query query = new Query(base); FluentIterable<Resource> resourceList = query.select(selector); assertSame(resourceList, fluentList); }
### Question: ResultingPojos { public void createAllTypes(String rootDirectory) throws IOException { generationContext.createSupportTypes(rootDirectory); for (CreationResult result : results) { result.createType(rootDirectory); } generationContext.createTypes(rootDirectory); } ResultingPojos(GenerationContextImpl generationContext); void addNewResult(CreationResult spec); List<CreationResult> creationResults(); void createFoundTypes(String rootDirectory); void createAllTypes(String rootDirectory); }### Answer: @Test public void createAllTypes() throws Exception { ResultingPojos pojos = new ResultingPojos(generationContext); pojos.addNewResult(result); pojos.createAllTypes("/tmp/fun"); verify(generationContext).createTypes("/tmp/fun"); verify(generationContext).createSupportTypes("/tmp/fun"); verify(result).createType("/tmp/fun"); }
### Question: ResultingPojos { public void createFoundTypes(String rootDirectory) throws IOException { generationContext.createSupportTypes(rootDirectory); for (CreationResult result : results) { result.createType(rootDirectory); } } ResultingPojos(GenerationContextImpl generationContext); void addNewResult(CreationResult spec); List<CreationResult> creationResults(); void createFoundTypes(String rootDirectory); void createAllTypes(String rootDirectory); }### Answer: @Test public void createFoundTypes() throws Exception { ResultingPojos pojos = new ResultingPojos(generationContext); pojos.addNewResult(result); pojos.createFoundTypes("/tmp/fun"); verify(result).createType("/tmp/fun"); verify(generationContext).createSupportTypes("/tmp/fun"); verify(generationContext, never()).createTypes("/tmp/fun"); }
### Question: GenerationContextImpl implements GenerationContext { public void setupTypeHierarchy(String actualName, TypeDeclaration typeDeclaration) { List<TypeDeclaration> parents = typeDeclaration.parentTypes(); for (TypeDeclaration parent : parents) { setupTypeHierarchy(parent.name(), parent); if ( ! parent.name().equals(actualName) ) { childTypes.put(parent.name(), actualName); } } } GenerationContextImpl(Api api); GenerationContextImpl(PluginManager pluginManager, Api api, TypeFetcher typeFetcher, String defaultPackage, List<String> basePlugins); @Override CreationResult findCreatedType(String typeName, TypeDeclaration ramlType); @Override String defaultPackage(); @Override Set<String> childClasses(String ramlTypeName); @Override ClassName buildDefaultClassName(String name, EventType eventType); void setupTypeHierarchy(String actualName, TypeDeclaration typeDeclaration); @Override void newExpectedType(String name, CreationResult creationResult); @Override void createTypes(String rootDirectory); @Override void createSupportTypes(String rootDirectory); @Override TypeName createSupportClass(TypeSpec.Builder newSupportType); @Override ObjectTypeHandlerPlugin pluginsForObjects(TypeDeclaration... typeDeclarations); @Override EnumerationTypeHandlerPlugin pluginsForEnumerations(TypeDeclaration... typeDeclarations); @Override ArrayTypeHandlerPlugin pluginsForArrays(TypeDeclaration... typeDeclarations); @Override UnionTypeHandlerPlugin pluginsForUnions(TypeDeclaration... typeDeclarations); @Override ReferenceTypeHandlerPlugin pluginsForReferences(TypeDeclaration... typeDeclarations); @Override Api api(); }### Answer: @Test public void setupTypeHierarchy() { when(type1.parentTypes()).thenReturn(Arrays.<TypeDeclaration>asList(type2, type3)); when(type2.parentTypes()).thenReturn(Arrays.<TypeDeclaration>asList(type3, type4)); when(type1.name()).thenReturn("type1"); when(type2.name()).thenReturn("type2"); when(type3.name()).thenReturn("type3"); when(type4.name()).thenReturn("type4"); GenerationContextImpl impl = new GenerationContextImpl(null); impl.setupTypeHierarchy("type1", type1); assertThat(impl.childClasses("type2"), Matchers.contains(Matchers.equalTo("type1"))); assertThat(impl.childClasses("type3"), Matchers.contains(Matchers.equalTo("type1"), Matchers.equalTo("type2"))); }
### Question: EnumerationTypeHandler implements TypeHandler { @Override public Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult) { Class cls = (typeDeclaration instanceof StringTypeDeclaration)?String.class:Number.class; FieldSpec.Builder field = FieldSpec.builder(ClassName.get(cls), "name").addModifiers(Modifier.PROTECTED, Modifier.FINAL); EnumerationPluginContext enumerationPluginContext = new EnumerationPluginContextImpl(generationContext, preCreationResult); ClassName className = preCreationResult.getJavaName(EventType.INTERFACE); TypeSpec.Builder enumBuilder = TypeSpec.enumBuilder(className); enumBuilder.addField(field.build()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addMethod( MethodSpec.constructorBuilder().addParameter(ClassName.get(cls), "name") .addStatement("this.$N = $N", "name", "name") .build() ); enumBuilder = generationContext.pluginsForEnumerations(typeDeclaration).classCreated(enumerationPluginContext, typeDeclaration, enumBuilder, EventType.INTERFACE); if ( enumBuilder == null ) { return Optional.absent(); } for (Object value : pullEnumValues(typeDeclaration)) { TypeSpec.Builder enumValueBuilder; if ( value instanceof String) { enumValueBuilder= TypeSpec.anonymousClassBuilder("$S", value); enumValueBuilder = generationContext.pluginsForEnumerations(typeDeclaration).enumValue(enumerationPluginContext, typeDeclaration, enumValueBuilder, (String)value, EventType.INTERFACE); } else { enumValueBuilder= TypeSpec.anonymousClassBuilder("$L", value); enumValueBuilder = generationContext.pluginsForEnumerations(typeDeclaration).enumValue(enumerationPluginContext, typeDeclaration, enumValueBuilder, (Number)value, EventType.INTERFACE); } if ( enumValueBuilder == null ) { continue; } enumBuilder.addEnumConstant(Names.constantName(String.valueOf(value)), enumValueBuilder.build()); } return Optional.of(preCreationResult.withInterface(enumBuilder.build())); } EnumerationTypeHandler(String name, TypeDeclaration stringTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); }### Answer: @Test public void createString() throws Exception { when(stringDeclaration.name()).thenReturn("Days"); when(stringDeclaration.enumValues()).thenReturn(Arrays.asList("one", "two", "three")); EnumerationTypeHandler handler = new EnumerationTypeHandler("days", stringDeclaration); GenerationContextImpl generationContext = new GenerationContextImpl(PluginManager.NULL, api, TypeFetchers.fromTypes(), "bar.pack", Collections.<String>emptyList()); generationContext.newExpectedType("Days", new CreationResult("bar.pack", ClassName.get("bar.pack", "Days"), null)); CreationResult result = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Days"), null)).get(); assertThat(result.getInterface(), allOf( name(equalTo("Days")), fields(Matchers.contains( FieldSpecMatchers.fieldName(equalTo("name")) ) ) )); System.err.println(result.getInterface().toString()); } @Test public void createInteger() throws Exception { when(integerDeclaration.name()).thenReturn("Time"); when(integerDeclaration.enumValues()).thenReturn(Arrays.<Number>asList(1, 2, 3)); EnumerationTypeHandler handler = new EnumerationTypeHandler("time", integerDeclaration); GenerationContextImpl generationContext = new GenerationContextImpl(PluginManager.NULL, api, TypeFetchers.fromTypes(), "bar.pack", Collections.<String>emptyList()); generationContext.newExpectedType("Time", new CreationResult("bar.pack", ClassName.get("bar.pack", "Time"), null)); CreationResult result = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Time"), null)).get(); assertThat(result.getInterface(), allOf( name(equalTo("Time")), fields(Matchers.contains( FieldSpecMatchers.fieldName(equalTo("name")) ) ) )); System.err.println(result.getInterface().toString()); }
### Question: Annotations { public T get(T def, Annotable type) { return getValueWithDefault(def, type); } static R evaluate(Function<TypeInstance, T> convert, String annotationName, String parameterName, Annotable mandatory, Annotable... others); static List<R> evaluateAsList(Function<TypeInstance, T> convert, String annotationName, String parameterName, Annotable mandatory, Annotable... others); static AnnotationRef findRef(Annotable annotable, String annotation); abstract T getWithContext(Annotable target, Annotable... others); T getValueWithDefault(T def, Annotable annotable, Annotable... others); T get(T def, Annotable type); T get(Annotable type); T get(T def, Annotable type, Annotable... others); static Annotations<Boolean> ABSTRACT; static Annotations<Boolean> USE_PRIMITIVE; static Annotations<Boolean> GENERATE_INLINE_ARRAY_TYPE; static Annotations<String> IMPLEMENTATION_CLASS_NAME; static Annotations<String> CLASS_NAME; static Annotations<List<PluginDef>> PLUGINS; }### Answer: @Test public void apiAnnotationsReading() throws IOException { Api api = getApi(); List<PluginDef> defs = Annotations.PLUGINS.get(api); assertEquals(2, defs.size()); assertEquals("core.one", defs.get(0).getPluginName()); assertEquals(Arrays.asList("foo", "bar"), defs.get(0).getArguments()); assertEquals("core.two", defs.get(1).getPluginName()); assertEquals(Arrays.asList("alpha", "gamma"), defs.get(1).getArguments()); } @Test public void typeAnnotationsReading() throws IOException { Api api = getApi(); TypeDeclaration fooType = RamlLoader.findTypes("foo", api.types()); List<PluginDef> defs = Annotations.PLUGINS.get(Collections.<PluginDef>emptyList(), api, fooType); assertEquals(3, defs.size()); assertEquals("core.one", defs.get(0).getPluginName()); assertEquals(Arrays.asList("foo", "bar"), defs.get(0).getArguments()); assertEquals("core.two", defs.get(1).getPluginName()); assertEquals(Arrays.asList("alpha", "gamma"), defs.get(1).getArguments()); assertEquals("core.foo", defs.get(2).getPluginName()); assertEquals(Arrays.asList("foo", "bar"), defs.get(2).getArguments()); } @Test public void abstractAnnotationsReading() throws IOException { Api api = getApi(); TypeDeclaration fooType = RamlLoader.findTypes("foo", api.types()); boolean b = Annotations.ABSTRACT.get(fooType); assertEquals(true, b); } @Test public void simplerTypeAnnotationsReading() throws IOException { Api api = getApi(); TypeDeclaration fooType = RamlLoader.findTypes("too", api.types()); List<PluginDef> defs = Annotations.PLUGINS.get(fooType); assertEquals(2, defs.size()); assertEquals("core.too", defs.get(0).getPluginName()); assertEquals("core.moo", defs.get(1).getPluginName()); }
### Question: CreationResult { public void createType(String rootDirectory) throws IOException { if ( interf.typeSpecs.size() == 0 ) { createInlineType(this); } createJavaFile(packageName, interf, rootDirectory, true); if ( implementationName != null ) { createJavaFile(packageName, impl, rootDirectory, false); } } CreationResult(String packageName, ClassName interfaceName, ClassName implementationName); CreationResult withInterface(TypeSpec spec); CreationResult withImplementation(TypeSpec spec); TypeSpec getInterface(); Optional<TypeSpec> getImplementation(); void createType(String rootDirectory); CreationResult getInternalTypeForProperty(String inside); ClassName getJavaName(EventType eventType); CreationResult withInternalType(String name, CreationResult internal); CreationResult internalType(String name); }### Answer: @Test public void createType() throws Exception { CreationResult result = new CreationResult("pack.me", ClassName.get("", "foo"), ClassName.get("", "foo")) { TypeSpec[] specs = {interf, cls}; int c = 0; @Override protected void createJavaFile(String pack, TypeSpec spec, String root, boolean b) { assertEquals("pack.me", pack); assertEquals("/tmp/foo", root); assertSame(spec, specs[c ++]); } }; result.withInterface(interf).withImplementation(cls); result.createType("/tmp/foo"); }
### Question: Names { public static String typeName(String... name) { if (name.length == 1 && isBlank(name[0])) { return "Root"; } List<String> values = new ArrayList<>(); int i = 0; for (String s : name) { String value = buildPart(i, s, NameFixer.CAMEL_UPPER); values.add(value); i++; } return Joiner.on("").join(values); } private Names(); static String typeName(String... name); static String methodName(String... name); static String variableName(String... name); static String constantName(String value); static String enumName(String value); static String javaTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); }### Answer: @Test public void buildTypeName() throws Exception { assertEquals("Fun", Names.typeName("/fun")); assertEquals("Fun", Names.typeName("/fun")); assertEquals("CodeBytes", Names.typeName(" assertEquals("Root", Names.typeName("")); assertEquals("FunAllo", Names.typeName("fun_allo")); assertEquals("FunAllo", Names.typeName("fun allo")); assertEquals("FunAllo", Names.typeName("funAllo")); assertEquals("FunAllo", Names.typeName("FunAllo")); assertEquals("FunAllo", Names.typeName("/FunAllo")); assertEquals("FunAllo", Names.typeName("Fun", "allo")); assertEquals("FunAllo", Names.typeName("fun", "_allo")); assertEquals("FunAllo", Names.typeName("fun", "allo")); } @Test public void nameWithDot() { assertEquals("FunImpl", Names.typeName("lib.Fun", "Impl")); }
### Question: Names { public static String methodName(String... name) { return checkMethodName(smallCamel(name)); } private Names(); static String typeName(String... name); static String methodName(String... name); static String variableName(String... name); static String constantName(String value); static String enumName(String value); static String javaTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); }### Answer: @Test public void buildMethod() { assertEquals("getSomething", Names.methodName("get", "something")); assertEquals("getClazz", Names.methodName("get", "class")); }
### Question: Names { public static String variableName(String... name) { Matcher m = LEADING_UNDERSCORES.matcher(name[0]); if (m.find()) { return m.group() + smallCamel(name); } else { return checkForReservedWord(smallCamel(name)); } } private Names(); static String typeName(String... name); static String methodName(String... name); static String variableName(String... name); static String constantName(String value); static String enumName(String value); static String javaTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, TypeDeclaration declaration); static String ramlTypeName(Resource resource, TypeDeclaration declaration); static String javaTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(Resource resource, Method method, Response response, TypeDeclaration declaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String ramlTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, BodyLike typeDeclaration); static String javaTypeName(org.raml.v2.api.model.v08.resources.Resource resource, org.raml.v2.api.model.v08.methods.Method method, org.raml.v2.api.model.v08.bodies.Response response, BodyLike typeDeclaration); }### Answer: @Test public void buildVariableName() throws Exception { assertEquals("funAllo", Names.variableName("funAllo")); assertEquals("funAllo", Names.variableName("FunAllo")); assertEquals("funAllo", Names.variableName("Fun", "allo")); assertEquals("funAllo", Names.variableName("fun", "_allo")); assertEquals("funAllo", Names.variableName("fun", "allo")); assertEquals("root", Names.variableName("")); assertEquals("fun", Names.variableName("/fun")); assertEquals("fun", Names.variableName("/fun")); assertEquals("funAllo", Names.variableName(" assertEquals("funAllo", Names.variableName("fun allo")); assertEquals("funAllo", Names.variableName("fun_allo")); } @Test public void buildVariableReservedWord() throws Exception { assertEquals("ifVariable", Names.variableName("if")); assertEquals("classVariable", Names.variableName("class")); } @Test public void buildVariableWithUnderscore() throws Exception { assertEquals("_funAllo", Names.variableName("_funAllo")); assertEquals("_funAllo", Names.variableName("_FunAllo")); assertEquals("_funAllo", Names.variableName("_Fun", "allo")); assertEquals("_funAllo", Names.variableName("_fun", "_allo")); }
### Question: PojoToRamlImpl implements PojoToRaml { @Override public Result classToRaml(final Class<?> clazz) { RamlType type = RamlTypeFactory.forType(clazz, classParserFactory.createParser(clazz), adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return new Result(null, Collections.<String, TypeDeclarationBuilder>emptyMap()); } Map<String, TypeDeclarationBuilder> dependentTypes = new HashMap<>(); TypeDeclarationBuilder builder = handleSingleType(clazz, dependentTypes); dependentTypes.remove(builder.id()); return new Result(builder, dependentTypes); } PojoToRamlImpl(ClassParserFactory parser, AdjusterFactory adjusterFactory); @Override Result classToRaml(final Class<?> clazz); @Override TypeBuilder name(Class<?> clazz); @Override TypeBuilder name(Type type); }### Answer: @Test public void scalarType() throws Exception { PojoToRamlImpl pojoToRaml = new PojoToRamlImpl(FieldClassParser.factory(), AdjusterFactory.NULL_FACTORY); Result types = pojoToRaml.classToRaml(String.class); Api api = createApi(types); List<TypeDeclaration> buildTypes = api.types(); assertEquals(0, buildTypes.size()); Emitter emitter = new Emitter(); emitter.emit(api); }
### Question: RenamePlugin extends AllTypesPluginHelper { @Override public ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return changeName(currentSuggestion, eventType); } RenamePlugin(List<String> arguments); @Override ClassName className(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); }### Answer: @Test public void className() { RenamePlugin plugin = new RenamePlugin(Arrays.asList("One", "OneImplementation")); ClassName cn = plugin.className((ObjectPluginContext) null, null, ClassName.bestGuess("fun.com.Allo"), EventType.INTERFACE); assertEquals("fun.com.One", cn.toString()); cn = plugin.className((ObjectPluginContext) null, null, ClassName.bestGuess("fun.com.Allo"), EventType.IMPLEMENTATION); assertEquals("fun.com.OneImplementation", cn.toString()); } @Test public void classNameWithDefaultImpl() { RenamePlugin plugin = new RenamePlugin(Arrays.asList("One")); ClassName cn = plugin.className((ObjectPluginContext) null, null, ClassName.bestGuess("fun.com.Allo"), EventType.INTERFACE); assertEquals("fun.com.One", cn.toString()); cn = plugin.className((ObjectPluginContext) null, null, ClassName.bestGuess("fun.com.Allo"), EventType.IMPLEMENTATION); assertEquals("fun.com.OneImpl", cn.toString()); }
### Question: BoxWhenNotRequired implements ReferenceTypeHandlerPlugin { @Override public TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion) { if (! ramlType.required()) { return currentSuggestion.box(); } else { return currentSuggestion; } } BoxWhenNotRequired(List<String> arguments); @Override TypeName typeName(ReferencePluginContext referencePluginContext, TypeDeclaration ramlType, TypeName currentSuggestion); }### Answer: @Test public void boxOnNotRequired() { when(integerDeclaration.required()).thenReturn(false); BoxWhenNotRequired boxWhenNotRequired = new BoxWhenNotRequired(null); TypeName tn = boxWhenNotRequired.typeName(null, integerDeclaration, TypeName.INT); assertEquals(TypeName.INT.box(), tn); } @Test public void noBoxOnRequired() { when(integerDeclaration.required()).thenReturn(true); BoxWhenNotRequired boxWhenNotRequired = new BoxWhenNotRequired(null); TypeName tn = boxWhenNotRequired.typeName(null, integerDeclaration, TypeName.INT); assertEquals(TypeName.INT, tn); }
### Question: JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType) { return currentSuggestion; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }### Answer: @Test public void className() { JaxbUnionExtension jaxb = new JaxbUnionExtension(); ClassName typeName = ClassName.bestGuess("foo.Union"); TypeName calculatedTypeName = jaxb.className(null, null, typeName, null); assertSame(typeName, calculatedTypeName); }
### Question: JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) { String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default"; String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name(); if (eventType == EventType.IMPLEMENTATION) { builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class) .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build()); AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name); builder.addAnnotation(annotation.build()); } else { builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class) .addMember("namespace", "$S", namespace) .addMember("name", "$S", name).build()); } return builder; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }### Answer: @Test public void classCreated() { JaxbUnionExtension jaxb = new JaxbUnionExtension(); TypeSpec.Builder classBuilder = TypeSpec.classBuilder("my.BuiltClass"); TypeSpec.Builder builder = jaxb.classCreated(null, unionTypeDeclaration, classBuilder, EventType.INTERFACE); TypeSpec buildClass = builder.build(); TypeSpecAssert.assertThat(buildClass) .hasName("my.BuiltClass"); AnnotationSpecAssert.assertThat(buildClass.annotations.get(0)).hasType(ClassName.get(XmlRootElement.class)); assertEquals("null", builder.build().annotations.get(0).members.get("name").get(0).toString()); assertEquals("\"##default\"", builder.build().annotations.get(0).members.get("namespace").get(0).toString()); } @Test public void implementationClassCreated() { JaxbUnionExtension jaxb = new JaxbUnionExtension(); TypeSpec.Builder classBuilder = TypeSpec.classBuilder("my.BuiltClass"); TypeSpec.Builder builder = jaxb.classCreated(null, unionTypeDeclaration, classBuilder, EventType.IMPLEMENTATION); TypeSpec buildClass = builder.build(); TypeSpecAssert.assertThat(buildClass) .hasName("my.BuiltClass"); AnnotationSpecAssert.assertThat(buildClass.annotations.get(0)).hasType(ClassName.get(XmlAccessorType.class)); assertEquals("javax.xml.bind.annotation.XmlAccessType.FIELD", builder.build().annotations.get(0).members.get("value").get(0).toString()); AnnotationSpecAssert.assertThat(buildClass.annotations.get(1)).hasType(ClassName.get(XmlRootElement.class)); assertEquals("null", builder.build().annotations.get(1).members.get("name").get(0).toString()); assertEquals("\"##default\"", builder.build().annotations.get(1).members.get("namespace").get(0).toString()); }
### Question: JaxbUnionExtension implements UnionTypeHandlerPlugin { @Override public FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { AnnotationSpec.Builder elementsAnnotation = AnnotationSpec.builder(XmlElements.class); for (TypeDeclaration typeDeclaration : union.of()) { TypeName unionPossibility = context.unionClass(typeDeclaration).getJavaName(EventType.IMPLEMENTATION); elementsAnnotation.addMember("value", "$L", AnnotationSpec .builder(XmlElement.class) .addMember("name", "$S", typeDeclaration.name()) .addMember("type", "$T.class", unionPossibility ) .build()); } anyType.addAnnotation(elementsAnnotation.build()); return anyType; } @Override ClassName className(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, ClassName currentSuggestion, EventType eventType); @Override TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration type, TypeSpec.Builder builder, EventType eventType); @Override FieldSpec.Builder anyFieldCreated(UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration property, FieldSpec.Builder fieldSpec, EventType eventType); }### Answer: @Test public void anyFieldCreated() { }
### Question: PojoToRamlImpl implements PojoToRaml { @Override public TypeBuilder name(Class<?> clazz) { RamlAdjuster adjuster = this.adjusterFactory.createAdjuster(clazz); ClassParser parser = classParserFactory.createParser(clazz); RamlType type = RamlTypeFactory.forType(clazz, parser, adjusterFactory).or(new RamlTypeSupplier(clazz)); if ( type.isScalar()) { return type.getRamlSyntax(); } final String simpleName = adjuster.adjustTypeName(clazz, clazz.getSimpleName()); return TypeBuilder.type(simpleName); } PojoToRamlImpl(ClassParserFactory parser, AdjusterFactory adjusterFactory); @Override Result classToRaml(final Class<?> clazz); @Override TypeBuilder name(Class<?> clazz); @Override TypeBuilder name(Type type); }### Answer: @Test public void name() throws Exception { PojoToRamlImpl pojoToRaml = new PojoToRamlImpl(FieldClassParser.factory(), AdjusterFactory.NULL_FACTORY); TypeBuilder builder = pojoToRaml.name(Fun.class.getMethod("stringMethod").getGenericReturnType()); ObjectNode node = builder.buildNode(); assertEquals("type: array", node.getChildren().get(0).toString()); }
### Question: Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType) { FacetValidation.addFacetsForBuilt(new AnnotationAdder() { @Override public TypeName typeName() { return anyType.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { anyType.addAnnotation(spec); } }); return anyType; } @Override FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder fieldBuilt(UnionPluginContext unionPluginContext, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType); @Override FieldSpec.Builder anyFieldCreated( UnionPluginContext context, UnionTypeDeclaration union, TypeSpec.Builder typeSpec, FieldSpec.Builder anyType, EventType eventType); }### Answer: @Test public void forUnion() throws Exception { Jsr303Extension ext = new Jsr303Extension(); TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(ClassName.get("xx.bb", "Foo")); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Double.class), "champ", Modifier.PUBLIC); ext.anyFieldCreated(unionPluginContext, union, typeBuilder, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
### Question: ArrayTypeHandler implements TypeHandler { @Override public TypeName javaClassReference(GenerationContext generationContext, EventType type) { if ( name.contains("[") || name.equals("array")) { String itemTypeName = typeDeclaration.items().name(); if ("object".equals(itemTypeName)) { itemTypeName = typeDeclaration.items().type(); } if ("object".equals(itemTypeName)) { throw new GenerationException("unable to create type array item of type object (or maybe an inline array type ?)"); } return generationContext.pluginsForReferences( Utils.allParents(typeDeclaration, new ArrayList<TypeDeclaration>()).toArray(new TypeDeclaration[0])) .typeName(new ReferencePluginContext() { }, typeDeclaration, ParameterizedTypeName.get(ClassName.get(List.class), TypeDeclarationType.calculateTypeName(itemTypeName, typeDeclaration.items(), generationContext, type).box())); } else { return javaClassName(generationContext, type); } } ArrayTypeHandler(String name, ArrayTypeDeclaration arrayTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); }### Answer: @Test public void javaClassReferenceWithString() { when(referencePlugin.typeName(any(ReferencePluginContext.class), any(TypeDeclaration.class), eq(ParameterizedTypeName.get(List.class, String.class)))).thenReturn(ParameterizedTypeName.get(List.class, String.class)); when(referencePlugin.typeName(any(ReferencePluginContext.class), any(TypeDeclaration.class), eq(ClassName.get(String.class)))).thenReturn(ClassName.get(String.class)); when(itemType.name()).thenReturn("string"); when(itemType.type()).thenReturn("string"); ArrayTypeHandler handler = new ArrayTypeHandler("string[]", arrayTypeDeclaration); TypeName tn = handler.javaClassReference(context, EventType.INTERFACE); assertEquals("java.util.List<java.lang.String>", tn.toString()); } @Test public void javaClassReferenceWithListOfSomething() { when(referencePlugin.typeName(any(ReferencePluginContext.class), any(TypeDeclaration.class), eq(ParameterizedTypeName.get(List.class, String.class)))).thenReturn(ParameterizedTypeName.get(ClassName.get(List.class), ClassName.bestGuess("foo.Something"))); when(referencePlugin.typeName(any(ReferencePluginContext.class), any(TypeDeclaration.class), (TypeName) any())).thenReturn(ParameterizedTypeName.get(ClassName.get(List.class), ClassName.bestGuess("foo.Something"))); when(itemType.name()).thenReturn("Something"); when(itemType.type()).thenReturn("object"); ArrayTypeHandler handler = new ArrayTypeHandler("Something[]", arrayTypeDeclaration); TypeName tn = handler.javaClassReference(context, EventType.INTERFACE); assertEquals("java.util.List<foo.Something>", tn.toString()); } @Test public void javaClassReferenceWithSomethingAsList() { when(arrayTypeHandlerPlugin.className(any(ArrayPluginContext.class), any(ArrayTypeDeclaration.class), (ClassName) eq(null), eq(EventType.INTERFACE))).thenReturn(ClassName.get("foo", "Something")); when(itemType.name()).thenReturn("Something"); when(itemType.type()).thenReturn("object"); ArrayTypeHandler handler = new ArrayTypeHandler("Something", arrayTypeDeclaration); TypeName tn = handler.javaClassReference(context, EventType.INTERFACE); assertEquals("foo.Something", tn.toString()); }
### Question: TypeFetchers { public static TypeFetcher fromTypes() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types())) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); static final TypeFetcher NULL_FETCHER; }### Answer: @Test public void fromTypes() throws Exception { when(api.types()).thenReturn(Arrays.asList(t1, t2, t3)); TypeDeclaration typeDeclaration = TypeFetchers.fromTypes().fetchType(api, "t1"); assertSame(t1, typeDeclaration); } @Test(expected = GenerationException.class) public void fromTypesFail() throws Exception { when(api.types()).thenReturn(Arrays.asList(t4, t5, t6)); when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); TypeFetchers.fromTypes().fetchType(api, "nosuchtype"); }
### Question: TypeFetchers { public static TypeFetcher fromLibraries() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses()))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); static final TypeFetcher NULL_FETCHER; }### Answer: @Test public void fromLibraries() throws Exception { when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); TypeDeclaration typeDeclaration1 = TypeFetchers.fromLibraries().fetchType(api, "t1"); TypeDeclaration typeDeclaration2 = TypeFetchers.fromLibraries().fetchType(api, "t2"); TypeDeclaration typeDeclaration3 = TypeFetchers.fromLibraries().fetchType(api, "t3"); assertSame(typeDeclaration1, t1); assertSame(typeDeclaration2, t2); assertSame(typeDeclaration3, t3); } @Test(expected = GenerationException.class) public void failFromLibraries() throws Exception { when(api.types()).thenReturn(Arrays.asList(t4, t5, t6)); when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); TypeFetchers.fromLibraries().fetchType(api, "t4"); }
### Question: TypeFetchers { public static TypeFetcher fromAnywhere() { return new TypeFetcher() { Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String name) throws GenerationException { return FluentIterable.from(Optional.fromNullable(foundInApi).or(FluentIterable.from(api.types()).append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())))) .firstMatch(namedPredicate(name)).or(fail(name)); } }; } static TypeFetcher fromTypes(); static TypeFetcher fromLibraries(); static TypeFetcher fromAnywhere(); static final TypeFetcher NULL_FETCHER; }### Answer: @Test public void fromAnywhere() throws Exception { when(api.types()).thenReturn(Arrays.asList(t4, t5, t6)); when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); TypeDeclaration typeDeclaration1 = TypeFetchers.fromAnywhere().fetchType(api, "t1"); TypeDeclaration typeDeclaration2 = TypeFetchers.fromAnywhere().fetchType(api, "t2"); TypeDeclaration typeDeclaration3 = TypeFetchers.fromAnywhere().fetchType(api, "t3"); TypeDeclaration typeDeclaration4 = TypeFetchers.fromAnywhere().fetchType(api, "t4"); TypeDeclaration typeDeclaration5 = TypeFetchers.fromAnywhere().fetchType(api, "t5"); TypeDeclaration typeDeclaration6 = TypeFetchers.fromAnywhere().fetchType(api, "t6"); assertSame(typeDeclaration1, t1); assertSame(typeDeclaration2, t2); assertSame(typeDeclaration3, t3); assertSame(typeDeclaration4, t4); assertSame(typeDeclaration5, t5); assertSame(typeDeclaration6, t6); }
### Question: TypeFinders { public static TypeFinder inTypes() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return api.types(); } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }### Answer: @Test public void inTypes() { when(api.types()).thenReturn(Arrays.asList(t1, t2, t3)); Iterable<TypeDeclaration> it = TypeFinders.inTypes().findTypes(api); assertThat(it, contains(equalTo(t1), equalTo(t2), equalTo(t3))); }
### Question: TypeFinders { public static TypeFinder inLibraries() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { List<TypeDeclaration> foundTypes = new ArrayList<>(); Utils.goThroughLibraries(foundTypes, new HashSet<String>(), api.uses()); return foundTypes; } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }### Answer: @Test public void inLibraries() { when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); Iterable<TypeDeclaration> it = TypeFinders.inLibraries().findTypes(api); System.err.println(it); assertThat(it, containsInAnyOrder(equalTo(t1), equalTo(t2), equalTo(t3))); }
### Question: TypeFinders { public static TypeFinder everyWhere() { return new TypeFinder() { @Override public Iterable<TypeDeclaration> findTypes(Api api) { return FluentIterable.from(api.types()) .append(resourceTypes(api.resources())) .append(Utils.goThroughLibraries(new ArrayList<TypeDeclaration>(), new HashSet<String>(), api.uses())); } }; } static TypeFinder inTypes(); static TypeFinder inLibraries(); static TypeFinder everyWhere(); static TypeFinder inResources(); }### Answer: @Test public void everyWhere() { when(api.types()).thenReturn(Arrays.asList(t4, t5, t6)); when(api.uses()).thenReturn(Arrays.asList(l1, l2)); when(l1.uses()).thenReturn(Collections.singletonList(l3)); when(l1.types()).thenReturn(Collections.singletonList(t1)); when(l2.types()).thenReturn(Collections.singletonList(t2)); when(l3.types()).thenReturn(Collections.singletonList(t3)); Iterable<TypeDeclaration> it = TypeFinders.everyWhere().findTypes(api); System.err.println(it); assertThat(it, containsInAnyOrder(equalTo(t1), equalTo(t2), equalTo(t3), equalTo(t4), equalTo(t5), equalTo(t6))); }
### Question: Augmenter { public static<T> T augment(Class<T> augmentedInterface, final Object delegate) { try { Extension extension = augmentedInterface.getAnnotation(Extension.class); ExtensionFactory extensionFactory = augmentedInterface.getAnnotation(ExtensionFactory.class); if ( extension == null && extensionFactory == null ) { throw new IllegalArgumentException("no @Extension or @ExtensionFactory annotation to build augmented interface"); } AugmentationExtensionFactory factory = createFactory(extension, extensionFactory); final Object handler = findFactoryMethod(delegate, factory); return buildProxy(augmentedInterface, delegate, handler); } catch (NoSuchMethodException| IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new AugmentationException("trying to augment " + augmentedInterface, e); } } static T augment(Class<T> augmentedInterface, final Object delegate); }### Answer: @Test public void simple() throws Exception { Foo foo = (Foo) Proxy.newProxyInstance(AugmenterTest.class.getClassLoader(), new Class[] {Foo.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.getName(); } }); Boo b = Augmenter.augment(Boo.class, foo); Assert.assertEquals("HandledBibi", b.getBibi()); Assert.assertEquals("getName", b.getName()); Assert.assertEquals("toString", b.toString()); } @Test public void factory() throws Exception { SubFoo subFoo = (SubFoo) Proxy.newProxyInstance(AugmenterTest.class.getClassLoader(), new Class[] {SubFoo.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.getName(); } }); AugmentedNode b = Augmenter.augment(AugmentedNode.class, subFoo); Assert.assertEquals("toString", b.toString()); }
### Question: ResponseBuilder extends KeyValueNodeBuilder<ResponseBuilder> implements NodeBuilder, AnnotableBuilder<ResponseBuilder> { static public ResponseBuilder response(int code) { return new ResponseBuilder(code); } private ResponseBuilder(int code); static ResponseBuilder response(int code); ResponseBuilder withBodies(BodyBuilder... builder); @Override ResponseBuilder withAnnotations(AnnotationBuilder... builders); @Override KeyValueNode buildNode(); ResponseBuilder description(String description); }### Answer: @Test public void response() { Api api = document() .baseUri("http: .title("doc") .version("one") .mediaType("foo/fun") .withResources( resource("/foo") .withMethods(MethodBuilder.method("get") .withResponses(ResponseBuilder.response(200) .withBodies(BodyBuilder.body("application/json").ofType(TypeBuilder.type("integer"))) ) ) ) .buildModel(); assertEquals("application/json", api.resources().get(0).methods().get(0).responses().get(0).body().get(0).name()); assertEquals("integer", api.resources().get(0).methods().get(0).responses().get(0).body().get(0).type()); }
### Question: ResourceBuilder extends KeyValueNodeBuilder<ResourceBuilder> implements NodeBuilder { private ResourceBuilder(String name) { super(name); } private ResourceBuilder(String name); static ResourceBuilder resource(String name); @Override KeyValueNode buildNode(); ResourceBuilder displayName(String displayName); ResourceBuilder description(String comment); ResourceBuilder relativeUri(String relativeUri); ResourceBuilder withResources(ResourceBuilder... resourceBuilders); ResourceBuilder withMethods(MethodBuilder... methodBuilders); }### Answer: @Test public void resourceBuilder() { Api api = document() .baseUri("http: .title("doc") .version("one") .mediaType("foo/fun") .withResources( resource("/foo") .description("happy") ) .buildModel(); assertEquals("/foo", api.resources().get(0).displayName().value()); assertEquals("/foo", api.resources().get(0).resourcePath()); assertEquals("/foo", api.resources().get(0).relativeUri().value()); assertEquals("happy", api.resources().get(0).description().value()); }
### Question: TypeBuilder extends ObjectNodeBuilder<TypeBuilder> implements NodeBuilder, AnnotableBuilder<TypeBuilder> { static public TypeBuilder type(String type) { return new TypeBuilder(type); } private TypeBuilder(String type); TypeBuilder(String[] types); TypeBuilder(TypeBuilder builder); String id(); static TypeBuilder type(String type); static TypeBuilder arrayOf(TypeBuilder builder); static TypeBuilder type(); static TypeBuilder type(String... types); @Override TypeBuilder withAnnotations(AnnotationBuilder... builders); TypeBuilder withProperty(TypePropertyBuilder... properties); TypeBuilder withExamples(ExamplesBuilder... properties); TypeBuilder withExample(ExamplesBuilder example); TypeBuilder withFacets(FacetBuilder... facetBuilders); TypeBuilder description(String description); TypeBuilder enumValues(String... enumValues); TypeBuilder enumValues(long... enumValues); TypeBuilder enumValues(boolean... enumValues); @Override ObjectNode buildNode(); public String[] types; }### Answer: @Test public void simpleType() { Api api = document() .baseUri("http: .title("doc") .version("one") .mediaType("foo/fun") .withTypes( TypeDeclarationBuilder.typeDeclaration("Mom") .ofType(TypeBuilder.type("boolean"))) .buildModel(); assertEquals("Mom", api.types().get(0).name()); assertEquals("boolean", api.types().get(0).type()); } @Test public void unionType() { Api api = document() .baseUri("http: .title("doc") .version("one") .mediaType("foo/fun") .withTypes( TypeDeclarationBuilder.typeDeclaration("Mom") .ofType(TypeBuilder.type("string | integer") ) ) .buildModel(); assertEquals("Mom", api.types().get(0).name()); assertEquals("string | integer", api.types().get(0).type()); assertEquals("string | integer", ((UnionTypeDeclaration)api.types().get(0)).of().get(0).name()); assertEquals("string | integer", ((UnionTypeDeclaration)api.types().get(0)).of().get(1).name()); }
### Question: Emitter { public void emit(Api api) throws IOException { emit(api, new OutputStreamWriter(System.out)); } Emitter(HandlerList list); Emitter(); void emit(Api api); void emit(Api api, Writer w); }### Answer: @Test public void emit() throws Exception { when(api.getNode()).thenReturn(node); when(node.getChildren()).thenReturn(Arrays.asList(child1, child2)); Emitter emitter = new Emitter(list) { @Override protected YamlEmitter createEmitter(Writer w) { assertSame(w, writer); return yamlEmitter; } }; emitter.emit(api, writer); verify(list).handle(eq(child1), any(YamlEmitter.class) ); verify(list).handle(eq(child2), any(YamlEmitter.class) ); }
### Question: HandlerList extends NodeHandler<Node> { @Override public boolean handles(final Node node) { return FluentIterable.from(handlerList).anyMatch(new Predicate<NodeHandler<? extends Node>>() { @Override public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) { return nodeHandler.handles(node); } }); } HandlerList(List<NodeHandler<? extends Node>> handlers); HandlerList(); @Override boolean handles(final Node node); @Override boolean handleSafely(final Node node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { when(nodeHandler1.handles(node)).thenReturn(true); HandlerList list = new HandlerList(Arrays.<NodeHandler<? extends Node>>asList(nodeHandler1, nodeHandler2)); assertTrue(list.handles(node)); verify(nodeHandler2, never()).handles(any(Node.class)); } @Test public void handlesNone() throws Exception { when(nodeHandler1.handles(node)).thenReturn(false); when(nodeHandler2.handles(node)).thenReturn(false); HandlerList list = new HandlerList(Arrays.<NodeHandler<? extends Node>>asList(nodeHandler1, nodeHandler2)); assertFalse(list.handles(node)); } @Test public void actuallyHandleSafely() throws Exception { when(nodeHandler1.handles(node)).thenReturn(false); when(nodeHandler2.handles(node)).thenReturn(true); when(nodeHandler2.handle(node, emitter)).thenReturn(true); HandlerList list = new HandlerList(Arrays.<NodeHandler<? extends Node>>asList(nodeHandler1, nodeHandler2)); assertTrue(list.handle(node, emitter)); verify(nodeHandler1, never()).handle(any(Node.class), any(YamlEmitter.class)); verify(nodeHandler2).handle(node, emitter); }
### Question: ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handles(Node node) { return node instanceof ReferenceNode; } @Override boolean handles(Node node); @Override boolean handleSafely(ReferenceNode node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { ReferenceNodeHandler handler = new ReferenceNodeHandler(); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); }
### Question: ReferenceNodeHandler extends NodeHandler<ReferenceNode> { @Override public boolean handleSafely(ReferenceNode node, YamlEmitter emitter) throws IOException { emitter.writeObjectValue(node.getRefName()); return true; } @Override boolean handles(Node node); @Override boolean handleSafely(ReferenceNode node, YamlEmitter emitter); }### Answer: @Test public void handleSafely() throws Exception { when(goodNode.getRefName()).thenReturn("ref.value"); ReferenceNodeHandler rnh = new ReferenceNodeHandler(); rnh.handleSafely(goodNode, emitter); verify(emitter).writeObjectValue("ref.value"); }
### Question: TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handles(Node node) { return node instanceof TypeDeclarationNode; } TypeDeclarationNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { TypeDeclarationNodeHandler tdnh = new TypeDeclarationNodeHandler(list); assertFalse(tdnh.handles(badNode)); assertTrue(tdnh.handles(goodNode)); }
### Question: TypeDeclarationNodeHandler extends NodeHandler<TypeDeclarationNode> { @Override public boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { handlerList.handle(child, emitter); } return true; } TypeDeclarationNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeDeclarationNode node, YamlEmitter emitter); }### Answer: @Test public void handleSafely() throws Exception { when(goodNode.getChildren()).thenReturn(Collections.<Node>singletonList(keyValueNode)); TypeDeclarationNodeHandler handler = new TypeDeclarationNodeHandler(list); handler.handleSafely(goodNode, emitter); verify(list).handle(keyValueNode, emitter); }
### Question: ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handles(Node node) { return node instanceof ArrayNode; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { ArrayNodeHandler handler = new ArrayNodeHandler(list); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); }
### Question: ArrayNodeHandler extends NodeHandler<ArrayNode> { @Override public boolean handleSafely(ArrayNode node, YamlEmitter emitter) throws IOException { List<Node> children = node.getChildren(); if ( childrenAreAllScalarTypes(children)) { emitter.writeSyntaxElement("["); for (int a = 0; a < children.size(); a++) { handlerList.handle(children.get(a), emitter); if (a < children.size() - 1) { emitter.writeSyntaxElement(","); } } emitter.writeSyntaxElement("]"); } else { YamlEmitter indented = emitter.indent(); for (Node child : children) { indented.writeSyntaxElement("\n"); indented.writeIndent(); indented.writeSyntaxElement("- "); handlerList.handle(child, indented.bulletListArray()); } } return true; } ArrayNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(ArrayNode node, YamlEmitter emitter); }### Answer: @Test public void handleSafelyEmpty() throws Exception { ArrayNodeHandler handler = new ArrayNodeHandler(list); handler.handleSafely(goodNode, emitter); verify(emitter).writeSyntaxElement("["); verify(emitter).writeSyntaxElement("]"); verifyNoMoreInteractions(emitter); } @Test public void handleSafelyTwoScalarElements() throws Exception { when(goodNode.getChildren()).thenReturn(Arrays.<Node>asList(scalar1, scalar2)); ArrayNodeHandler handler = new ArrayNodeHandler(list); handler.handleSafely(goodNode, emitter); verify(emitter).writeSyntaxElement("["); verify(emitter).writeSyntaxElement(","); verify(emitter).writeSyntaxElement("]"); verify(list).handle(scalar1, emitter); verify(list).handle(scalar2, emitter); verifyNoMoreInteractions(emitter, list); } @Test public void handleSafelyTwoNonScalarElements() throws Exception { when(goodNode.getChildren()).thenReturn(Arrays.asList(object1, object2)); when(emitter.indent()).thenReturn(subEmitter); when(subEmitter.bulletListArray()).thenReturn(bullet); ArrayNodeHandler handler = new ArrayNodeHandler(list); handler.handleSafely(goodNode, emitter); verify(emitter).indent(); verify(subEmitter, times(2)).bulletListArray(); verify(subEmitter, times(2)).writeSyntaxElement("\n"); verify(subEmitter, times(2)).writeSyntaxElement("- "); verify(subEmitter, times(2)).writeIndent(); verify(list).handle(object1, bullet); verify(list).handle(object2, bullet); verifyNoMoreInteractions(emitter, subEmitter, list); }
### Question: KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handles(Node node) { return node instanceof KeyValueNode; } KeyValueNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(KeyValueNode node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { KeyValueNodeHandler handler = new KeyValueNodeHandler(list); assertFalse(handler.handles(notKeyNode)); assertTrue(handler.handles(keyNode)); }
### Question: KeyValueNodeHandler extends NodeHandler<KeyValueNode> { @Override public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException { String scalar = isScalar(node.getValue()); if ( scalar != null ) { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter); } else { emitter.writeTag(node.getKey().toString()); handlerList.handle(node.getValue(), emitter.indent()); } return true; } KeyValueNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(KeyValueNode node, YamlEmitter emitter); }### Answer: @Test public void handleSafelyScalar() throws Exception { when(keyNode.getValue()).thenReturn(simpleNode); when(keyNode.getKey()).thenReturn(new StringNodeImpl("hello")); KeyValueNodeHandler handler = new KeyValueNodeHandler(list); assertTrue(handler.handleSafely(keyNode, emitter)); verify(emitter).writeTag("hello"); verify(list).handle(simpleNode, emitter); } @Test public void handleSafelyObject() throws Exception { when(keyNode.getValue()).thenReturn(objectNode); when(emitter.indent()).thenReturn(subEmitter); when(keyNode.getKey()).thenReturn(new StringNodeImpl("hello")); KeyValueNodeHandler handler = new KeyValueNodeHandler(list); assertTrue(handler.handleSafely(keyNode, emitter)); verify(emitter).writeTag("hello"); verify(list).handle(objectNode, subEmitter); }
### Question: SubclassedNodeHandler extends NodeHandler<T> { @Override public boolean handle(Node node, YamlEmitter emitter) { try { return subclassHandlerList.handle(node, emitter) || handleSafely((T) node, emitter); } catch (IOException e) { throw new RuntimeException(e); } } SubclassedNodeHandler(Class<?> superClass, HandlerList subclassHandlerList); @Override boolean handles(Node node); @Override boolean handle(Node node, YamlEmitter emitter); }### Answer: @Test public void fallsThrough() throws Exception { when(subNodeHandler.handle(node, emitter)).thenReturn(false); SubclassedNodeHandler<ObjectNode> on = new SubclassedNodeHandler<ObjectNode>(ObjectNode.class, subNodeHandler) { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { nodeVerifier.handleSafely(node, emitter); return true; } }; assertTrue(on.handle(node, emitter)); verify(subNodeHandler).handle(node, emitter); verify(nodeVerifier).handleSafely(node, emitter); } @Test public void sublistHandles() throws Exception { when(subNodeHandler.handle(node, emitter)).thenReturn(true); SubclassedNodeHandler<ObjectNode> on = new SubclassedNodeHandler<ObjectNode>(ObjectNode.class, subNodeHandler) { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { nodeVerifier.handleSafely(node, emitter); return true; } }; assertTrue(on.handle(node, emitter)); verify(subNodeHandler).handle(node, emitter); verify(nodeVerifier, never()).handleSafely(node, emitter); }
### Question: TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handles(Node node) { return node instanceof TypeExpressionNode; } TypeExpressionNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { TypeExpressionNodeHandler handler = new TypeExpressionNodeHandler(list); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); }
### Question: TypeExpressionNodeHandler extends SubclassedNodeHandler<TypeExpressionNode> { @Override public boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter) throws IOException { List<LibraryRefNode> descs = node.findDescendantsWith(LibraryRefNode.class); if ( descs.size() != 0 && descs.get(0) != null ) { emitter.writeObjectValue(descs.get(0).getRefName() + "." +node.getTypeExpressionText()); } else { emitter.writeObjectValue(node.getTypeExpressionText()); } return true; } TypeExpressionNodeHandler(HandlerList handlerList); @Override boolean handles(Node node); @Override boolean handleSafely(TypeExpressionNode node, YamlEmitter emitter); }### Answer: @Test public void handleSafely() throws Exception { when(goodNode.getTypeExpressionText()).thenReturn("JustReference"); TypeExpressionNodeHandler handler = new TypeExpressionNodeHandler(list); handler.handle(goodNode, emitter); verify(emitter).writeObjectValue("JustReference"); }
### Question: ObjectNodeHandler extends SubclassedNodeHandler<ObjectNode> { @Override public boolean handleSafely(ObjectNode node, YamlEmitter emitter) throws IOException { for (Node child : node.getChildren()) { String scalar = isScalar(node.getChildren().get(0)); if ( scalar != null ) { emitter.writeObjectValue(scalar); } else { handlerList.handle(child, emitter); } } return true; } ObjectNodeHandler(HandlerList handlerList); @Override boolean handleSafely(ObjectNode node, YamlEmitter emitter); }### Answer: @Test public void handleSafely() throws Exception { when(objectNode.getChildren()).thenReturn(Collections.<Node>singletonList(child)); ObjectNodeHandler on = new ObjectNodeHandler(list); on.handleSafely(objectNode, emitter); verify(list).handle(child, emitter); } @Test public void handleSafelyScalar() throws Exception { when(objectNode.getChildren()).thenReturn(Collections.<Node>singletonList(scalarNode)); ObjectNodeHandler on = new ObjectNodeHandler(list); on.handleSafely(objectNode, emitter); verify(emitter).writeObjectValue("foo"); }
### Question: NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handles(Node node) { return node instanceof NullNode; } NullNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(NullNode node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { NullNodeHandler handler = new NullNodeHandler(); assertFalse(handler.handles(notNullNode)); assertTrue(handler.handles(nullNode)); }
### Question: NullNodeHandler extends NodeHandler<NullNode> { @Override public boolean handleSafely(NullNode node, YamlEmitter emitter) throws IOException { return true; } NullNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(NullNode node, YamlEmitter emitter); }### Answer: @Test public void handleSafely() throws Exception { NullNodeHandler nul = new NullNodeHandler(); nul.handleSafely(nullNode, emitter); verifyNoMoreInteractions(emitter); }
### Question: SimpleTypeNodeHandler extends NodeHandler<SimpleTypeNode<?>> { @Override public boolean handles(Node node) { return node instanceof SimpleTypeNode; } SimpleTypeNodeHandler(); @Override boolean handles(Node node); @Override boolean handleSafely(SimpleTypeNode<?> node, YamlEmitter emitter); }### Answer: @Test public void handles() throws Exception { SimpleTypeNodeHandler handler = new SimpleTypeNodeHandler(); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); }
### Question: Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId) { Matcher matcher = HIGHLIGHT_PATTERN.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<ContentValues> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); ContentValues contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_BOOK_ID, bookId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, highlight.pageInfo.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID, highlight.id); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME, highlight.className); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, highlight.containerElementId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, highlight.text); highlights.add(contentValues); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } Highlight(String text, int id, String className, int containerElementId, String timeStampString, PageInfo pageInfo, int bookId, Title parentTitle, String noteText); Highlight(String text, int id, String className, int containerElementId, PageInfo pageInfo, String noteText, int bookId); @ColorInt static int getHighlightColor(@NonNull String className); @ColorInt static int getDarkHighlightColor(@NonNull String className); @NonNull static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId); @NonNull static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId); @Override int compareTo(@NonNull Highlight highlight); boolean hasNote(); Date getDateTime(); static boolean sortByDate; public String text; public int id; public String className; public int containerElementId; public String noteText; }### Answer: @Test public void deserializeGeneric() throws Exception { ArrayList<ContentValues> highlightsReturn = Highlight.deserializeToContentValues(serialized1,pagId,0); ArrayList<ContentValues> highlightsGiven = new ArrayList<>(); ContentValues contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, pagId.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID,2); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME,"highlight3"); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, 0); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, "dcdcdc "); highlightsGiven.add(contentValues); contentValues = new ContentValues(); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID, pagId.pageId); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID,4); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME,"highlight1"); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID, 0); contentValues.put(UserDataDBContract.HighlightEntry.COLUMN_TEXT, "cdcdc "); highlightsGiven.add(contentValues); assertEquals(highlightsGiven.size(), highlightsReturn.size()); }
### Question: Highlight extends UserNote implements Comparable<Highlight> { @NonNull public static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId) { final Pattern pattern = Pattern.compile("^type:(\\w+)(?:\\|(\\d+)\\$(\\d+)\\$(\\d+)\\$(\\w+)\\$(\\d*)\\$([^|]+))+$"); Matcher matcher = pattern.matcher(serialized); if (matcher.matches()) { String[] serializedHighlights = serialized.split("\\|"); ArrayList<Highlight> highlights = new ArrayList<>(); for (int i = 1; i < serializedHighlights.length; i++) { String[] parts; parts = serializedHighlights[i].split("\\$"); int containerElementId = 0; if (!parts[4].isEmpty()) { containerElementId = Integer.valueOf(parts[4]); } String note = null; if (parts.length == 7 && !parts[6].isEmpty()) note = parts[6]; Highlight highlight = new Highlight(parts[5], Integer.valueOf(parts[2]), parts[3], containerElementId, pageInfo, note, bookId); highlights.add(highlight); } return highlights; } else { throw new Error("Serialized highlights are invalid."); } } Highlight(String text, int id, String className, int containerElementId, String timeStampString, PageInfo pageInfo, int bookId, Title parentTitle, String noteText); Highlight(String text, int id, String className, int containerElementId, PageInfo pageInfo, String noteText, int bookId); @ColorInt static int getHighlightColor(@NonNull String className); @ColorInt static int getDarkHighlightColor(@NonNull String className); @NonNull static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId); @NonNull static ArrayList<Highlight> deserialize(@NonNull String serialized, PageInfo pageInfo, int bookId); @Override int compareTo(@NonNull Highlight highlight); boolean hasNote(); Date getDateTime(); static boolean sortByDate; public String text; public int id; public String className; public int containerElementId; public String noteText; }### Answer: @Test public void deserialize() throws Exception { ArrayList<Highlight> highlightsRerurn = Highlight.deserialize(serialized1,pagId,0); ArrayList<Highlight> highlightsGiven = new ArrayList<>(); highlightsGiven.add(new Highlight("dcdcdc ", 2, "highlight3", 0, pagId, "note",0)); highlightsGiven.add(new Highlight("cdcdc ", 4, "highlight1", 0, pagId, "note",0)); assertEquals(highlightsRerurn.size(), highlightsRerurn.size()); for (int i = 0; i < highlightsRerurn.size(); i++) { Highlight expectedHighlight = highlightsGiven.get(i); Highlight HighlightActual = highlightsGiven.get(i); assertEquals(expectedHighlight.containerElementId, HighlightActual.containerElementId); assertEquals(expectedHighlight.id, HighlightActual.id); assertEquals(expectedHighlight.className, HighlightActual.className); assertEquals(expectedHighlight.text, HighlightActual.text); } }
### Question: ArabicUtilities { public static String handleTatweela(@NonNull String s) { Matcher matcher4 = TATWEELA_PATTERN.matcher(s); StringBuffer sb2 = new StringBuffer(); while (matcher4.find()) { matcher4.appendReplacement(sb2, "$1$3"); } matcher4.appendTail(sb2); return sb2.toString(); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }### Answer: @Test public void handleTatweela() throws Exception { assertEquals(ArabicUtilities.handleTatweela("ุจู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ู€ุณู…"), "ุจุณู…"); assertEquals(ArabicUtilities.handleTatweela("ู‡ู€"), "ู‡ู€"); }
### Question: ArabicUtilities { @NonNull public static String cleanTextForSearchingWthStingBuilder(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if ((c < HAMZAH || c > YEH) & !Character.isSpace(c)) { sb.deleteCharAt(i); i--; } else if (Character.isSpace(c)) { sb.setCharAt(i, ' '); } else { switch (c) { case ALEF_MADDA: case ALEF_HAMZA_ABOVE: case ALEF_HAMZA_BELOW: sb.setCharAt(i, ALEF); break; case DOTLESS_YEH: sb.setCharAt(i, YEH); break; case TEH_MARBUTA: sb.setCharAt(i, HEH); break; default: break; } } } return sb.toString(); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }### Answer: @Test public void cleanTextForSearchingWthStingBuilder() throws Exception { }
### Question: ArabicUtilities { public static boolean startsWithDefiniteArticle(@NonNull String string) { return string.startsWith("ุงู„"); } static String cleanTashkeel(@NonNull String s); static String cleanTextForSearchingIndexing(String s); @NonNull static String cleanTextForSearchingQuery(@NonNull String s); static String handleTatweela(@NonNull String s); @NonNull static String cleanTextForSearchingWthStingBuilder(String s); static String prepareForPrefixingLam(@NonNull String string); static boolean startsWithDefiniteArticle(@NonNull String string); @NonNull static String cleanHtml(String htmlText); static final char ALEF; static final char ALEF_MADDA; static final char ALEF_HAMZA_ABOVE; static final char ALEF_HAMZA_BELOW; static final char YEH; static final char DOTLESS_YEH; static final char TEH_MARBUTA; static final char HEH; static final char TATWEEL; static final char FATHATAN; static final char DAMMATAN; static final char KASRATAN; static final char FATHA; static final char DAMMA; static final char KASRA; static final char SHADDA; static final char SUKUN; static final char HAMZAH; }### Answer: @Test public void startsWithDefiniteArticle() throws Exception { assertEquals(ArabicUtilities.startsWithDefiniteArticle("ุงู„ุจุฎุงุฑูŠ"), true); assertEquals(ArabicUtilities.startsWithDefiniteArticle("ุงู„ู„ุจู†"), true); assertEquals(ArabicUtilities.startsWithDefiniteArticle("ุงู„ู„ุญู…"), true); }
### Question: ConfigHelper { public static ConfigHelper fromFile(String file) throws IOException { return new ConfigHelper(file); } ConfigHelper(); ConfigHelper(Properties properties); @Inject ConfigHelper(List<ConfigHelper> configuration); private ConfigHelper(String configFilename); private ConfigHelper(File configFile); private ConfigHelper(InputStream input, String resourceName); static ConfigHelper fromClasspathResource(String resourceName); static ConfigHelper fromSystemProperty(String property); static ConfigHelper fromFile(String file); static ConfigHelper fromFile(File file); static ConfigHelper fromStream(InputStream input); void add(String propertyName, MappedConfiguration<String, Object> configuration); void add(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void addIfExists(String propertyName, MappedConfiguration<String, Object> configuration); void addIfExists(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void override(String propertyName, MappedConfiguration<String, Object> configuration); void override(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); void overrideIfExists(String propertyName, MappedConfiguration<String, Object> configuration); void overrideIfExists(Class<?> propertyType, String propertyName, MappedConfiguration<String, Object> configuration); Set<String> getPropertyNames(); Set<String> getReferenced(); Class<?> getPropertyType(String propertyName); String getRaw(String propertyName); void copyFrom(ConfigHelper source); static final String EXTEND; static final String PREFIX; }### Answer: @Test public void testFromFile() throws IOException { ConfigHelper helper = ConfigHelper.fromFile("src/test/resources/base-config.properties"); Assert.assertEquals("Base Property 1", helper.getRaw("prop1")); Assert.assertEquals("Base Property 2", helper.getRaw("prop2")); }
### Question: PropertyTypeValidator implements ConfigHelperValidator { @Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { continue; } if (desiredType == Object.class) { continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); typeCoercer.coerce(symbolValue, desiredType); } } PropertyTypeValidator(TypeCoercer typeCoercer, SymbolSource symbolSource); @Override void validate(ConfigHelper configHelper); }### Answer: @Test public void shouldSkipValidationOfUnreferencedProperties() { Properties properties = new Properties(); properties.put("property", "false"); ConfigHelper configHelper = new ConfigHelper(properties); PropertyTypeValidator validator = new PropertyTypeValidator(null, null); validator.validate(configHelper); } @Test public void shouldSkipValidationOfPropertiesWithDefaultType() { Properties properties = new Properties(); properties.put("property", "false"); MappedConfiguration<String, Object> configuration = Mockito.mock(MappedConfiguration.class); ConfigHelper configHelper = new ConfigHelper(properties); configHelper.add("property", configuration); Mockito.inOrder(configuration) .verify(configuration, Mockito.calls(1)) .add("property", "false"); PropertyTypeValidator validator = new PropertyTypeValidator(null, null); validator.validate(configHelper); } @Test public void shouldUseTypeCoercerWithValueFromSymbolSourceToValidatePropertyType() { Properties properties = new Properties(); properties.put("property", "${symbol}"); MappedConfiguration<String, Object> configuration = Mockito.mock(MappedConfiguration.class); TypeCoercer typeCoercer = Mockito.mock(TypeCoercer.class); SymbolSource symbolSource = Mockito.mock(SymbolSource.class); Mockito.when(symbolSource.expandSymbols("${symbol}")).thenReturn("true"); ConfigHelper configHelper = new ConfigHelper(properties); configHelper.add(Boolean.class, "property", configuration); Mockito.inOrder(configuration) .verify(configuration, Mockito.calls(1)) .add("property", "${symbol}"); PropertyTypeValidator validator = new PropertyTypeValidator(typeCoercer, symbolSource); validator.validate(configHelper); Mockito.inOrder(typeCoercer) .verify(typeCoercer, Mockito.calls(1)) .coerce("true", Boolean.class); }
### Question: JpaMetamodelRedGProvider implements NameProvider, DataTypeProvider { @Override public String getClassNameForTable(Table table) { ManagedType managedType = managedTypesByTableName.get(table.getName().toUpperCase()); return managedType != null ? managedType.getJavaType().getSimpleName() : fallbackNameProvider.getClassNameForTable(table); } 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 testGetClassNameForTable() throws Exception { Assert.assertEquals("ManagedSuperClassJoined", provider.getClassNameForTable(getTable("MANAGEDSUPERCLASSJOINED"))); Assert.assertEquals("SubEntityJoined1", provider.getClassNameForTable(getTable("SUB_ENTITY_JOINED_1"))); Assert.assertEquals("SubEntityJoined2", provider.getClassNameForTable(getTable("SUBENTITY_JOINED_2"))); Assert.assertEquals("ManagedSuperClassSingleTable", provider.getClassNameForTable(getTable("MANAGED_SUPERCLASS_SINGLE_TABLE"))); Assert.assertEquals("SubEntityTablePerClass1", provider.getClassNameForTable(getTable("SUBENTITYTABLEPERCLASS1"))); Assert.assertEquals("SubEntityTablePerClass2", provider.getClassNameForTable(getTable("SUBENTITY_TABLE_PER_CLASS_2"))); }
### Question: RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); RedGBuilder<T> withDefaultValueStrategy(final DefaultValueStrategy strategy); RedGBuilder<T> withPreparedStatementParameterSetter(final PreparedStatementParameterSetter setter); RedGBuilder<T> withSqlValuesFormatter(final SQLValuesFormatter formatter); RedGBuilder<T> withDummyFactory(final DummyFactory dummyFactory); T build(); }### Answer: @Test public void testBuilder_ClassPrivate() { expectedException.expect(RuntimeException.class); expectedException.expectMessage("Could not instantiate RedG instance"); AbstractRedG redG = new RedGBuilder<>(PrivateRedG.class).build(); } @Test public void testBuilder_DefaultConstructor() throws Exception { try { AbstractRedG redG = new RedGBuilder<>().build(); } catch (RuntimeException e) { assertEquals("Could not load default RedG class", e.getMessage()); } final ClassLoader classLoader = this.getClass().getClassLoader(); final Method defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); defineClassMethod.setAccessible(true); byte[] classDef = java.util.Base64.getDecoder().decode(this.redGClassData); defineClassMethod.invoke(classLoader, "com.btc.redg.generated.RedG", classDef, 0, classDef.length); try { AbstractRedG redG = new RedGBuilder<>().build(); } catch (RuntimeException e) { assertEquals("Could not instantiate RedG instance", e.getMessage()); } } @Test public void testBuilder_AllDefault() { MyRedG redG = new RedGBuilder<>(MyRedG.class) .build(); assertTrue(redG.getDefaultValueStrategy() instanceof DefaultDefaultValueStrategy); assertTrue(redG.getDummyFactory() instanceof DefaultDummyFactory); assertTrue(redG.getSqlValuesFormatter() instanceof DefaultSQLValuesFormatter); assertTrue(redG.getPreparedStatementParameterSetter() instanceof DefaultPreparedStatementParameterSetter); }
### Question: DefaultDummyFactory implements DummyFactory { @Override public <T extends RedGEntity> T getDummy(final AbstractRedG redG, final Class<T> dummyClass) { if (this.dummyCache.containsKey(dummyClass)) { return dummyClass.cast(this.dummyCache.get(dummyClass)); } final T obj = createNewDummy(redG, dummyClass); this.dummyCache.put(dummyClass, obj); return obj; } @Override T getDummy(final AbstractRedG redG, final Class<T> dummyClass); @Override boolean isDummy(final RedGEntity entity); }### Answer: @Test public void testGetDummy_reuseCachedObject() throws Exception { AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); TestRedGEntity1 entity1 = factory.getDummy(redG, TestRedGEntity1.class); assertNotNull(entity1); TestRedGEntity1 entity2 = factory.getDummy(redG, TestRedGEntity1.class); assertNotNull(entity1); assertEquals(entity1, entity2); } @Test public void testGetDummy_transitiveDependencies() throws Exception { AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); TestRedGEntity2 entity2 = factory.getDummy(redG, TestRedGEntity2.class); assertNotNull(entity2); assertTrue(redG.findSingleEntity(TestRedGEntity1.class, e -> true) != null); assertTrue(redG.findSingleEntity(TestRedGEntity2.class, e -> true) != null); } @Test public void testGetDummy_NoFittingConstructor() throws Exception { thrown.expect(DummyCreationException.class); thrown.expectMessage("Could not find a fitting constructor"); AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); factory.getDummy(redG, TestRedGEntity4.class); } @Test public void testGetDummy_NoFittingConstructor2() throws Exception { thrown.expect(DummyCreationException.class); thrown.expectMessage("Could not find a fitting constructor"); AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); factory.getDummy(redG, TestRedGEntity6.class); } @Test public void testGetDummy_NoFittingConstructor3() throws Exception { thrown.expect(DummyCreationException.class); thrown.expectMessage("Could not find a fitting constructor"); AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); factory.getDummy(redG, TestRedGEntity7.class); } @Test public void testGetDummy_InstantiationFails() throws Exception { thrown.expect(DummyCreationException.class); thrown.expectMessage("Instantiation of the dummy failed"); AbstractRedG redG = spy(AbstractRedG.class); DefaultDummyFactory factory = new DefaultDummyFactory(); assertNotNull(factory); factory.getDummy(redG, TestRedGEntity5.class); }
### Question: RedGDatabaseUtil { public static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection) { insertDataIntoDatabase(gObjects, connection, new DefaultPreparedStatementParameterSetter()); } private RedGDatabaseUtil(); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection); static void insertDataIntoDatabase(List<? extends RedGEntity> gObjects, final Connection connection, PreparedStatementParameterSetter preparedStatementParameterSetter); static Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor); }### Answer: @Test public void testInsertDataIntoDatabase() throws Exception { Connection connection = getConnection("-idid"); 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()); RedGDatabaseUtil.insertDataIntoDatabase(gObjects, connection); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM TEST"); rs.next(); assertEquals(20, rs.getInt(1)); } @Test public void testInsertDataIntoDatabase2() throws Exception { Connection connection = getConnection("-idid2"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); List<MockEntity3> gObjects = IntStream.rangeClosed(1, 20).mapToObj(i -> new MockEntity3()).collect(Collectors.toList()); RedGDatabaseUtil.insertDataIntoDatabase(gObjects, connection); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM TEST"); rs.next(); assertEquals(20, rs.getInt(1)); } @Test public void testInsertDataIntoDatabase3() throws Exception { Connection connection = getConnection("-idid3"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); List<MockEntity4> gObjects = IntStream.rangeClosed(1, 20).mapToObj(i -> new MockEntity4()).collect(Collectors.toList()); RedGDatabaseUtil.insertDataIntoDatabase(gObjects, connection); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM TEST"); rs.next(); assertEquals(40, rs.getInt(1)); } @Test public void testInsertExistingDataIntoDatabase() throws Exception { Connection connection = getConnection("-iedid"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); stmt.execute("INSERT INTO TEST VALUES ('obj1')"); RedGDatabaseUtil.insertDataIntoDatabase(Collections.singletonList(new ExistingMockEntity1()), connection); } @Test public void testInsertExistingDataIntoDatabase_NotExisting() throws Exception { this.thrown.expect(ExistingEntryMissingException.class); Connection connection = getConnection("-iedidm"); Statement stmt = connection.createStatement(); stmt.execute("CREATE TABLE TEST (CONTENT VARCHAR2(50 CHAR))"); RedGDatabaseUtil.insertDataIntoDatabase(Collections.singletonList(new ExistingMockEntity1()), connection); }
### Question: XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeByName(String tableName, String columnName) { if (typeMappings.getTableTypeMappings() == null) { return null; } return typeMappings.getTableTypeMappings().stream() .filter(tableTypeMapping -> tableName.matches(tableTypeMapping.getTableName())) .flatMap(tableTypeMapping -> tableTypeMapping.getColumnTypeMappings().stream()) .filter(columnTypeMapping -> columnName.matches(columnTypeMapping.getColumnName())) .findFirst() .map(ColumnTypeMapping::getJavaType) .orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }### Answer: @Test public void testGetDataTypeByName() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setTableTypeMappings(Arrays.asList( new TableTypeMapping(".+", Collections.singletonList(new ColumnTypeMapping("ACTIVE", "java.lang.Boolean"))), new TableTypeMapping("JOIN_TABLE", Collections.singletonList(new ColumnTypeMapping(".*_ID", "java.math.BigDecimal"))) )); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEquals(dataTypeProvider.getDataTypeByName("FOO", "ACTIVE"), "java.lang.Boolean"); Assert.assertEquals(dataTypeProvider.getDataTypeByName("BAR", "ACTIVE"), "java.lang.Boolean"); Assert.assertEquals(dataTypeProvider.getDataTypeByName("BAR", "INACTIVE"), null); Assert.assertEquals(dataTypeProvider.getDataTypeByName("JOIN_TABLE", "FOO_ID"), "java.math.BigDecimal"); Assert.assertEquals(dataTypeProvider.getDataTypeByName("JOIN_TABLE", "BAR"), null); }
### Question: EntitySorter { public static List<RedGEntity> sortEntities(List<RedGEntity> entities) { Map<RedGEntity, Integer> depths = new DepthCalculator().calculateDepths(entities); return entities.stream() .sorted(Comparator.comparing(EntitySorter::isExisting).reversed().thenComparingInt(depths::get)) .collect(Collectors.toList()); } static List<RedGEntity> sortEntities(List<RedGEntity> entities); }### Answer: @Test public void entitiesAreSortedByDepths() throws Exception { EntitySorter entitySorter = new EntitySorter(); Entity leafEntity1 = new Entity("leafEntity1"); Entity leafEntity2 = new Entity("leafEntity2"); Entity leafEntity3 = new Entity("leafEntity3"); Entity nonLeaf1 = new Entity("nonLeaf1", leafEntity1, leafEntity2); Entity nonLeaf2 = new Entity("nonLeaf2", leafEntity1, leafEntity3); Entity nonLeaf3 = new Entity("nonLeaf3", nonLeaf1); Entity superDependentNode = new Entity("superDependentNode", leafEntity1, nonLeaf1, nonLeaf3); List<RedGEntity> sortedEntities = entitySorter.sortEntities(Arrays.asList( superDependentNode, nonLeaf3, nonLeaf2, nonLeaf1, leafEntity1, leafEntity2, leafEntity3 )); Assert.assertEquals(Arrays.asList( leafEntity1, leafEntity2, leafEntity3, nonLeaf2, nonLeaf1, nonLeaf3, superDependentNode ), sortedEntities); } @Test public void entitiesSelfReferenceTest() throws Exception { Entity root = new Entity("root"); root.addDependency(root); Entity leaf = new Entity("leaf", root); Entity leafWithSelf = new Entity("leafWithSelf", root, leaf); leafWithSelf.addDependency(leafWithSelf); List<RedGEntity> sorted = EntitySorter.sortEntities(Arrays.asList( leaf, leafWithSelf, root)); Assert.assertEquals(Arrays.asList( root, leaf, leafWithSelf ), sorted); } @Test public void existingEntitiesFirst() throws Exception { EntitySorter entitySorter = new EntitySorter(); Entity existingEntity1 = new ExistingEntity("existingEntity1"); Entity leafEntity1 = new Entity("leafEntity1"); Entity existingEntity2 = new ExistingEntity("existingEntity2"); Entity leafEntity2 = new Entity("leafEntity2"); leafEntity2.setDependencies(null); Entity existingEntity3 = new ExistingEntity("existingEntity3"); Entity nonLeaf1 = new Entity("nonLeaf1", leafEntity1, leafEntity2); Entity existingEntity4 = new ExistingEntity("existingEntity4"); List<RedGEntity> sortedEntities = entitySorter.sortEntities(Arrays.asList( existingEntity1, nonLeaf1, existingEntity2, leafEntity1, existingEntity3, leafEntity2, existingEntity4 )); Assert.assertEquals(Arrays.asList( existingEntity1, existingEntity2, existingEntity3, existingEntity4, leafEntity1, leafEntity2, nonLeaf1 ), sortedEntities); }
### Question: DataExtractor { public void setSqlSchemaName(String sqlSchemaName) { this.sqlSchemaName = sqlSchemaName; } JavaCodeRepresentationProvider getJcrProvider(); void setJcrProvider(final JavaCodeRepresentationProvider jcrProvider); Function<EntityModel, EntityInclusionMode> getEntityModeDecider(); void setEntityModeDecider(final Function<EntityModel, EntityInclusionMode> entityModeDecider); void setSqlSchemaName(String sqlSchemaName); List<EntityModel> extractAllData(final DataSource dataSource, final List<TableModel> tableModels); List<EntityModel> extractAllData(final Connection connection, final List<TableModel> tableModels); }### Answer: @Test public void testGetFullSqlName() throws Exception { final TableModel tm1 = new TableModel(); tm1.setSqlFullName("TEST.TABLE"); assertThat(wrapGetFullTableName(new DataExtractor(), tm1)).isEqualTo("TEST.TABLE"); final TableModel tm2 = new TableModel(); tm2.setSqlFullName("TEST.\"TABLE\""); assertThat(wrapGetFullTableName(new DataExtractor(), tm2)).isEqualTo("TEST.\"TABLE\""); final TableModel tm3 = new TableModel(); tm3.setSqlFullName("\"TEST\".TABLE"); assertThat(wrapGetFullTableName(new DataExtractor(), tm3)).isEqualTo("\"TEST\".TABLE"); final TableModel tm4 = new TableModel(); tm4.setSqlFullName("TEST.TABLE"); final DataExtractor de1 = new DataExtractor(); de1.setSqlSchemaName("TEST2"); assertThat(wrapGetFullTableName(de1, tm4)).isEqualTo("TEST2.TABLE"); final TableModel tm5 = new TableModel(); tm5.setSqlFullName("TEST.TABLE"); final DataExtractor de2 = new DataExtractor(); de2.setSqlSchemaName("TEST2."); assertThat(wrapGetFullTableName(de2, tm5)).isEqualTo("TEST2.TABLE"); final TableModel tm6 = new TableModel(); tm6.setSqlFullName("TEST.\"TABLE\""); final DataExtractor de3 = new DataExtractor(); de3.setSqlSchemaName("TEST2"); assertThat(wrapGetFullTableName(de3, tm6)).isEqualTo("TEST2.\"TABLE\""); final TableModel tm7 = new TableModel(); tm7.setSqlFullName("TEST.\"TABLE\""); final DataExtractor de4 = new DataExtractor(); de4.setSqlSchemaName("TEST2."); assertThat(wrapGetFullTableName(de4, tm7)).isEqualTo("TEST2.\"TABLE\""); }
### Question: TableModelExtractor { public static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException { LOG.debug("Starting table model extraction from source code..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = srcDir.resolve(packageNameAsFolders); LOG.debug("Folder with source files is {}", codeFilePath.toAbsolutePath().toString()); final List<Path> paths = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.java")) .collect(Collectors.toList()); LOG.debug("Found following java source files:\n{}", paths.stream().map(p -> p.toAbsolutePath().toString()).collect(Collectors.joining("\n"))); for (Path p : paths) { LOG.debug("Loading source file {}", p.toAbsolutePath().toString()); final String code = new String(Files.readAllBytes(p)); final Matcher m = tableModelPattern.matcher(code); if (m.find()) { LOG.debug("Found serialized table model inside of file. Extracting..."); final String encodedModel = m.group(1); final byte[] decodedModel = Base64.getDecoder().decode(encodedModel); final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(decodedModel)); results.add((TableModel) ois.readObject()); LOG.debug("Table model successfully extracted and deserialized."); } } return results; } static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix); static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix); }### Answer: @Test @Ignore public void extractTableModelsFromSourceCode() throws Exception { TableModelExtractor.extractTableModelsFromSourceCode(Paths.get("D:\\redg\\redg-playground\\target\\generated-test-sources\\redg"), "com.btc.redg.generated", "G"); }
### Question: TableModelExtractor { public static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { LOG.debug("Starting table model extraction from compiled class files..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = classDir.resolve(packageNameAsFolders); LOG.debug("Folder with class files is {}", codeFilePath.toAbsolutePath().toString()); final List<String> classNames = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.class")) .map(classDir::relativize) .map(Path::toString) .map(name -> name.replaceFirst("\\.class$", "")) .map(name -> name.replaceAll("(/|\\\\)", ".")) .collect(Collectors.toList()); LOG.debug("Found following class files:\n{}", classNames.stream().collect(Collectors.joining("\n"))); LOG.debug("Loading all found classes..."); final ClassLoader cl = new URLClassLoader(new URL[]{classDir.toUri().toURL()}); for (String className : classNames) { LOG.debug("Loading class {}.", className); final Class cls = cl.loadClass(className); final Method m = cls.getDeclaredMethod("getTableModel"); results.add((TableModel) m.invoke(null)); LOG.debug("Successfully extracted table model."); } return results; } static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix); static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix); }### Answer: @Test @Ignore public void extractTableModelFromClasses() throws Exception { TableModelExtractor.extractTableModelFromClasses(Paths.get("D:\\redg\\redg-playground\\target\\test-classes"), "com.btc.redg.generated", "G"); }
### Question: XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeBySqlType(final Column column) { if (typeMappings.getDefaultTypeMappings() == null) { return null; } List<String> variants = DataTypePrecisionHelper.getDataTypeWithAllPrecisionVariants(column); return variants.stream() .map(variant -> typeMappings.getDefaultTypeMappings().stream() .filter(dtm -> dtm.getSqlType() .trim() .replaceAll("\\s+", " ") .replaceAll("\\s+(?=[(),])", "") .replaceAll("(?<=[(),])\\s+", "") .toUpperCase().equals(variant.toUpperCase())) .findFirst().orElse(null)) .filter(Objects::nonNull) .map(DefaultTypeMapping::getJavaType) .findFirst().orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }### Answer: @Test public void testGetDataTypeBySqlName() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setDefaultTypeMappings(Arrays.asList( new DefaultTypeMapping("DECIMAL", "java.lang.Long"), new DefaultTypeMapping("DECIMAL(1)", "java.lang.Boolean"), new DefaultTypeMapping(" TIMESTAMP WITH TIME ZONE ( 30 , 0 ) ", "java.sql.Timestamp") )); ColumnDataType cdt = Mockito.mock(ColumnDataType.class); when(cdt.getName()).thenReturn("DECIMAL"); Column column1 = Mockito.mock(Column.class); when(column1.getColumnDataType()).thenReturn(cdt); when(column1.getSize()).thenReturn(1); when(column1.getDecimalDigits()).thenReturn(0); Column column2 = Mockito.mock(Column.class); when(column2.getColumnDataType()).thenReturn(cdt); when(column2.getSize()).thenReturn(10); when(column2.getDecimalDigits()).thenReturn(0); ColumnDataType timestampWithTimeZoneDataType = Mockito.mock(ColumnDataType.class); when(timestampWithTimeZoneDataType.getName()).thenReturn("TIMESTAMP WITH TIME ZONE"); Column column3 = Mockito.mock(Column.class); when(column3.getColumnDataType()).thenReturn(timestampWithTimeZoneDataType); when(column3.getSize()).thenReturn(30); when(column3.getDecimalDigits()).thenReturn(0); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEquals("java.lang.Boolean", dataTypeProvider.getDataTypeBySqlType(column1)); Assert.assertEquals("java.lang.Long", dataTypeProvider.getDataTypeBySqlType(column2)); Assert.assertEquals("java.sql.Timestamp", dataTypeProvider.getDataTypeBySqlType(column3)); }
### Question: XmlFileDataTypeProvider implements DataTypeProvider { @Override public String getCanonicalDataTypeName(final Column column) { String dataTypeByName = getDataTypeByName(column.getParent().getName(), column.getName()); String dataTypeByType = getDataTypeBySqlType(column); return dataTypeByName != null ? dataTypeByName : dataTypeByType != null ? dataTypeByType : fallbackDataTypeProvider.getCanonicalDataTypeName(column); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); }### Answer: @Test public void testCanHandleMissingTableTypeMappings() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setDefaultTypeMappings(Collections.emptyList()); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEquals("java.lang.Integer", dataTypeProvider.getCanonicalDataTypeName(createColumnMock())); } @Test public void testCanHandleMissingDefaultTypeMappings() throws Exception { TypeMappings typeMappings = new TypeMappings(); typeMappings.setTableTypeMappings(Collections.emptyList()); XmlFileDataTypeProvider dataTypeProvider = new XmlFileDataTypeProvider(typeMappings, new DefaultDataTypeProvider()); Assert.assertEquals("java.lang.Integer", dataTypeProvider.getCanonicalDataTypeName(createColumnMock())); }