src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
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); } | @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(); } |
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); } | @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); } |
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); } | @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(); } |
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); } | @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); } |
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); } | @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); } |
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); } | @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)); } |
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); } | @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)); } |
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); } | @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); } |
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); } | @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(); } |
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); } | @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(); } |
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); } | @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); } |
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); } | @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)); } |
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); } | @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"); } |
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); } | @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(); } |
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); } | @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")); } |
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); } | @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)); } |
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); } | @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"); } |
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); } | @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"); } |
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); } | @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); } |
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); } | @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); } |
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); } | @Test public void handleSafely() throws Exception { SimpleTypeNodeHandler rnh = new SimpleTypeNodeHandler(); rnh.handleSafely(goodNode, emitter); verify(emitter).writeValue(goodNode); } |
DefaultNodeHandler extends NodeHandler<Node> { @Override public boolean handles(Node node) { return true; } @Override boolean handles(Node node); @Override boolean handleSafely(Node node, YamlEmitter emitter); } | @Test public void handles() throws Exception { DefaultNodeHandler handler = new DefaultNodeHandler(); assertTrue(handler.handles(node)); } |
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); } | @Test public void handleSafely() throws Exception { DefaultNodeHandler handler = new DefaultNodeHandler(); assertTrue(handler.handle(node, emitter)); verifyNoMoreInteractions(emitter); } |
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(); } | @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()); } |
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); } | @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(); } |
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); } | @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(); } |
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); } | @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); } |
RamlTypeFactory { public static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory) { if ( type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if ( Collection.class.isAssignableFrom((Class)parameterizedType.getRawType())) { if ( parameterizedType.getActualTypeArguments().length != 1 && ! (parameterizedType.getActualTypeArguments()[0] instanceof Class) ) { throw new IllegalArgumentException("type " + type + " is not a simple enough type for system to handle: too many parameters in type or parameter not a class"); } final Class<?> cls = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } }))); } } if ( type instanceof Class && ((Class)type).isArray() ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls.getComponentType()); return Optional.<RamlType>of(CollectionRamlType.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls.getComponentType()); return ComposedRamlType.forClass(cls.getComponentType(), adjuster.adjustTypeName(cls.getComponentType(), cls.getComponentType().getSimpleName())); } }))); } if ( type instanceof Class && Enum.class.isAssignableFrom((Class<?>) type) ) { final Class<?> cls = (Class<?>) type; RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return Optional.<RamlType>of(EnumRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName()))); } if ( type instanceof Class ) { final Class<?> cls = (Class<?>) type; Optional<RamlType> ramlType = ScalarType.fromType(cls); return Optional.of(ramlType.or(new Supplier<RamlType>() { @Override public RamlType get() { RamlAdjuster adjuster = adjusterFactory.createAdjuster(cls); return ComposedRamlType.forClass(cls, adjuster.adjustTypeName(cls, cls.getSimpleName())); } })); } return Optional.absent(); } static Optional<RamlType> forType(Type type, final ClassParser parser, final AdjusterFactory adjusterFactory); } | @Test public void forArrayOfComposed() throws Exception { when(adjusterFactory.createAdjuster(SubFun.class)).thenReturn(RamlAdjuster.NULL_ADJUSTER); RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("arrayOfSubs").getGenericType(), null, adjusterFactory).orNull(); assertTrue(type instanceof CollectionRamlType); assertEquals("array", type.getRamlSyntax().id()); }
@Test public void forScalars() throws Exception { RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("one").getGenericType(), null, null).orNull(); assertEquals("string", type.getRamlSyntax().id()); }
@Test public void forComposed() throws Exception { when(adjusterFactory.createAdjuster(SubFun.class)).thenReturn(adjuster); when(adjuster.adjustTypeName(SubFun.class, "SubFun")).thenReturn("foo"); RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("sub").getGenericType(), classParser, adjusterFactory).orNull(); assertTrue(type instanceof ComposedRamlType); assertEquals("foo", type.getRamlSyntax().id()); }
@Test public void forCollectionsOfScalars() throws Exception { RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("listOfStrings").getGenericType(), null, null).orNull(); assertTrue(type instanceof CollectionRamlType); assertEquals("array", type.getRamlSyntax().id()); }
@Test public void forCollectionsOfScalarsFromArray() throws Exception { when(adjusterFactory.createAdjuster(Fun.class)).thenReturn(RamlAdjuster.NULL_ADJUSTER); RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("arrayOfInts").getGenericType(), null, adjusterFactory).orNull(); assertTrue(type instanceof CollectionRamlType); assertEquals("array", type.getRamlSyntax().id()); }
@Test public void forListOfComposed() throws Exception { when(adjusterFactory.createAdjuster(SubFun.class)).thenReturn(RamlAdjuster.NULL_ADJUSTER); when(adjuster.adjustTypeName(SubFun.class, "SubFun")).thenReturn("foo"); RamlType type = RamlTypeFactory.forType(Fun.class.getDeclaredField("listOfSubs").getGenericType(), classParser, adjusterFactory).orNull(); assertTrue(type instanceof CollectionRamlType); assertEquals("array", type.getRamlSyntax().id()); } |
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); } | @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); } |
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); } | @Test public void fromApi() throws Exception { TopResourceSelector topResourceSelector = new TopResourceSelector(); FluentIterable<Resource> apiElements = topResourceSelector.fromApi(api); assertEquals(0, apiElements.size()); verify(api).resources(); } |
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); } | @Test public void fromResource() throws Exception { TopResourceSelector topResourceSelector = new TopResourceSelector(); FluentIterable<Resource> resourceElements = topResourceSelector.fromResource(resource); assertEquals(0, resourceElements.size()); verify(resource).resources(); } |
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); } | @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); } |
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); } | @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"); } |
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); } | @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"); } |
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(); } | @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"))); } |
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); } | @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()); } |
UnionTypeHandler implements TypeHandler { private TypeSpec.Builder getImplementation(ClassName interfaceName, GenerationContext generationContext, UnionPluginContext context, CreationResult preCreationResult) { TypeSpec.Builder typeSpec = TypeSpec.classBuilder(preCreationResult.getJavaName(EventType.IMPLEMENTATION)) .addModifiers(Modifier.PUBLIC) .addSuperinterface(interfaceName); if (UnionTypesHelper.isAmbiguous(union.of(), (x) -> findType(x.name(), x, generationContext))) { throw new GenerationException( "This union is ambiguous. It's impossible to create a correct constructor for ambiguous types: " + union.of().stream().map(x -> findType(x.name(), x, generationContext)).collect(Collectors.toList()) + ". Use unique primitive types or classes with discriminator to solve this conflict." ); } String unionEnumName = "unionType"; ClassName unionClassInterfaceName = preCreationResult.getJavaName(EventType.INTERFACE); ClassName unionEnumClassName = unionClassInterfaceName.nestedClass(Names.typeName(unionEnumName)); typeSpec.addField(FieldSpec.builder(unionEnumClassName, unionEnumName, Modifier.PRIVATE).build()); typeSpec.addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .build()); MethodSpec.Builder constructorSpec = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(ClassName.get(Object.class), "value"); boolean firstConstructorArgument = true; typeSpec.addMethod(MethodSpec.methodBuilder(Names.methodName("get", unionEnumName)) .addModifiers(Modifier.PUBLIC) .addStatement("return this.$L", unionEnumName) .returns(unionEnumClassName) .build()); for (TypeDeclaration unitedType : UnionTypesHelper.sortByPriority(union.of())) { TypeName typeName = unitedType instanceof NullTypeDeclaration ? NULL_CLASS : findType(unitedType.name(), unitedType, generationContext).box(); String prettyName = prettyName(unitedType, generationContext); String fieldName = Names.methodName(prettyName, "value"); if (typeName == NULL_CLASS) { if (firstConstructorArgument) { constructorSpec.beginControlFlow("if (value == null)"); firstConstructorArgument = false; } else { constructorSpec.beginControlFlow("else if (value == null)"); } constructorSpec.addStatement("this.$L = $T.NIL", unionEnumName, unionEnumClassName); constructorSpec.endControlFlow(); typeSpec .addMethod(MethodSpec.methodBuilder("isNil") .addStatement("return this.$L == $T.NIL", unionEnumName, unionEnumClassName) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .build()) .addMethod(MethodSpec.methodBuilder("getNil") .addModifiers(Modifier.PUBLIC).returns(typeName) .addStatement("if (!isNil()) throw new $T(\"fetching wrong type out of the union: NullType should be null\")", IllegalStateException.class) .addStatement("return null") .build()) .build(); } else { FieldSpec.Builder fieldValueSpec = FieldSpec.builder(typeName, fieldName, Modifier.PRIVATE); fieldValueSpec = generationContext.pluginsForUnions(union).fieldBuilt(context, unitedType, fieldValueSpec, EventType.IMPLEMENTATION); typeSpec.addField(fieldValueSpec.build()); String enumName = Names.enumName(prettyName); String isName = Names.methodName("is", prettyName); String getName = Names.methodName("get", prettyName); if (firstConstructorArgument) { constructorSpec.beginControlFlow("if (value instanceof $T)", typeName); firstConstructorArgument = false; } else { constructorSpec.beginControlFlow("else if (value instanceof $T)", typeName); } constructorSpec.addStatement("this.$L = $T.$L", unionEnumName, unionEnumClassName, enumName); constructorSpec.addStatement("this.$L = ($T) value", fieldName, typeName); constructorSpec.endControlFlow(); typeSpec .addMethod(MethodSpec.methodBuilder(isName) .addStatement("return this.$L == $T.$L", unionEnumName, unionEnumClassName, enumName) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .build()) .addMethod(MethodSpec.methodBuilder(getName) .addModifiers(Modifier.PUBLIC).returns(typeName) .addStatement("if (!$L()) throw new $T(\"fetching wrong type out of the union: $L\")", isName, IllegalStateException.class, typeName) .addStatement("return this.$L", fieldName) .build()) .build(); } } constructorSpec.beginControlFlow("else"); constructorSpec.addStatement("throw new $T($S + value)", IllegalArgumentException.class, "Union creation is not supported for given value: "); constructorSpec.endControlFlow(); typeSpec.addMethod(constructorSpec.build()); typeSpec = generationContext.pluginsForUnions(union).classCreated(context, union, typeSpec, EventType.IMPLEMENTATION); if (typeSpec == null) { return null; } return typeSpec; } UnionTypeHandler(String name, UnionTypeDeclaration union); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override Optional<CreationResult> create(GenerationContext generationContext, CreationResult preCreationResult); static final ClassName NULL_CLASS; } | @Test public void datesUnion() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("union-dates.raml"), "."); RamlToPojo ramlToPojo = new RamlToPojoBuilder(api).fetchTypes(TypeFetchers.fromAnywhere()).findTypes(TypeFinders.everyWhere()).build(Arrays.asList("core.jackson2")); ramlToPojo.buildPojos().creationResults().stream().forEach(x -> { System.err.println(x.getInterface().toString()); System.err.println(x.getImplementation().toString()); }); } |
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; } | @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()); } |
ObjectTypeHandler implements TypeHandler { @Override public Optional<CreationResult> create(GenerationContext generationContext, CreationResult result) { ObjectPluginContext context = new ObjectPluginContextImpl(generationContext, result); TypeSpec interfaceSpec = createInterface(context, result, generationContext); TypeSpec implementationSpec = createImplementation(context, result, generationContext); if ( interfaceSpec == null ) { return Optional.absent(); } else { return Optional.of(result.withInterface(interfaceSpec).withImplementation(implementationSpec)); } } ObjectTypeHandler(String name, ObjectTypeDeclaration objectTypeDeclaration); @Override ClassName javaClassName(GenerationContext generationContext, EventType type); @Override TypeName javaClassReference(GenerationContext generationContext, EventType type); @Override // TODO deal with null interface spec. Optional<CreationResult> create(GenerationContext generationContext, CreationResult result); static final String DISCRIMINATOR_TYPE_NAME; } | @Test public void simplest() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("simplest-type.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); GenerationContextImpl generationContext = new GenerationContextImpl(api); CreationResult r = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); assertThat(r.getInterface()) .hasName("Foo"); ListAssert.listMatches(r.getInterface().methodSpecs, (c) -> assertThat(c) .hasName("getName") .hasReturnType(ClassName.get(String.class)), (c) -> assertThat(c) .hasName("setName") .hasReturnType(ClassName.VOID), (c) -> assertThat(c) .hasName("getAge") .hasReturnType(ClassName.INT), (c) -> assertThat(c) .hasName("setAge") .hasReturnType(ClassName.VOID)); assertThat(r.getInterface(), is(allOf( name(equalTo("Foo")), methods(contains( allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getAge")), returnType(equalTo(ClassName.INT))), allOf(methodName(equalTo("setAge")), parameters(contains(type(equalTo(ClassName.INT))))) )) ))); assertThat(r.getImplementation().get(), is(allOf( name(equalTo("FooImpl")), fields(contains( allOf(fieldName(equalTo("name")), fieldType(equalTo(ClassName.get(String.class)))), allOf(fieldName(equalTo("age")), fieldType(equalTo(ClassName.INT))) )), methods(contains( allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class))), codeContent(equalTo("return this.name;\n"))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class))))), codeContent(equalTo("this.name = name;\n"))), allOf(methodName(equalTo("getAge")), returnType(equalTo(ClassName.INT))), allOf(methodName(equalTo("setAge")), parameters(contains(type(equalTo(ClassName.INT))))) )), superInterfaces(contains( allOf(typeName(equalTo(ClassName.get("", "bar.pack.Foo")))) )) ))); System.err.println(r.getInterface().toString()); System.err.println(r.getImplementation().toString()); }
@Test public void simplestContainingSimpleArray() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("simplest-containing-simple-array.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); GenerationContextImpl generationContext = new GenerationContextImpl(api); CreationResult r = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); System.err.println(r.getInterface().toString()); System.err.println(r.getImplementation().toString()); assertThat(r.getInterface(), is(allOf( name(equalTo("Foo")), methods(contains( allOf(methodName(equalTo("getNames")), returnType(equalTo(ParameterizedTypeName.get(List.class, String.class)))), allOf(methodName(equalTo("setNames")), parameters(contains(type(equalTo(ParameterizedTypeName.get(List.class, String.class)))))), allOf(methodName(equalTo("getAges")), returnType(equalTo(ParameterizedTypeName.get(List.class, Integer.class)))), allOf(methodName(equalTo("setAges")), parameters(contains(type(equalTo(ParameterizedTypeName.get(List.class, Integer.class)))))) )) ))); assertThat(r.getImplementation().get(), is(allOf( name(equalTo("FooImpl")), fields(contains( allOf(fieldName(equalTo("names")), fieldType(equalTo(ParameterizedTypeName.get(List.class, String.class)))), allOf(fieldName(equalTo("ages")), fieldType(equalTo(ParameterizedTypeName.get(List.class, Integer.class)))) )), methods(contains( allOf(methodName(equalTo("getNames")), returnType(equalTo(ParameterizedTypeName.get(List.class, String.class)))), allOf(methodName(equalTo("setNames")), parameters(contains(type(equalTo(ParameterizedTypeName.get(List.class, String.class)))))), allOf(methodName(equalTo("getAges")), returnType(equalTo(ParameterizedTypeName.get(List.class, Integer.class)))), allOf(methodName(equalTo("setAges")), parameters(contains(type(equalTo(ParameterizedTypeName.get(List.class, Integer.class)))))) )) ))); }
@Test public void usingComposedTypes() throws Exception { final Api api = RamlLoader.load(this.getClass().getResourceAsStream("using-composed-type.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); CreationResult r = handler.create(createGenerationContext(api), new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); System.err.println(r.getInterface().toString()); System.err.println(r.getImplementation().toString()); assertThat(r.getInterface(), is(allOf( name(equalTo("Foo")), methods(contains( allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get("", "pojo.pack.Composed")))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get("", "pojo.pack.Composed")))))) )) ))); assertThat(r.getImplementation().get(), is(allOf( name(equalTo("FooImpl")), fields(contains( allOf(fieldName(equalTo("name")), fieldType(equalTo(ClassName.get("", "pojo.pack.Composed")))) )), methods(contains( allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get("", "pojo.pack.Composed")))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get("", "pojo.pack.Composed"))))))) )) )); }
@Test public void simpleInheritance() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("inherited-type.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); CreationResult r = handler.create(createGenerationContext(api), new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); System.err.println(r.getInterface().toString()); System.err.println(r.getImplementation().toString()); assertThat(r.getInterface(), is(allOf( name(equalTo("Foo")), methods(containsInAnyOrder( allOf(methodName(equalTo("getAdditionalProperties")), returnType(equalTo(ParameterizedTypeName.get(Map.class, String.class, Object.class)))), allOf(methodName(equalTo("setAdditionalProperties")), parameters(contains(type(equalTo(TypeName.get(String.class))), type(equalTo(TypeName.get(Object.class)))))), allOf(methodName(equalTo("getAge")), returnType(equalTo(ClassName.INT))), allOf(methodName(equalTo("setAge")), parameters(contains(type(equalTo(ClassName.INT))))), allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))) )), superInterfaces(contains( allOf(typeName(equalTo(ClassName.get("", "pojo.pack.Inherited")))) ))))); assertThat(r.getImplementation().get(), is(allOf( name(equalTo("FooImpl")), fields(containsInAnyOrder( allOf(fieldName(equalTo("name")), fieldType(equalTo(ClassName.get(String.class)))), allOf(fieldName(equalTo("age")), fieldType(equalTo(ClassName.INT))), allOf(fieldName(equalTo("additionalProperties")), fieldType(equalTo(ParameterizedTypeName.get(Map.class, String.class, Object.class)))) )), methods(containsInAnyOrder( allOf(methodName(equalTo("getAdditionalProperties")), returnType(equalTo(ParameterizedTypeName.get(Map.class, String.class, Object.class)))), allOf(methodName(equalTo("setAdditionalProperties")), parameters(contains(type(equalTo(TypeName.get(String.class))), type(equalTo(TypeName.get(Object.class)))))), allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getAge")), returnType(equalTo(ClassName.INT))), allOf(methodName(equalTo("setAge")), parameters(contains(type(equalTo(ClassName.INT))))) )), superInterfaces(contains( allOf(typeName(equalTo(ClassName.get("", "bar.pack.Foo")))) )) ))); }
@Test public void inheritanceWithDiscriminator() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("inheritance-with-discriminator-type.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); CreationResult r = handler.create(createGenerationContext(api), new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); System.err.println(r.getInterface().toString()); System.err.println(r.getImplementation().toString()); assertThat(r.getInterface(), is(allOf( name(equalTo("Foo")), methods(containsInAnyOrder( allOf(methodName(equalTo("getAdditionalProperties")), returnType(equalTo(ParameterizedTypeName.get(Map.class, String.class, Object.class)))), allOf(methodName(equalTo("setAdditionalProperties")), parameters(contains(type(equalTo(TypeName.get(String.class))), type(equalTo(TypeName.get(Object.class)))))), allOf(methodName(equalTo("getKind")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("getRight")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setRight")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))) )), superInterfaces(contains( allOf(typeName(equalTo(ClassName.get("", "pojo.pack.Once")))) ))))); assertThat(r.getImplementation().get(), is(allOf( name(equalTo("FooImpl")), fields(containsInAnyOrder( allOf(fieldName(equalTo("kind")), fieldType(equalTo(ClassName.get(String.class))), initializer(equalTo("_DISCRIMINATOR_TYPE_NAME"))), allOf(fieldName(equalTo("right")), fieldType(equalTo(ClassName.get(String.class)))), allOf(fieldName(equalTo("name")), fieldType(equalTo(ClassName.get(String.class)))), allOf(fieldName(equalTo("additionalProperties")), fieldType(equalTo(ParameterizedTypeName.get(Map.class, String.class, Object.class)))) )), methods(containsInAnyOrder( allOf(methodName(equalTo("getAdditionalProperties")), returnType(equalTo(ParameterizedTypeName.get(Map.class, String.class, Object.class)))), allOf(methodName(equalTo("setAdditionalProperties")), parameters(contains(type(equalTo(TypeName.get(String.class))), type(equalTo(TypeName.get(Object.class)))))), allOf(methodName(equalTo("getKind")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("getRight")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setRight")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))) )), superInterfaces(contains( allOf(typeName(equalTo(ClassName.get("", "bar.pack.Foo")))) )) ))); }
@Test public void inheritanceWithDiscriminatorAndValue() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("inheritance-with-discriminatorvalue-type.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); CreationResult r = handler.create(createGenerationContext(api), new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); System.err.println(r.getInterface().toString()); System.err.println(r.getImplementation().toString()); assertThat(r.getImplementation().get(), is(allOf( name(equalTo("FooImpl")), fields(containsInAnyOrder( allOf(fieldName(equalTo("kind")), fieldType(equalTo(ClassName.get(String.class))), initializer(equalTo("_DISCRIMINATOR_TYPE_NAME"))), allOf(fieldName(equalTo("right")), fieldType(equalTo(ClassName.get(String.class)))), allOf(fieldName(equalTo("name")), fieldType(equalTo(ClassName.get(String.class)))) )) ))); }
@Test public void multipleInheritance() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("multiple-inheritance-type.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); CreationResult r = handler.create(createGenerationContext(api), new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); System.err.println(r.getInterface().toString()); System.err.println(r.getImplementation().toString()); assertThat(r.getInterface(), is(allOf( name(equalTo("Foo")), methods(containsInAnyOrder( allOf(methodName(equalTo("getLeft")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setLeft")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getRight")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setRight")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))) )), superInterfaces(contains( typeName(equalTo(ClassName.get("", "pojo.pack.Once"))), typeName(equalTo(ClassName.get("", "pojo.pack.Twice"))) ) )))); assertThat(r.getImplementation().get(), is(allOf( name(equalTo("FooImpl")), fields(containsInAnyOrder( allOf(fieldName(equalTo("left")), fieldType(equalTo(ClassName.get(String.class)))), allOf(fieldName(equalTo("right")), fieldType(equalTo(ClassName.get(String.class)))), allOf(fieldName(equalTo("name")), fieldType(equalTo(ClassName.get(String.class)))) )), methods(containsInAnyOrder( allOf(methodName(equalTo("getLeft")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setLeft")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getRight")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setRight")), parameters(contains(type(equalTo(ClassName.get(String.class)))))), allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))) )), superInterfaces(contains( allOf(typeName(equalTo(ClassName.get("", "bar.pack.Foo")))) )) ))); }
@Test public void simplestInternal() throws Exception { Api api = RamlLoader.load(this.getClass().getResourceAsStream("inline-type.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", findTypes("foo", api.types())); GenerationContextImpl generationContext = new GenerationContextImpl(api); CreationResult r = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); assertThat(r.getInternalTypeForProperty("inside").getInterface(), name(equalTo("InsideType"))); assertThat(r.getInternalTypeForProperty("inside").getImplementation().get(), name(equalTo("InsideTypeImpl"))); }
@Test public void pluginCalled() throws Exception { final ObjectTypeHandlerPlugin mockPlugin = mock(ObjectTypeHandlerPlugin.class); when(mockPlugin.classCreated(ArgumentMatchers.any(ObjectPluginContext.class), ArgumentMatchers.any(ObjectTypeDeclaration.class), ArgumentMatchers.any(TypeSpec.Builder.class), eq(EventType.INTERFACE))).thenAnswer(new Answer<TypeSpec.Builder>() { @Override public TypeSpec.Builder answer(InvocationOnMock invocation) throws Throwable { return (TypeSpec.Builder) invocation.getArguments()[2]; } }); when(mockPlugin.getterBuilt(ArgumentMatchers.any(ObjectPluginContext.class), ArgumentMatchers.any(ObjectTypeDeclaration.class), ArgumentMatchers.any(MethodSpec.Builder.class), eq(EventType.INTERFACE))).thenAnswer(new Answer<MethodSpec.Builder>() { @Override public MethodSpec.Builder answer(InvocationOnMock invocation) throws Throwable { return (MethodSpec.Builder) invocation.getArguments()[2]; } }); when(mockPlugin.setterBuilt(ArgumentMatchers.any(ObjectPluginContext.class), ArgumentMatchers.any(ObjectTypeDeclaration.class), ArgumentMatchers.any(MethodSpec.Builder.class), eq(EventType.INTERFACE))).thenAnswer(new Answer<MethodSpec.Builder>() { @Override public MethodSpec.Builder answer(InvocationOnMock invocation) throws Throwable { return (MethodSpec.Builder) invocation.getArguments()[2]; } }); Api api = RamlLoader.load(this.getClass().getResourceAsStream("plugin-test.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", findTypes("foo", api.types())); GenerationContextImpl generationContext = new GenerationContextImpl(api) { @Override public ObjectTypeHandlerPlugin pluginsForObjects(TypeDeclaration... typeDeclarations) { return mockPlugin; } }; CreationResult r = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); assertNotNull(r); assertFalse(r.getImplementation().isPresent()); verify(mockPlugin, times(1)).classCreated(ArgumentMatchers.any(ObjectPluginContext.class), ArgumentMatchers.any(ObjectTypeDeclaration.class), ArgumentMatchers.any(TypeSpec.Builder.class), eq(EventType.INTERFACE)); verify(mockPlugin, times(2)).getterBuilt(ArgumentMatchers.any(ObjectPluginContext.class), ArgumentMatchers.any(StringTypeDeclaration.class), ArgumentMatchers.any(MethodSpec.Builder.class), eq(EventType.INTERFACE)); verify(mockPlugin, times(2)).setterBuilt(ArgumentMatchers.any(ObjectPluginContext.class), ArgumentMatchers.any(StringTypeDeclaration.class), ArgumentMatchers.any(MethodSpec.Builder.class), eq(EventType.INTERFACE)); }
@Test public void checkAnnotations() throws Exception { URL url = this.getClass().getResource("plugin-invocation.raml"); Api api = RamlLoader.load(url.openStream(), new File(url.getFile()).getAbsolutePath()); ObjectTypeHandler handler = new ObjectTypeHandler("foo", findTypes("foo", api.types())); GenerationContextImpl generationContext = new GenerationContextImpl(PluginManager.createPluginManager("org/raml/ramltopojo/object/simple-plugin.properties"), api, TypeFetchers.NULL_FETCHER, "bar.pack", Collections.<String>emptyList()); CreationResult r = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); assertNotNull(r); assertTrue(r.getInterface().annotations.size() == 1); assertEquals("@java.lang.Deprecated", r.getInterface().annotations.get(0).toString()); assertTrue(r.getImplementation().get().annotations.size() == 1); assertEquals("@java.lang.Deprecated", r.getImplementation().get().annotations.get(0).toString()); }
@Test public void enumerationsInline() { Api api = RamlLoader.load(this.getClass().getResourceAsStream("inline-enumeration.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); CreationResult r = handler.create(createGenerationContext(api), new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); assertNotNull(r); assertThat(r.internalType("name").getInterface(), is(allOf( name( is(equalTo("NameType")) ) ))); assertThat(r.internalType("int").getInterface(), is(allOf( name( is(equalTo("IntType")) ) ))); assertThat(r.internalType("num").getInterface(), is(allOf( name( is(equalTo("NumType")) ) ))); }
@Test public void unionsInline() { Api api = RamlLoader.load(this.getClass().getResourceAsStream("inline-union.raml"), "."); ObjectTypeHandler handler = new ObjectTypeHandler("foo", RamlLoader.findTypes("foo", api.types())); CreationResult r = handler.create(createGenerationContext(api), new CreationResult("bar.pack", ClassName.get("bar.pack", "Foo"), ClassName.get("bar.pack", "FooImpl"))).get(); assertNotNull(r); assertThat(r.internalType("unionOfPrimitives").getInterface(), is(allOf( name( is(equalTo("StringIntegerUnion")) ), methods(containsInAnyOrder( allOf(methodName(equalTo("getUnionType")), returnType(equalTo(ClassName.get("bar.pack", "Foo.StringIntegerUnion.UnionType")))), allOf(methodName(equalTo("isString")), returnType(equalTo(ClassName.get(Boolean.class).unbox()))), allOf(methodName(equalTo("getString")), returnType(equalTo(ClassName.get(String.class)))), allOf(methodName(equalTo("isInteger")), returnType(equalTo(ClassName.get(Boolean.class).unbox()))), allOf(methodName(equalTo("getInteger")), returnType(equalTo(ClassName.get(Integer.class)))) )) ))); assertThat(r.internalType("unionOfOthers").getInterface(), is(allOf( name( is(equalTo("OneTwoUnion")) ), methods(contains( allOf(methodName(equalTo("getUnionType")), returnType(equalTo(ClassName.get("bar.pack", "Foo.OneTwoUnion.UnionType")))), allOf(methodName(equalTo("isOne")), returnType(equalTo(ClassName.get(Boolean.class).unbox()))), allOf(methodName(equalTo("getOne")), returnType(equalTo(ClassName.get("pojo.pack", "One")))), allOf(methodName(equalTo("isTwo")), returnType(equalTo(ClassName.get(Boolean.class).unbox()))), allOf(methodName(equalTo("getTwo")), returnType(equalTo(ClassName.get("pojo.pack", "Two")))) )) ))); System.err.println(r.internalType("unionOfOthers").getInterface()); } |
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); } | @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"); } |
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); } | @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")); } |
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); } | @Test public void buildMethod() { assertEquals("getSomething", Names.methodName("get", "something")); assertEquals("getClazz", Names.methodName("get", "class")); } |
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); } | @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")); } |
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); } | @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); } |
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); } | @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()); } |
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); } | @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); } |
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); } | @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); } |
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); } | @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()); } |
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); } | @Test public void anyFieldCreated() { } |
Jsr303Extension extends AllTypesPluginHelper { @Override public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder fieldSpec, EventType eventType) { AnnotationAdder adder = new AnnotationAdder() { @Override public TypeName typeName() { return fieldSpec.build().type; } @Override public void addAnnotation(AnnotationSpec spec) { fieldSpec.addAnnotation(spec); } }; addAnnotations(typeDeclaration, adder); return fieldSpec; } @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); } | @Test public void forInteger() throws Exception { setupNumberFacets(); Jsr303Extension ext = new Jsr303Extension(); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Integer.class), "champ", Modifier.PUBLIC); ext.fieldBuilt(objectPluginContext, number, builder, EventType.IMPLEMENTATION); assertForIntegerNumber(builder); }
@Test public void forBigInt() throws Exception { setupNumberFacets(); Jsr303Extension ext = new Jsr303Extension(); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(BigInteger.class), "champ", Modifier.PUBLIC); ext.fieldBuilt(objectPluginContext, number, builder, EventType.IMPLEMENTATION); assertForIntegerNumber(builder); }
@Test public void forObject() throws Exception { Jsr303Extension ext = new Jsr303Extension(); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Double.class), "champ", Modifier.PUBLIC); ext.fieldBuilt(objectPluginContext, object, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Test public void forDouble() throws Exception { setupNumberFacets(); Jsr303Extension ext = new Jsr303Extension(); FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Double.class), "champ", Modifier.PUBLIC); ext.fieldBuilt(objectPluginContext, object, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Test public void forArrays() throws Exception { when(array.minItems()).thenReturn(3); when(array.maxItems()).thenReturn(5); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Size.class.getName(), builder.build().annotations.get(0).type.toString()); assertEquals("3", builder.build().annotations.get(0).members.get("min").get(0).toString()); assertEquals("5", builder.build().annotations.get(0).members.get("max").get(0).toString()); }
@Test public void forArraysOfStrings() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(null); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(0, builder.build().annotations.size()); }
@Test public void forArraysOfObject() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(null); when(array.items()).thenReturn(object); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Test public void forArraysOfUnion() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(null); when(array.items()).thenReturn(union); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString()); }
@Test public void forArraysMaxOnly() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(5); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(Size.class.getName(), builder.build().annotations.get(0).type.toString()); assertEquals(1, builder.build().annotations.get(0).members.size()); assertEquals("5", builder.build().annotations.get(0).members.get("max").get(0).toString()); }
@Test public void forArraysNotNull() throws Exception { when(array.minItems()).thenReturn(null); when(array.maxItems()).thenReturn(null); when(array.required()).thenReturn(true); FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ", Modifier.PUBLIC); Jsr303Extension ext = new Jsr303Extension(); ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION); assertEquals(1, builder.build().annotations.size()); assertEquals(NotNull.class.getName(), builder.build().annotations.get(0).type.toString()); } |
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); } | @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()); } |
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); } | @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()); } |
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); } | @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()); } |
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; } | @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"); } |
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; } | @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"); } |
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; } | @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); } |
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(); } | @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))); } |
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(); } | @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))); } |
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(); } | @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))); } |
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); } | @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()); } |
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); } | @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()); } |
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); } | @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()); } |
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; } | @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()); } |
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); } | @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) ); } |
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); } | @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); } |
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); } | @Test public void handles() throws Exception { ReferenceNodeHandler handler = new ReferenceNodeHandler(); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); } |
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); } | @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"); } |
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); } | @Test public void handles() throws Exception { TypeDeclarationNodeHandler tdnh = new TypeDeclarationNodeHandler(list); assertFalse(tdnh.handles(badNode)); assertTrue(tdnh.handles(goodNode)); } |
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); } | @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); } |
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); } | @Test public void handles() throws Exception { ArrayNodeHandler handler = new ArrayNodeHandler(list); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); } |
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); } | @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); } |
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); } | @Test public void handles() throws Exception { KeyValueNodeHandler handler = new KeyValueNodeHandler(list); assertFalse(handler.handles(notKeyNode)); assertTrue(handler.handles(keyNode)); } |
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); } | @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); } |
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); } | @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); } |
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); } | @Test public void handles() throws Exception { TypeExpressionNodeHandler handler = new TypeExpressionNodeHandler(list); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); } |
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); } | @Test public void handleSafely() throws Exception { when(goodNode.getTypeExpressionText()).thenReturn("JustReference"); TypeExpressionNodeHandler handler = new TypeExpressionNodeHandler(list); handler.handle(goodNode, emitter); verify(emitter).writeObjectValue("JustReference"); } |
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); } | @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"); } |
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); } | @Test public void handles() throws Exception { NullNodeHandler handler = new NullNodeHandler(); assertFalse(handler.handles(notNullNode)); assertTrue(handler.handles(nullNode)); } |
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); } | @Test public void handleSafely() throws Exception { NullNodeHandler nul = new NullNodeHandler(); nul.handleSafely(nullNode, emitter); verifyNoMoreInteractions(emitter); } |
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); } | @Test public void handles() throws Exception { SimpleTypeNodeHandler handler = new SimpleTypeNodeHandler(); assertFalse(handler.handles(badNode)); assertTrue(handler.handles(goodNode)); } |
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; } | @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()); } |
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; } | @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); } } |
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; } | @Test public void handleTatweela() throws Exception { assertEquals(ArabicUtilities.handleTatweela("ุจูููููููููููููููููููุณู
"), "ุจุณู
"); assertEquals(ArabicUtilities.handleTatweela("ูู"), "ูู"); } |
ArabicUtilities { public static String cleanTextForSearchingIndexing(String s) { return cleanTextForSearchingQuery(cleanHtml(s)); } 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; } | @Test public void cleanTextForSearchingIndexing() throws Exception { assertEquals(ArabicUtilities.cleanTextForSearchingIndexing(testCase), "ูุฐุง ุงูู
ุณุชุฏุฑู ุซู
ุจุนุฏ ุงู ุฌู
ุนุช ูุชุงูู ูุฑุณุงุฆู ู
ูุชู ุงูุฏูุงุฑ ุงูุณุนูุฏูู ูุฑุฆูุณ ูุถุงุฆูุง ูุงูุดุฆูู ุงูุงุณูุงู
ูู ุณู
ุงุญู ุงูุดูุฎ ู
ุญู
ุฏ ุจู ุงุจุฑุงููู
ุงู ุงูุดูุฎ ุจุงู
ุฑ ุฌูุงูู ุงูู
ูู ููุตู ุจู ุนุจุฏ ุงูุนุฒูุฒ ุงู ุณุนูุฏ ุฑุญู
ู ุงููู ูุทุจุนุช ูู ู
ุทุจุนู ุงูุญููู
ู ุจู
ูู ุงูู
ูุฑู
ู ุนุงู
ุชุณุนู ูุชุณุนูู ูุซูุงุซู
ุงุฆู ูุงูู ุจุงู
ุฑู ูู ุซูุงุซู ุนุดุฑ ู
ุฌูุฏุง ูุงูุชุดุฑุช ูุงูุชูุน ุงููุงุณ ุจูุง ููุฑุช ูู ุงูุจุญุซ ุนู ุดูุก ู
ุง ูุดูุฎ ุงูุงุณูุงู
ุงุญู
ุฏ ุงุจู ุชูู
ูู ูุฏุณ ุงููู ุฑูุญู ูุชุฐูุฑุช ุงูู ุญูู ุณุงูุฑุช ุงูู ุจุบุฏุงุฏ ููุจุญุซ ุนู ูุชุงูู ุดูุฎ ุงูุงุณูุงู
ุนุซุฑุช ุนูู ู
ุฌูุฏ ู
ู ุงูุฏุฑุฑ ุงูู
ุถูู ู
ู ุงููุชุงูู ุงูู
ุตุฑูู ูุนุฏุฏ ู
ุฌูุฏุงุชูุง ุณุชู ููู
ุง ุฐูุฑู ุงุจู ุงูููู
ุฑุญู
ู ุงููู ููููู ุงูุนููู
ู ุณุจุนู ูุชุจูู ุงู ุงูุฎู
ุณู ุงูุจุงููู ู
ูููุฏู ุฑุงูุช ุจุนุฏ ุฐูู ุงู ุงุฑุฌุน ุงูู ู
ุฎุชุตุฑ ูุฐู ุงููุชุงูู ุงูุฐู ุงุฎุชุตุฑู ุจุฏุฑ ุงูุฏูู ู
ุญู
ุฏ ุจู ุนูู ุจู ู
ุญู
ุฏ ุงูุจุนูู ุงูุญูุจูู ุงูู
ุชููู ุณูู ุงู ูู ูุทุจุน ูู ู
ุทุจุนู ุงูุตุงุฑ ุงูุณูู ุจู
ุตุฑ ูู ุนุงู
ูู ูุงุฌู
ุน ู
ููุง ู
ุง ููุณ ูู ุงูุฌุฒุก ุงูุงูู ุงูุฐู ุงุฏุฎูุชู ูู ู
ุฌู
ูุน ุงููุชุงูู ุงูุณุงุจู ููุฌุฏุช ููู ูุชุงูู ูุซูุฑู ููุณุช ูู ุงูู
ุฌู
ูุน ุงูุงูู ุจูุบ ุนุฏุฏูุง ุณุจุนุง ูุฎู
ุณูู ูู
ุงุฆุชู ู
ุณุงูู ูููู ู
ููุง ู
ูุฌูุฏ ูู ุงูู
ุฌู
ูุน ุงูุณุงุจู ููู ูู ูุฐุง ู
ุน ุฒูุงุฏู ูููุง ููุฑุณ ุนุงู
ูู ู
ุฌูุฏ ู
ุฎุทูุท ุฐูุฑูุง ุงุจู ุงูููู
ูู ุงูููููู ุจูููู ููุฐุงู ุงุฌูุจู ูู ู
ุตุฑูู ูู ุณุช ุงุณูุงุฑ ูุชุจู ุณู
ุงู ููููู ุงูุนููู
ู ุงููุง ุณุจุน ู
ุฌูุฏุงุช ุงูุฏุฑ ุงูู
ูุถุฏ ุฌู "); } |
ArabicUtilities { @NonNull public static String cleanHtml(String htmlText) { Document doc = Jsoup.parse(htmlText); Elements footnotes = doc.select("a[title].comment"); StringBuilder htmlTextBuilder = new StringBuilder(htmlText); for (Element footnote : footnotes) { htmlTextBuilder.append("\n").append(footnote.attr("title")); } String encodedHtml = REMOVE_HTML_TAGS.matcher(htmlTextBuilder.toString()).replaceAll(""); return encodedHtml; } 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; } | @Test public void cleanHtml() throws Exception { assertEquals(ArabicUtilities.cleanHtml(testCase), "ูุฐุง ุงูู
ุณุชุฏุฑู\nุซู
ุจุนุฏ ุฃู ุฌู
ุนุช ูุชุงูู ูุฑุณุงุฆู ู
ูุชู ุงูุฏูุงุฑ ุงูุณุนูุฏูุฉ ูุฑุฆูุณ ูุถุงุฆูุง ูุงูุดุฆูู ุงูุฅุณูุงู
ูุฉ ุณู
ุงุญุฉ ุงูุดูุฎ ู
ุญู
ุฏ ุจู ุฅุจุฑุงููู
ุขู ุงูุดูุฎ ุจุฃู
ุฑ ุฌูุงูุฉ ุงูู
ูู ููุตู ุจู ุนุจุฏ ุงูุนุฒูุฒ ุขู ุณุนูุฏ ุฑุญู
ู ุงููู ูุทุจุนุช ูู ู
ุทุจุนุฉ ุงูุญููู
ุฉ ุจู
ูุฉ ุงูู
ูุฑู
ุฉ ุนุงู
ุชุณุนุฉ ูุชุณุนูู ูุซูุงุซู
ุงุฆุฉ ูุฃูู ุจุฃู
ุฑู ูู ุซูุงุซุฉ ุนุดุฑ ู
ุฌูุฏุง ูุงูุชุดุฑุชุ ูุงูุชูุน ุงููุงุณ ุจูุง (?) ููุฑุช ูู ุงูุจุญุซ ุนู ุดูุก ยซู
ุงยป ูุดูุฎ ุงูุฅุณูุงู
ุฃุญู
ุฏ ุงุจู ุชูู
ูุฉ (ูุฏุณ ุงููู ุฑูุญู) ุ ูุชุฐูุฑุช ุฃูู ุญูู ุณุงูุฑุช ุฅูู ุจุบุฏุงุฏ ููุจุญุซ ุนู ูุชุงูู ุดูุฎ ุงูุฅุณูุงู
ุนุซุฑุช ุนูู ู
ุฌูุฏ ู
ู ยซุงูุฏุฑุฑ ุงูู
ุถูุฉ ู
ู ุงููุชุงูู ุงูู
ุตุฑูุฉยป ูุนุฏุฏ ู
ุฌูุฏุงุชูุง ุณุชุฉ ููู
ุง ุฐูุฑู ุงุจู ุงูููู
ุฑุญู
ู ุงููู ููููู ุงูุนููู
ู ุณุจุนุฉ (?) ุ ูุชุจูู ุฃู ุงูุฎู
ุณุฉ ุงูุจุงููุฉ ู
ูููุฏุฉ ุฑุฃูุช ุจุนุฏ ุฐูู ุฃู ุฃุฑุฌุน ุฅูู ู
ุฎุชุตุฑ ูุฐู ุงููุชุงูู ุงูุฐู ุงุฎุชุตุฑู ุจุฏุฑ ุงูุฏูู ู
ุญู
ุฏ ุจู ุนูู ุจู ู
ุญู
ุฏ ุงูุจุนูู ุงูุญูุจูู ุงูู
ุชููู ุณูุฉ 777 ุฃู 778ูู ูุทุจุน ูู ู
ุทุจุนุฉ ุฃูุตุงุฑ ุงูุณูุฉ ุจู
ุตุฑ ูู ุนุงู
1368ูู ูุฃุฌู
ุน ู
ููุง ู
ุง ููุณ ูู ุงูุฌุฒุก ุงูุฃูู ุงูุฐู ุฃุฏุฎูุชู ูู ู
ุฌู
ูุน ุงููุชุงูู ุงูุณุงุจูุ ููุฌุฏุช ููู ูุชุงูู ูุซูุฑุฉ ููุณุช ูู ุงูู
ุฌู
ูุน ุงูุฃููุ ุจูุบ ุนุฏุฏูุง ุณุจุนุง ูุฎู
ุณูู ูู
ุงุฆุชู ู
ุณุฃูุฉ ูููู ู
ููุง ู
ูุฌูุฏ ูู ุงูู
ุฌู
ูุน ุงูุณุงุจู ููู ูู ูุฐุง ู
ุน ุฒูุงุฏุฉ.\n\nูููุง ููุฑุณ ุนุงู
ูู ู
ุฌูุฏ ู
ุฎุทูุท.\nุฐูุฑูุง ุงุจู ุงูููู
ูู ุงูููููุฉ ุจูููู:\nููุฐุงู ุฃุฌูุจุฉ ูู ู
ุตุฑูุฉ ... ูู ุณุช ุฃุณูุงุฑ ูุชุจู ุณู
ุงู\nููููู ุงูุนููู
ู: ุฅููุง ุณุจุน ู
ุฌูุฏุงุช (ุงูุฏุฑ ุงูู
ูุถุฏ ุฌู2/478)"); } |
ArabicUtilities { public static String cleanTashkeel(@NonNull String s) { Matcher matcher = CLEANING_TASHKEEL.matcher(s); return matcher.replaceAll(""); } 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; } | @Test public void cleanTashkeel() throws Exception { String testStringWithTashkeel = "ููููู
ู ููุฏู ุฑูุฃูููููุง ู
ููู ุฑูุฌูุงูู ููุฏูููููุฉู ... ููุจูุงุฏููุง ุฌูู
ููุนูุง ู
ูุณูุฑูุนูููู ููุฒูุงูููุง"; String testStringWithTashkeel2 = "ุฎูููุงูู ููุตูุญูู ุชูุฎูุฑููุฌููู ุนูููู ููุฐููู ุงููููุงุนูุฏูุฉู ููุฃูููู ูููููููู ุญูุฑูุงู
ู ู
ูุทููููู ุฏูุงููู ุนูููู ู
ูุทููููู ุงูุชููุญูุฑููู
ู ุงูุฏููุงุฆูุฑู ุจููููู ุงูุฑููุชูุจู ุงููู
ูุฎูุชูููููุฉู ููุฃูู
ููููู ุญูู
ููููู ุนูููู ุฃูุนูููุงููุง ุฃููู ุนูููู ุฃูุฏูููุงููุง ููููููุญููู ุจูู
ูุณูุฃูููุฉู ุงููุญูุฑูุงู
ู ู
ูุง ู
ูุนูููุง ููู ู
ูุฐูููุจู ู
ูุงูููู ู
ููู ุงููุฃูููููุงุธู ููุญููู ุฃูููุจูุชููุฉู ููุงููุจูุงุฆููู ููุญูุจูููู ุนูููู ุบูุงุฑูุจูู ูููู ููุญูู
ููู ุนูููู ุฃูุนูููู ุงูุฑููุชูุจู ูููููู ุงูุซููููุงุซู ุฃูู
ู ููุง ููู
ูููููุง ู
ูุณูุฃูููุฉู ุงูุชููููู
ููู
ู ููู ูููููู ุชูุนูุงููู {ููุชูููู
ููู
ููุง ุตูุนููุฏูุง} [ุงููุณุงุก: 43] ูููููููููู ุตูุนููุฏูุง ู
ูุฏูููููููู ุฃูู
ูุฑู ูููููููู ููู
ููููู ุญูู
ููููู ุนูููู ุฃูุฏูููู ุงูุฑููุชูุจู ูููููู ู
ูุทููููู ู
ูุง ููุณูู
ููู ุตูุนููุฏูุง ุชูุฑูุงุจูุง ููุงูู ุฃููู ุบูููุฑููู ู
ููู ุฌูููุณู ุงููุฃูุฑูุถู ูููููู ู
ูุฐูููุจู ู
ูุงูููู - ุฑูุญูู
ููู ุงูููููู - ุฃููู ุฃูุนูููู ุฑูุชูุจู ุงูุตููุนููุฏู ูููููู ุงูุชููุฑูุงุจู ูููููู ู
ูุฐูููุจู ุงูุดููุงููุนูููู ููููุฐููู ุงููู
ูุณูุฃูููุฉู ุฃูููุถูุง ุญูุณูููุฉู ุงูุชููุฎูุฑููุฌู ุนูููู ููุฐููู ุงููููุงุนูุฏูุฉู ู
ููู ุบูููุฑู ู
ูุนูุงุฑูุถู ู
ููู ุฌูููุฉู ุงููููููุธู ููููุง ุงููู
ูุนูููู. " + "ููู
ูููููุง ูููููููู - ุนููููููู ุงูุณููููุงู
ู - ยซุฅุฐูุง ุณูู
ูุนูุชูู
ู ุงููู
ูุคูุฐูููู ููุคูุฐูููู ููููููููุง ู
ูุซููู ู
ูุง ูููููููยป ููุงููู
ูุซููููููุฉู ููู ููุณูุงูู ุงููุนูุฑูุจู ุชูุตูุฏููู ุจููููู ุงูุดููููุฆููููู ุจูุฃูููู ููุตููู ููุงูู ู
ููู ุบูููุฑู ุดูู
ูููู ููุฅูุฐูุง ููููุช: ุฒูููุฏู ู
ูุซููู ุงููุฃูุณูุฏู ููููู ููู ุฐููููู ุงูุดููุฌูุงุนูุฉู ุฏูููู ุจููููููุฉู ุงููุฃูููุตูุงูู ููููุฐููููู ุฒูููุฏู ู
ูุซููู ุนูู
ูุฑูู ููุตูุฏููู ุฐููููู ุญููููููุฉู ุจูู
ูุดูุงุฑูููุชูููู
ูุง ููู ุตูููุฉู ููุงุญูุฏูุฉู ููุงููู
ูุซููู ุงููู
ูุฐููููุฑู ููู ุงููุฃูุฐูุงูู ุฅูู ุญูู
ููู ุนูููู ุฃูุนูููู ุงูุฑููุชูุจู ููุงูู: ู
ูุซููู ู
ูุง ููููููู ุฅููู ุขุฎูุฑู ุงููุฃูุฐูุงูู ุฃููู ุนูููู ุฃูุฏูููู ุงูุฑููุชูุจู ููููู ุงูุชููุดููููุฏู ุฎูุงุตููุฉู ูููููู ู
ูุดููููุฑู ู
ูุฐูููุจู ู
ูุงูููู ููููุฐููู ุณูุชูู ู
ูุณูุงุฆููู ุชูููุจููููู ุนูููู ุตูุญููุฉู ุงูุชููุฎูุฑููุฌู ุนูููู ููุฐููู ุงููููุงุนูุฏูุฉู ููุงููู
ูุณูุงุฆููู ุงูุณููุงุจูููุฉู ุชูููุจููููู ุนูููู ุงูุชููุฎูุฑููุฌู ุงููููุงุณูุฏู ุนูููููููุง ููุฃูููู ุงููุฃูููููู ู
ููู ุจูุงุจู ุงููุฃูุฌูุฒูุงุกู ููููุฐููู ู
ููู ุจูุงุจู ุงููุฌูุฒูุฆููููุงุชู ููููุฏู ุธูููุฑู ููู ุงููููุฑููู ุจูููููููู
ูุง ููุงูุตููุญููุญู ู
ููู ุงููููุงุณูุฏู."; String testStringWithoutTashkeel = "ููู
ูุฏ ุฑุฃููุง ู
ู ุฑุฌุงู ูุฏููุฉ ... ูุจุงุฏูุง ุฌู
ูุนุง ู
ุณุฑุนูู ูุฒุงููุง"; String testStringWithoutTashkeel2 = "ุฎูุงู ูุตุญ ุชุฎุฑูุฌู ุนูู ูุฐู ุงููุงุนุฏุฉ ูุฃู ูููู ุญุฑุงู
ู
ุทูู ุฏุงู ุนูู ู
ุทูู ุงูุชุญุฑูู
ุงูุฏุงุฆุฑ ุจูู ุงูุฑุชุจ ุงูู
ุฎุชููุฉ ูุฃู
ูู ุญู
ูู ุนูู ุฃุนูุงูุง ุฃู ุนูู ุฃุฏูุงูุง ูููุญู ุจู
ุณุฃูุฉ ุงูุญุฑุงู
ู
ุง ู
ุนูุง ูู ู
ุฐูุจ ู
ุงูู ู
ู ุงูุฃููุงุธ ูุญู ุฃูุจุชุฉ ูุงูุจุงุฆู ูุญุจูู ุนูู ุบุงุฑุจู ูู ูุญู
ู ุนูู ุฃุนูู ุงูุฑุชุจ ููู ุงูุซูุงุซ ุฃู
ูุง ูู
ููุง ู
ุณุฃูุฉ ุงูุชูู
ู
ูู ูููู ุชุนุงูู {ูุชูู
ู
ูุง ุตุนูุฏุง} [ุงููุณุงุก: 43] ููููู ุตุนูุฏุง ู
ุฏูููู ุฃู
ุฑ ููู ูู
ูู ุญู
ูู ุนูู ุฃุฏูู ุงูุฑุชุจ ููู ู
ุทูู ู
ุง ูุณู
ู ุตุนูุฏุง ุชุฑุงุจุง ูุงู ุฃู ุบูุฑู ู
ู ุฌูุณ ุงูุฃุฑุถ ููู ู
ุฐูุจ ู
ุงูู - ุฑุญู
ู ุงููู - ุฃู ุฃุนูู ุฑุชุจ ุงูุตุนูุฏ ููู ุงูุชุฑุงุจ ููู ู
ุฐูุจ ุงูุดุงูุนู ููุฐู ุงูู
ุณุฃูุฉ ุฃูุถุง ุญุณูุฉ ุงูุชุฎุฑูุฌ ุนูู ูุฐู ุงููุงุนุฏุฉ ู
ู ุบูุฑ ู
ุนุงุฑุถ ู
ู ุฌูุฉ ุงูููุธ ููุง ุงูู
ุนูู. " + "ูู
ููุง ูููู - ุนููู ุงูุณูุงู
- ยซุฅุฐุง ุณู
ุนุชู
ุงูู
ุคุฐู ูุคุฐู ูููููุง ู
ุซู ู
ุง ููููยป ูุงูู
ุซููุฉ ูู ูุณุงู ุงูุนุฑุจ ุชุตุฏู ุจูู ุงูุดูุฆูู ุจุฃู ูุตู ูุงู ู
ู ุบูุฑ ุดู
ูู ูุฅุฐุง ููุช: ุฒูุฏ ู
ุซู ุงูุฃุณุฏ ููู ูู ุฐูู ุงูุดุฌุงุนุฉ ุฏูู ุจููุฉ ุงูุฃูุตุงู ููุฐูู ุฒูุฏ ู
ุซู ุนู
ุฑู ูุตุฏู ุฐูู ุญูููุฉ ุจู
ุดุงุฑูุชูู
ุง ูู ุตูุฉ ูุงุญุฏุฉ ูุงูู
ุซู ุงูู
ุฐููุฑ ูู ุงูุฃุฐุงู ุฅู ุญู
ู ุนูู ุฃุนูู ุงูุฑุชุจ ูุงู: ู
ุซู ู
ุง ูููู ุฅูู ุขุฎุฑ ุงูุฃุฐุงู ุฃู ุนูู ุฃุฏูู ุงูุฑุชุจ ููู ุงูุชุดูุฏ ุฎุงุตุฉ ููู ู
ุดููุฑ ู
ุฐูุจ ู
ุงูู ููุฐู ุณุช ู
ุณุงุฆู ุชูุจูู ุนูู ุตุญุฉ ุงูุชุฎุฑูุฌ ุนูู ูุฐู ุงููุงุนุฏุฉ ูุงูู
ุณุงุฆู ุงูุณุงุจูุฉ ุชูุจูู ุนูู ุงูุชุฎุฑูุฌ ุงููุงุณุฏ ุนูููุง ูุฃู ุงูุฃูู ู
ู ุจุงุจ ุงูุฃุฌุฒุงุก ููุฐู ู
ู ุจุงุจ ุงูุฌุฒุฆูุงุช ููุฏ ุธูุฑ ูู ุงููุฑู ุจูููู
ุง ูุงูุตุญูุญ ู
ู ุงููุงุณุฏ."; assertEquals(testStringWithoutTashkeel, ArabicUtilities.cleanTashkeel(testStringWithTashkeel)); assertEquals(testStringWithoutTashkeel2, ArabicUtilities.cleanTashkeel(testStringWithTashkeel2)); } |
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; } | @Test public void cleanTextForSearchingWthStingBuilder() throws Exception { } |
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; } | @Test public void startsWithDefiniteArticle() throws Exception { assertEquals(ArabicUtilities.startsWithDefiniteArticle("ุงูุจุฎุงุฑู"), true); assertEquals(ArabicUtilities.startsWithDefiniteArticle("ุงููุจู"), true); assertEquals(ArabicUtilities.startsWithDefiniteArticle("ุงููุญู
"), true); } |
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; } | @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")); } |
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); } | @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); } |
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); } | @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"))); } |
RedGBuilder { public T build() { final T inst = instance; instance = null; return inst; } @SuppressWarnings("unchecked") RedGBuilder(); RedGBuilder(final Class<T> clazz); RedGBuilder<T> withDefaultValueStrategy(final DefaultValueStrategy strategy); RedGBuilder<T> withPreparedStatementParameterSetter(final PreparedStatementParameterSetter setter); RedGBuilder<T> withSqlValuesFormatter(final SQLValuesFormatter formatter); RedGBuilder<T> withDummyFactory(final DummyFactory dummyFactory); T build(); } | @Test public void 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); } |
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); } | @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); } |
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); } | @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); } |
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); } | @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); } |
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); } | @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); } |
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); } | @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\""); } |
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); } | @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"); } |
TableModelExtractor { public static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { LOG.debug("Starting table model extraction from compiled class files..."); final List<TableModel> results = new ArrayList<>(); final String packageNameAsFolders = packageName.replace(".", "/"); final Path codeFilePath = classDir.resolve(packageNameAsFolders); LOG.debug("Folder with class files is {}", codeFilePath.toAbsolutePath().toString()); final List<String> classNames = Files.list(codeFilePath) .filter(path -> path.getFileName().toString().matches(classPrefix + ".+\\.class")) .map(classDir::relativize) .map(Path::toString) .map(name -> name.replaceFirst("\\.class$", "")) .map(name -> name.replaceAll("(/|\\\\)", ".")) .collect(Collectors.toList()); LOG.debug("Found following class files:\n{}", classNames.stream().collect(Collectors.joining("\n"))); LOG.debug("Loading all found classes..."); final ClassLoader cl = new URLClassLoader(new URL[]{classDir.toUri().toURL()}); for (String className : classNames) { LOG.debug("Loading class {}.", className); final Class cls = cl.loadClass(className); final Method m = cls.getDeclaredMethod("getTableModel"); results.add((TableModel) m.invoke(null)); LOG.debug("Successfully extracted table model."); } return results; } static List<TableModel> extractTableModelsFromSourceCode(final Path srcDir, final String packageName, final String classPrefix); static List<TableModel> extractTableModelFromClasses(final Path classDir, final String packageName, final String classPrefix); } | @Test @Ignore public void extractTableModelFromClasses() throws Exception { TableModelExtractor.extractTableModelFromClasses(Paths.get("D:\\redg\\redg-playground\\target\\test-classes"), "com.btc.redg.generated", "G"); } |
XmlFileDataTypeProvider implements DataTypeProvider { String getDataTypeBySqlType(final Column column) { if (typeMappings.getDefaultTypeMappings() == null) { return null; } List<String> variants = DataTypePrecisionHelper.getDataTypeWithAllPrecisionVariants(column); return variants.stream() .map(variant -> typeMappings.getDefaultTypeMappings().stream() .filter(dtm -> dtm.getSqlType() .trim() .replaceAll("\\s+", " ") .replaceAll("\\s+(?=[(),])", "") .replaceAll("(?<=[(),])\\s+", "") .toUpperCase().equals(variant.toUpperCase())) .findFirst().orElse(null)) .filter(Objects::nonNull) .map(DefaultTypeMapping::getJavaType) .findFirst().orElse(null); } XmlFileDataTypeProvider(Reader xmlReader, DataTypeProvider fallbackDataTypeProvider); XmlFileDataTypeProvider(TypeMappings typeMappings, DataTypeProvider fallbackDataTypeProvider); @Override String getCanonicalDataTypeName(final Column column); } | @Test public void 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)); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.