method2testcases
stringlengths 118
3.08k
|
---|
### Question:
PlaceholderRetriever { public static boolean hasAnnotation(final VariableElement element) { return getAnnotation(element) != null; } private PlaceholderRetriever(); static AnnotationMirror getAnnotation(final VariableElement element); static boolean hasAnnotation(final VariableElement element); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testHasAnnotation_nullSupplied() { PlaceholderRetriever.hasAnnotation(null); } |
### Question:
CompanionNamer { public static String getCompanionNameFor(final TypeElement targetClass) { return getParentChain(targetClass) + "_SpyglassCompanion"; } static String getCompanionNameFor(final TypeElement targetClass); }### Answer:
@Test public void testGetCompanionNameFor_topLevelClass() { final TypeElement element = avatarRule.getElementWithUniqueId("top level"); final String companionName = CompanionNamer.getCompanionNameFor(element); final String expectedName = "TestCompanionNamerData_SpyglassCompanion"; assertThat(companionName, is(expectedName)); }
@Test public void testGetCompanionNameFor_classNestedByOneLevel() { final TypeElement element = avatarRule.getElementWithUniqueId("nested one level"); final String companionName = CompanionNamer.getCompanionNameFor(element); final String expectedName = "TestCompanionNamerData_ClassA_SpyglassCompanion"; assertThat(companionName, is(expectedName)); }
@Test public void testGetCompanionNameFor_classNestedByMultipleLevels() { final TypeElement element = avatarRule.getElementWithUniqueId("nested multiple levels"); final String companionName = CompanionNamer.getCompanionNameFor(element); final String expectedName = "TestCompanionNamerData_ClassA_ClassB_ClassC_ClassD_SpyglassCompanion"; assertThat(companionName, is(expectedName)); } |
### Question:
AnnotationMirrorHelper { public static AnnotationMirror getAnnotationMirror( final Element element, final Class<? extends Annotation> annotationClass) { checkNotNull(element, "Argument \'element\' cannot be null."); checkNotNull(annotationClass, "Argument \'annotationClass\' cannot be null."); for (final AnnotationMirror mirror : element.getAnnotationMirrors()) { if (mirror.getAnnotationType().toString().equals(annotationClass.getName())) { return mirror; } } return null; } @Inject AnnotationMirrorHelper(final Elements elementHelper); static AnnotationMirror getAnnotationMirror(
final Element element,
final Class<? extends Annotation> annotationClass); AnnotationValue getValueIgnoringDefaults(final AnnotationMirror mirror, final String valueKey); AnnotationValue getValueUsingDefaults(final AnnotationMirror mirror, final String valueKey); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetAnnotationMirror_nullElement() { AnnotationMirrorHelper.getAnnotationMirror(null, Annotation.class); }
@Test(expected = IllegalArgumentException.class) public void testGetAnnotationMirror_nullAnnotationClass() { AnnotationMirrorHelper.getAnnotationMirror(mock(Element.class), null); }
@Test public void testGetAnnotationMirror_annotationMissing() { final Element element = avatarRule.getElementWithUniqueId("get annotation mirror: without annotation"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, SomeAnnotationWithValue.class); assertThat(mirror, is(nullValue())); }
@Test public void testGetAnnotationMirror_annotationPresent() { final Element element = avatarRule.getElementWithUniqueId("get annotation mirror: with annotation"); final AnnotationMirror mirror = AnnotationMirrorHelper .getAnnotationMirror(element, SomeAnnotationWithValue.class); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(SomeAnnotationWithValue.class.getName())); } |
### Question:
AnnotationMirrorHelper { public AnnotationValue getValueUsingDefaults(final AnnotationMirror mirror, final String valueKey) { checkNotNull(mirror, "Argument \'mirror\' cannot be null."); checkNotNull(valueKey, "Argument \'valueKey\' cannot be null."); final Map<? extends ExecutableElement, ? extends AnnotationValue> values = elementHelper .getElementValuesWithDefaults(mirror); for (final ExecutableElement mapKey : values.keySet()) { if (mapKey.getSimpleName().toString().equals(valueKey)) { return values.get(mapKey); } } return null; } @Inject AnnotationMirrorHelper(final Elements elementHelper); static AnnotationMirror getAnnotationMirror(
final Element element,
final Class<? extends Annotation> annotationClass); AnnotationValue getValueIgnoringDefaults(final AnnotationMirror mirror, final String valueKey); AnnotationValue getValueUsingDefaults(final AnnotationMirror mirror, final String valueKey); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetValueUsingDefaults_nullAnnotationMirrorSupplied() { helper.getValueUsingDefaults(null, ""); }
@Test(expected = IllegalArgumentException.class) public void testGetValueUsingDefaults_nullValueKeySupplied() { helper.getValueUsingDefaults(mock(AnnotationMirror.class), null); } |
### Question:
DefaultRetriever { public static boolean hasAnnotation(final ExecutableElement element) { return getAnnotation(element) != null; } private DefaultRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testHasAnnotation_nullSupplied() { DefaultRetriever.hasAnnotation(null); } |
### Question:
UnconditionalHandlerRetriever { public static boolean hasAnnotation(final ExecutableElement element) { return getAnnotation(element) != null; } private UnconditionalHandlerRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testHasAnnotation_nullSupplied() { UnconditionalHandlerRetriever.hasAnnotation(null); } |
### Question:
ConditionalHandlerRetriever { public static AnnotationMirror getAnnotation(final ExecutableElement element) { checkNotNull(element, "Argument \'element\' cannot be null."); for (final Class<? extends Annotation> annotationClass : AnnotationRegistry.CONDITIONAL_HANDLERS) { final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, annotationClass); if (mirror != null) { return mirror; } } return null; } private ConditionalHandlerRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetAnnotation_nullSupplied() { ConditionalHandlerRetriever.getAnnotation(null); }
@Test public void testGetAnnotation_specificBooleanHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("specific boolean"); final AnnotationMirror mirror = ConditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(SpecificBooleanHandler.class.getName())); }
@Test public void testGetAnnotation_specificEnumHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("specific enum"); final AnnotationMirror mirror = ConditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(SpecificEnumHandler.class.getName())); }
@Test public void testGetAnnotation_specificFlagHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("specific flag"); final AnnotationMirror mirror = ConditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(SpecificFlagHandler.class.getName())); }
@Test public void testGetAnnotation_noConditionalHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("no call handler annotation"); final AnnotationMirror mirror = ConditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(nullValue())); } |
### Question:
ConditionalHandlerRetriever { public static boolean hasAnnotation(final ExecutableElement element) { return getAnnotation(element) != null; } private ConditionalHandlerRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testHasAnnotation_nullSupplied() { ConditionalHandlerRetriever.hasAnnotation(null); } |
### Question:
TypeElementWrapper { @Override public int hashCode() { return element.getQualifiedName().toString().hashCode(); } TypeElementWrapper(final TypeElement element); TypeElement unwrap(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testHashcode_checkContractIsSatisfied() { final TypeElementWrapper wrapper1A = new TypeElementWrapper(class1); final TypeElementWrapper wrapper1B = new TypeElementWrapper(class1); for (int i = 0; i < 1000; i++) { assertThat(wrapper1A.hashCode(), is(wrapper1B.hashCode())); } } |
### Question:
TypeElementWrapper { public TypeElement unwrap() { return element; } TypeElementWrapper(final TypeElement element); TypeElement unwrap(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testUnwrap() { final TypeElementWrapper wrapper = new TypeElementWrapper(class1); assertThat(wrapper.unwrap() == class1, is(true)); } |
### Question:
SpecificValueIsAvailableMethodGenerator { public MethodSpec generateFor(final AnnotationMirror conditionalHandlerAnnotation) { checkNotNull(conditionalHandlerAnnotation, "Argument \'conditionalHandlerAnnotation\' cannot be null."); final String annotationClassName = conditionalHandlerAnnotation.getAnnotationType().toString(); if (!methodBodySuppliers.containsKey(annotationClassName)) { throw new IllegalArgumentException("Argument \'conditionalHandlerAnnotation\' is not a call handler annotation."); } return MethodSpec .methodBuilder("specificValueIsAvailable") .returns(Boolean.class) .addCode(methodBodySuppliers.get(annotationClassName).apply(conditionalHandlerAnnotation)) .build(); } @Inject SpecificValueIsAvailableMethodGenerator(final AnnotationMirrorHelper annotationMirrorHelper); MethodSpec generateFor(final AnnotationMirror conditionalHandlerAnnotation); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullSupplied() { generator.generateFor(null); }
@Test public void testGenerateFor_specificBooleanHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("specific boolean"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, SpecificBooleanHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_specificEnumHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("specific enum"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, SpecificEnumHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_specificFlagHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("specific flag"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, SpecificFlagHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); } |
### Question:
NoopMetricsSystemFactory implements MetricsSystemFactory { @Override public NoopMetricsSystem create(MetricsSystemConfiguration<?> config) { return NoopMetricsSystem.getInstance(); } @Override NoopMetricsSystem create(MetricsSystemConfiguration<?> config); }### Answer:
@Test public void testSingleton() { NoopMetricsSystemFactory factory = new NoopMetricsSystemFactory(); NoopMetricsSystemConfiguration config = NoopMetricsSystemConfiguration.getInstance(); assertTrue("The factory should only return one NoopMetricsSystem instance", factory.create(config) == factory.create(config)); } |
### Question:
NoopMetricsSystem implements MetricsSystem { public static NoopMetricsSystem getInstance() { return NOOP_METRICS; } private NoopMetricsSystem(); static NoopMetricsSystem getInstance(); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); }### Answer:
@Test public void testSingleton() { assertTrue("Should be a singleton", NoopMetricsSystem.getInstance() == NoopMetricsSystem.getInstance()); } |
### Question:
ConnectionConfigImpl implements ConnectionConfig { public File truststore() { String filename = BuiltInConnectionProperty.TRUSTSTORE.wrap(properties).getString(); if (null == filename) { return null; } return new File(filename); } ConnectionConfigImpl(Properties properties); String schema(); String timeZone(); Service.Factory factory(); String url(); String serialization(); String authentication(); String avaticaUser(); String avaticaPassword(); AvaticaHttpClientFactory httpClientFactory(); String httpClientClass(); String kerberosPrincipal(); File kerberosKeytab(); File truststore(); String truststorePassword(); File keystore(); String keystorePassword(); String keyPassword(); HostnameVerification hostnameVerification(); static Map<ConnectionProperty, String> parse(Properties properties,
Map<String, ? extends ConnectionProperty> nameToProps); static Converter<E> enumConverter(
final Class<E> enumClass); static Converter<T> pluginConverter(final Class<T> pluginClass,
final T defaultInstance); static final Converter<Boolean> BOOLEAN_CONVERTER; static final Converter<Number> NUMBER_CONVERTER; static final Converter<String> IDENTITY_CONVERTER; }### Answer:
@Test public void testTrustStore() { final String trustStore = "/my/truststore.jks"; final String windowsTrustStore = "my\\truststore.jks"; final String pw = "supremelysecret"; Properties props = new Properties(); props.setProperty(BuiltInConnectionProperty.TRUSTSTORE.name(), trustStore); props.setProperty(BuiltInConnectionProperty.TRUSTSTORE_PASSWORD.name(), pw); ConnectionConfigImpl config = new ConnectionConfigImpl(props); assertThat(config.truststore().getAbsolutePath(), File.separatorChar == '/' ? is(trustStore) : is(Paths.get(".").toAbsolutePath().getRoot() + windowsTrustStore)); assertThat(config.truststorePassword(), is(pw)); } |
### Question:
UnsynchronizedBuffer extends OutputStream { public static int nextArraySize(int i) { if (i < 0) { throw new IllegalArgumentException(); } if (i > (1 << 30)) { return Integer.MAX_VALUE; } if (i == 0) { return 1; } int ret = i; ret--; ret |= ret >> 1; ret |= ret >> 2; ret |= ret >> 4; ret |= ret >> 8; ret |= ret >> 16; ret++; return ret; } UnsynchronizedBuffer(); UnsynchronizedBuffer(int initialCapacity); void write(byte[] bytes, int off, int length); @Override void write(int b); byte[] toArray(); void reset(); int getOffset(); long getSize(); static int nextArraySize(int i); }### Answer:
@Test public void testArrayResizing() { int size = 64; int expected = 128; for (int i = 0; i < 10; i++) { int next = UnsynchronizedBuffer.nextArraySize(size + 1); assertEquals(expected, next); size = next; expected *= 2; } } |
### Question:
StructImpl implements Struct { @Override public Object[] getAttributes() throws SQLException { return list.toArray(); } StructImpl(List list); @Override String toString(); @Override String getSQLTypeName(); @Override Object[] getAttributes(); @Override Object[] getAttributes(Map<String, Class<?>> map); }### Answer:
@Test public void testStructAccessor() throws Exception { List<List<Object>> rows = new ArrayList<>(); for (Object o : columnInputBundle.inputValues) { rows.add(Collections.singletonList(o)); } try (Cursor cursor = new ListIteratorCursor(rows.iterator())) { List<Accessor> accessors = cursor.createAccessors( Collections.singletonList(columnInputBundle.metaData), Unsafe.localCalendar(), null); Accessor accessor = accessors.get(0); int i = 0; while (cursor.next()) { Struct s = accessor.getObject(Struct.class); Object[] expectedStructAttributes = columnInputBundle.expectedValues.get(i).getAttributes(); Object[] actualStructAttributes = s.getAttributes(); assertArrayEquals(expectedStructAttributes, actualStructAttributes); i++; } } } |
### Question:
AvaticaCommonsHttpClientImpl implements AvaticaHttpClient,
UsernamePasswordAuthenticateable, TrustStoreConfigurable,
KeyStoreConfigurable, HostnameVerificationConfigurable { HostnameVerifier getHostnameVerifier(HostnameVerification verification) { if (verification == null) { verification = HostnameVerification.STRICT; } switch (verification) { case STRICT: return SSLConnectionSocketFactory.getDefaultHostnameVerifier(); case NONE: return NoopHostnameVerifier.INSTANCE; default: throw new IllegalArgumentException("Unhandled HostnameVerification: " + hostnameVerification); } } AvaticaCommonsHttpClientImpl(URL url); @Override byte[] send(byte[] request); @Override void setUsernamePassword(AuthenticationType authType, String username,
String password); @Override void setTrustStore(File truststore, String password); @Override void setKeyStore(File keystore, String keystorepassword, String keypassword); @Override void setHostnameVerification(HostnameVerification verification); }### Answer:
@Test public void testHostnameVerification() throws Exception { AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class); when(client.getHostnameVerifier(nullable(HostnameVerification.class))) .thenCallRealMethod(); HostnameVerifier actualVerifier = client.getHostnameVerifier(null); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof DefaultHostnameVerifier); actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof DefaultHostnameVerifier); actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof NoopHostnameVerifier); } |
### Question:
KerberosConnection { Entry<RenewalTask, Thread> createRenewalThread(LoginContext originalContext, Subject originalSubject, long renewalPeriod) { RenewalTask task = new RenewalTask(this, originalContext, originalSubject, jaasConf, renewalPeriod); Thread t = new Thread(task); t.setDaemon(true); t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOG.error("Uncaught exception from Kerberos credential renewal thread", e); } }); t.setName(RENEWAL_THREAD_NAME); return new AbstractMap.SimpleEntry<>(task, t); } KerberosConnection(String principal, File keytab); synchronized Subject getSubject(); synchronized void login(); void stopRenewalThread(); static boolean isIbmJava(); static String getKrb5LoginModuleName(); static final float PERCENT_OF_LIFETIME_TO_RENEW; static final long RENEWAL_PERIOD; }### Answer:
@Test public void testThreadConfiguration() { KerberosConnection krbUtil = new KerberosConnection("foo", new File("/bar.keytab")); Subject subject = new Subject(); LoginContext context = Mockito.mock(LoginContext.class); Entry<RenewalTask, Thread> entry = krbUtil.createRenewalThread(context, subject, 10); assertNotNull("RenewalTask should not be null", entry.getKey()); Thread t = entry.getValue(); assertTrue("Thread name should contain 'Avatica', but is '" + t.getName() + "'", t.getName().contains("Avatica")); assertTrue(t.isDaemon()); assertNotNull(t.getUncaughtExceptionHandler()); } |
### Question:
DropwizardGauge implements Gauge<T> { @Override public T getValue() { return gauge.getValue(); } DropwizardGauge(org.apache.calcite.avatica.metrics.Gauge<T> gauge); @Override T getValue(); }### Answer:
@Test public void test() { SimpleGauge gauge = new SimpleGauge(); DropwizardGauge<Long> dwGauge = new DropwizardGauge<>(gauge); assertEquals(gauge.getValue(), dwGauge.getValue()); gauge.setValue(1000L); assertEquals(gauge.getValue(), dwGauge.getValue()); } |
### Question:
DropwizardMetricsSystemFactory implements MetricsSystemFactory { @Override public DropwizardMetricsSystem create(MetricsSystemConfiguration<?> config) { if (config instanceof DropwizardMetricsSystemConfiguration) { DropwizardMetricsSystemConfiguration typedConfig = (DropwizardMetricsSystemConfiguration) config; return new DropwizardMetricsSystem(typedConfig.get()); } throw new IllegalStateException("Expected instance of " + DropwizardMetricsSystemConfiguration.class.getName() + " but got " + (null == config ? "null" : config.getClass().getName())); } @Override DropwizardMetricsSystem create(MetricsSystemConfiguration<?> config); }### Answer:
@Test(expected = IllegalStateException.class) public void testNullConfigurationFails() { factory.create(null); }
@Test(expected = IllegalStateException.class) public void testUnhandledConfigurationType() { factory.create(NoopMetricsSystemConfiguration.getInstance()); }
@Test public void testHandledConfigurationType() { DropwizardMetricsSystem metrics = factory.create(new DropwizardMetricsSystemConfiguration(new MetricRegistry())); assertNotNull("Expected DropwizardMetricsSystem to be non-null", metrics); } |
### Question:
DropwizardMeter implements org.apache.calcite.avatica.metrics.Meter { @Override public void mark() { this.meter.mark(); } DropwizardMeter(Meter meter); @Override void mark(); @Override void mark(long count); }### Answer:
@Test public void test() { DropwizardMeter dwMeter = new DropwizardMeter(this.meter); dwMeter.mark(); dwMeter.mark(10L); dwMeter.mark(); dwMeter.mark(); Mockito.verify(meter, Mockito.times(3)).mark(); Mockito.verify(meter).mark(10L); } |
### Question:
DropwizardTimer implements org.apache.calcite.avatica.metrics.Timer { @Override public DropwizardContext start() { return new DropwizardContext(timer.time()); } DropwizardTimer(Timer timer); @Override DropwizardContext start(); }### Answer:
@Test public void test() { DropwizardTimer dwTimer = new DropwizardTimer(timer); Mockito.when(timer.time()).thenReturn(context); DropwizardContext dwContext = dwTimer.start(); dwContext.close(); Mockito.verify(timer).time(); Mockito.verify(context).stop(); } |
### Question:
DropwizardMetricsSystem implements MetricsSystem { @Override public <T> void register(String name, Gauge<T> gauge) { registry.register(name, new DropwizardGauge<T>(gauge)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); }### Answer:
@Test public void testGauge() { final long gaugeValue = 42L; final String name = "gauge"; metrics.register(name, new Gauge<Long>() { @Override public Long getValue() { return gaugeValue; } }); verify(mockRegistry, times(1)).register(eq(name), any(com.codahale.metrics.Gauge.class)); } |
### Question:
DropwizardMetricsSystem implements MetricsSystem { @Override public Meter getMeter(String name) { return new DropwizardMeter(registry.meter(name)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); }### Answer:
@Test public void testMeter() { final String name = "meter"; final com.codahale.metrics.Meter mockMeter = mock(com.codahale.metrics.Meter.class); when(mockRegistry.meter(name)).thenReturn(mockMeter); Meter meter = metrics.getMeter(name); final long count = 5; meter.mark(count); verify(mockMeter, times(1)).mark(count); meter.mark(); verify(mockMeter, times(1)).mark(); } |
### Question:
DropwizardMetricsSystem implements MetricsSystem { @Override public Histogram getHistogram(String name) { return new DropwizardHistogram(registry.histogram(name)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); }### Answer:
@Test public void testHistogram() { final String name = "histogram"; final com.codahale.metrics.Histogram mockHistogram = mock(com.codahale.metrics.Histogram.class); when(mockRegistry.histogram(name)).thenReturn(mockHistogram); Histogram histogram = metrics.getHistogram(name); long[] long_values = new long[] {1L, 5L, 15L, 30L, 60L}; for (long value : long_values) { histogram.update(value); } for (long value : long_values) { verify(mockHistogram).update(value); } int[] int_values = new int[] {2, 6, 16, 31, 61}; for (int value : int_values) { histogram.update(value); } for (int value : int_values) { verify(mockHistogram).update(value); } } |
### Question:
DropwizardMetricsSystem implements MetricsSystem { @Override public Counter getCounter(String name) { return new DropwizardCounter(registry.counter(name)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); }### Answer:
@Test public void testCounter() { final String name = "counter"; final com.codahale.metrics.Counter mockCounter = mock(com.codahale.metrics.Counter.class); when(mockRegistry.counter(name)).thenReturn(mockCounter); Counter counter = metrics.getCounter(name); long[] updates = new long[] {1L, 5L, -2L, 4L, -8L, 0}; for (long update : updates) { if (update < 0) { counter.decrement(Math.abs(update)); } else { counter.increment(update); } } for (long update : updates) { if (update < 0) { verify(mockCounter).dec(Math.abs(update)); } else { verify(mockCounter).inc(update); } } int numSingleUpdates = 3; for (int i = 0; i < numSingleUpdates; i++) { counter.increment(); counter.decrement(); } verify(mockCounter, times(numSingleUpdates)).inc(); verify(mockCounter, times(numSingleUpdates)).dec(); } |
### Question:
DropwizardMetricsSystem implements MetricsSystem { @Override public Timer getTimer(String name) { return new DropwizardTimer(registry.timer(name)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); }### Answer:
@Test public void testTimer() { final String name = "timer"; final com.codahale.metrics.Timer mockTimer = mock(com.codahale.metrics.Timer.class); final com.codahale.metrics.Timer.Context mockContext = mock(com.codahale.metrics.Timer.Context.class); when(mockRegistry.timer(name)).thenReturn(mockTimer); when(mockTimer.time()).thenReturn(mockContext); Timer timer = metrics.getTimer(name); Context context = timer.start(); context.close(); verify(mockTimer).time(); verify(mockContext).stop(); } |
### Question:
DropwizardHistogram implements org.apache.calcite.avatica.metrics.Histogram { @Override public void update(int value) { histogram.update(value); } DropwizardHistogram(Histogram histogram); @Override void update(int value); @Override void update(long value); }### Answer:
@Test public void test() { DropwizardHistogram dwHistogram = new DropwizardHistogram(histogram); dwHistogram.update(10); dwHistogram.update(100L); Mockito.verify(histogram).update(10); Mockito.verify(histogram).update(100L); } |
### Question:
HandlerFactory { public AvaticaHandler getHandler(Service service, Driver.Serialization serialization) { return getHandler(service, serialization, NoopMetricsSystemConfiguration.getInstance()); } AvaticaHandler getHandler(Service service, Driver.Serialization serialization); AvaticaHandler getHandler(Service service, Driver.Serialization serialization,
AvaticaServerConfiguration serverConfig); AvaticaHandler getHandler(Service service, Driver.Serialization serialization,
MetricsSystemConfiguration<?> metricsConfig); AvaticaHandler getHandler(Service service, Driver.Serialization serialization,
MetricsSystemConfiguration<?> metricsConfig, AvaticaServerConfiguration serverConfig); }### Answer:
@Test public void testJson() { Handler handler = factory.getHandler(service, Serialization.JSON); assertTrue("Expected an implementation of the AvaticaHandler, " + "but got " + handler.getClass(), handler instanceof AvaticaJsonHandler); }
@Test public void testProtobuf() { Handler handler = factory.getHandler(service, Serialization.PROTOBUF); assertTrue("Expected an implementation of the AvaticaProtobufHandler, " + "but got " + handler.getClass(), handler instanceof AvaticaProtobufHandler); } |
### Question:
UTF8Util { public static final long skipUntilEOF(InputStream in) throws IOException { return internalSkip(in, Long.MAX_VALUE).charsSkipped(); } private UTF8Util(); static final long skipUntilEOF(InputStream in); static final long skipFully(InputStream in, long charsToSkip); }### Answer:
@Test public void testSkipUntilEOFOnZeroLengthStream() throws IOException { TestCase.assertEquals(0, UTF8Util.skipUntilEOF(new LoopingAlphabetStream(0))); }
@Test public void testSkipUntilEOFOnShortStreamASCII() throws IOException { TestCase.assertEquals(5, UTF8Util.skipUntilEOF(new LoopingAlphabetStream(5))); }
@Test public void testSkipUntilEOFOnShortStreamCJK() throws IOException { final int charLength = 5; InputStream in = new ReaderToUTF8Stream( new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()), charLength, 0, TYPENAME, new CharStreamHeaderGenerator()); in.skip(HEADER_LENGTH); TestCase.assertEquals(charLength, UTF8Util.skipUntilEOF(in)); }
@Test public void testSkipUntilEOFOnLongStreamASCII() throws IOException { TestCase.assertEquals(127019, UTF8Util.skipUntilEOF( new LoopingAlphabetStream(127019))); }
@Test public void testSkipUntilEOFOnLongStreamCJK() throws IOException { final int charLength = 127019; InputStream in = new ReaderToUTF8Stream( new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()), charLength, 0, TYPENAME, new ClobStreamHeaderGenerator(true)); in.skip(HEADER_LENGTH); TestCase.assertEquals(charLength, UTF8Util.skipUntilEOF(in)); } |
### Question:
SpliceDoNotRetryIOException extends DoNotRetryIOException { @Override public String getMessage() { LOG.trace("getMessage"); return super.getMessage(); } SpliceDoNotRetryIOException(); SpliceDoNotRetryIOException(String message, Throwable cause); SpliceDoNotRetryIOException(String message); @Override String getMessage(); }### Answer:
@Test public void messageTrimmingTest() { Assert.assertEquals(msg1,exception.getMessage()); } |
### Question:
OrcMetadataReader implements MetadataReader { @VisibleForTesting public static Slice getMinSlice(String minimum) { if (minimum == null) { return null; } int index = firstSurrogateCharacter(minimum); if (index == -1) { return Slices.utf8Slice(minimum); } return Slices.utf8Slice(minimum.substring(0, index)); } @Override PostScript readPostScript(byte[] data, int offset, int length); @Override Metadata readMetadata(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override Footer readFooter(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override StripeFooter readStripeFooter(HiveWriterVersion hiveWriterVersion, List<OrcType> types, InputStream inputStream); @Override List<RowGroupIndex> readRowIndexes(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override List<HiveBloomFilter> readBloomFilterIndexes(InputStream inputStream); @VisibleForTesting static Slice getMaxSlice(String maximum); @VisibleForTesting static Slice getMinSlice(String minimum); }### Answer:
@Test public void testGetMinSlice() throws Exception { int startCodePoint = MIN_CODE_POINT; int endCodePoint = MAX_CODE_POINT; Slice minSlice = Slices.utf8Slice(""); for (int i = startCodePoint; i < endCodePoint; i++) { String value = new String(new int[] { i }, 0, 1); if (firstSurrogateCharacter(value) == -1) { assertEquals(getMinSlice(value), Slices.utf8Slice(value)); } else { assertEquals(getMinSlice(value), minSlice); } } String prefix = "apple"; for (int i = startCodePoint; i < endCodePoint; i++) { String value = prefix + new String(new int[] { i }, 0, 1); if (firstSurrogateCharacter(value) == -1) { assertEquals(getMinSlice(value), Slices.utf8Slice(value)); } else { assertEquals(getMinSlice(value), Slices.utf8Slice(prefix)); } } } |
### Question:
DoubleColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendDoubles(size,Double.parseDouble(value)); } DoubleColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); }### Answer:
@Test public void setPartitionValueTest() { DoubleColumnBlock doubleColumnBlock = new DoubleColumnBlock(null, DataTypes.DoubleType); doubleColumnBlock.setPartitionValue("1.23",1000); for (int i = 0; i< 1000; i++) { Assert.assertEquals(1.23d,doubleColumnBlock.getTestObject(i)); } } |
### Question:
IntegerColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendInts(size,Integer.parseInt(value)); } IntegerColumnBlock(DataType type); IntegerColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); }### Answer:
@Test public void setPartitionValueTest() { IntegerColumnBlock integerColumnBlock = new IntegerColumnBlock(null, DataTypes.IntegerType); integerColumnBlock.setPartitionValue("45",1000); for (int i = 0; i< 1000; i++) { Assert.assertEquals(45,integerColumnBlock.getTestObject(i)); } } |
### Question:
FloatColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendFloats(size,Float.parseFloat(value)); } FloatColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); }### Answer:
@Test public void setPartitionValueTest() { FloatColumnBlock longColumnBlock = new FloatColumnBlock(null, DataTypes.FloatType); longColumnBlock.setPartitionValue("45.23",1000); for (int i = 0; i< 1000; i++) { Assert.assertEquals(45.23f,longColumnBlock.getTestObject(i)); } } |
### Question:
ShortColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendShorts(size,Short.parseShort(value)); } ShortColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); }### Answer:
@Test public void setPartitionValueTest() { ShortColumnBlock shortColumnBlock = new ShortColumnBlock(null, DataTypes.ShortType); shortColumnBlock.setPartitionValue("5",1000); short value = 5; for (int i = 0; i< 1000; i++) { Assert.assertEquals(value,shortColumnBlock.getTestObject(i)); } } |
### Question:
LongColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendLongs(size,Long.parseLong(value)); } LongColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); }### Answer:
@Test public void setPartitionValueTest() { LongColumnBlock longColumnBlock = new LongColumnBlock(null, DataTypes.LongType); longColumnBlock.setPartitionValue("45",1000); for (int i = 0; i< 1000; i++) { Assert.assertEquals(45l,longColumnBlock.getTestObject(i)); } } |
### Question:
StringColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { try { columnVector = ColumnVector.allocate(size, DataTypes.IntegerType, MemoryMode.ON_HEAP); SliceDictionary dictionary = new SliceDictionary(new Slice[]{Slices.wrappedBuffer(value.getBytes("UTF-8"))}); columnVector.setDictionary(dictionary); columnVector.reserveDictionaryIds(size); columnVector.getDictionaryIds().appendInts(size,0); } catch (Exception e) { throw new RuntimeException(e); } } StringColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override Object getTestObject(int i); @Override void setPartitionValue(String value, int size); }### Answer:
@Test public void setPartitionValueTest() { StringColumnBlock stringColumnBlock = new StringColumnBlock(null, DataTypes.StringType); stringColumnBlock.setPartitionValue("foobar",1000); for (int i = 0; i< 1000; i++) { Assert.assertTrue("foobar".equals(stringColumnBlock.getTestObject(i))); } } |
### Question:
HdfsDirFile implements StorageFile { @Override public boolean deleteAll() { try { FileSystem fs = getFileSystem(); return fs.delete(new Path(path), true); } catch (IOException e) { LOG.error(String.format("An exception occurred while deleting the path '%s'.", path), e); return false; } } HdfsDirFile(String path); HdfsDirFile(String directoryName, String fileName); HdfsDirFile(HdfsDirFile directoryName, String fileName); FileSystem getFileSystem(); void setFileSystem(FileSystem fileSystem); @Override String[] list(); @Override boolean canWrite(); @Override boolean exists(); @Override boolean isDirectory(); @Override boolean delete(); @Override boolean deleteAll(); @Override String getPath(); @Override String getCanonicalPath(); @Override String getName(); @Override URL getURL(); @Override boolean createNewFile(); @Override boolean renameTo(StorageFile newName); @Override boolean mkdir(); @Override boolean mkdirs(); @Override long length(); @Override StorageFile getParentDir(); @Override boolean setReadOnly(); @Override OutputStream getOutputStream(); @Override OutputStream getOutputStream(boolean append); @Override InputStream getInputStream(); @Override int getExclusiveFileLock(); @Override void releaseExclusiveFileLock(); @Override StorageRandomAccessFile getRandomAccessFile(String mode); @Override void limitAccessToOwner(); }### Answer:
@Test public void testDeleteAll() throws IOException { HdfsDirFile dir = createHdfsDirFile("myfolder3"); Assert.assertTrue("Directory was not created", dir.mkdir()); HdfsDirFile file1 = createHdfsDirFile(dir, "able3.txt"); Assert.assertTrue("File was not created", file1.createNewFile()); HdfsDirFile file2 = createHdfsDirFile(dir, "baker3.txt"); Assert.assertTrue("File was not created", file2.createNewFile()); HdfsDirFile file3 = createHdfsDirFile(dir, "charlie3.txt"); Assert.assertTrue("File was not created", file3.createNewFile()); Assert.assertTrue("File was not deleted", dir.deleteAll()); } |
### Question:
SpliceDoNotRetryIOExceptionWrapping { public static Exception unwrap(SpliceDoNotRetryIOException spliceException) { String fullMessage = spliceException.getMessage(); int firstColonIndex = fullMessage.indexOf(COLON); int openBraceIndex = fullMessage.indexOf(OPEN_BRACE); String exceptionType; if (firstColonIndex < openBraceIndex) { exceptionType = fullMessage.substring(firstColonIndex + 1, openBraceIndex).trim(); } else { exceptionType = fullMessage.substring(0, openBraceIndex).trim(); } Class exceptionClass; try { exceptionClass = Class.forName(exceptionType); } catch (ClassNotFoundException e1) { exceptionClass = Exception.class; } String json = fullMessage.substring(openBraceIndex, fullMessage.indexOf(CLOSE_BRACE) + 1); return (Exception) GSON.fromJson(json, exceptionClass); } static Exception unwrap(SpliceDoNotRetryIOException spliceException); static SpliceDoNotRetryIOException wrap(StandardException se); }### Answer:
@Test public void testUnwrap() throws Exception { StandardException stdExceptionIn = StandardException.newException(SQLState.LANG_COLUMN_ID, "arg1", "arg2", "arg3", "arg4"); SpliceDoNotRetryIOException wrapped = SpliceDoNotRetryIOExceptionWrapping.wrap(stdExceptionIn); StandardException stdExceptionOut = (StandardException) SpliceDoNotRetryIOExceptionWrapping.unwrap(wrapped); assertEquals("Column Id", stdExceptionOut.getMessage()); assertArrayEquals(new String[]{"arg1", "arg2", "arg3", "arg4"}, stdExceptionOut.getArguments()); assertEquals("42Z42", stdExceptionOut.getSqlState()); } |
### Question:
MemstoreKeyValueScanner implements KeyValueScanner, InternalScanner { @Override public KeyValue next() throws IOException{ KeyValue returnValue=peakKeyValue; if(currentResult!=null && advance()) peakKeyValue=(KeyValue)current(); else{ nextResult(); returnValue=peakKeyValue; } return returnValue; } MemstoreKeyValueScanner(ResultScanner resultScanner); Cell current(); boolean advance(); boolean nextResult(); @Override KeyValue peek(); @Override KeyValue next(); @Override boolean next(List<Cell> results); @Override boolean seekToLastRow(); @Override boolean seek(Cell key); @Override boolean reseek(Cell key); @Override boolean requestSeek(Cell kv,boolean forward,boolean useBloom); @Override boolean backwardSeek(Cell key); @Override boolean seekToPreviousRow(Cell key); @Override long getScannerOrder(); @Override void close(); @Override boolean shouldUseScanner(Scan scan, HStore store, long l); @Override boolean realSeekDone(); @Override void enforceSeek(); @Override boolean isFileScanner(); @Override Path getFilePath(); @Override boolean next(List<Cell> result, ScannerContext scannerContext); @Override Cell getNextIndexedKey(); @Override void shipped(); }### Answer:
@Test public void testExistingResultsAreOrdered() throws IOException { ResultScanner rs = generateResultScanner(SITestUtils.getMockTombstoneCell(10)); MemstoreKeyValueScanner mkvs = new MemstoreKeyValueScanner(rs); List<Cell> results = new ArrayList<>(); results.add(SITestUtils.getMockCommitCell(10, 11)); results.add(SITestUtils.getMockValueCell(10)); mkvs.next(results); assertEquals("Number of results doesn't match", 3, results.size()); assertTrue("Results are not ordered", Ordering.from(KeyValue.COMPARATOR).isOrdered(results)); } |
### Question:
HConfiguration extends HBaseConfiguration { private SConfiguration init() { SConfiguration config = INSTANCE; if (config == null) { synchronized (this) { config = INSTANCE; if (config == null) { HBaseConfigurationSource configSource = new HBaseConfigurationSource(SpliceConfiguration.create()); ConfigurationBuilder builder = new ConfigurationBuilder(); config = builder.build(new HConfigurationDefaultsList().addConfig(this), configSource); INSTANCE = config; LOG.info("Created Splice configuration."); config.traceConfig(); } } } return config; } private HConfiguration(); static SConfiguration getConfiguration(); static SConfiguration reloadConfiguration(Configuration resetConfiguration); static Configuration unwrapDelegate(); @Override void setDefaults(ConfigurationBuilder builder, ConfigurationSource configurationSource); static final Boolean DEFAULT_IN_MEMORY; static final Boolean DEFAULT_BLOCKCACHE; static final int DEFAULT_TTL; static final String DEFAULT_BLOOMFILTER; }### Answer:
@Test public void testInit() throws Exception { SConfiguration config = HConfiguration.getConfiguration(); String auth = config.getAuthentication(); assertEquals("NON-NATIVE", auth); } |
### Question:
HConfiguration extends HBaseConfiguration { public static SConfiguration getConfiguration() { return new HConfiguration().init(); } private HConfiguration(); static SConfiguration getConfiguration(); static SConfiguration reloadConfiguration(Configuration resetConfiguration); static Configuration unwrapDelegate(); @Override void setDefaults(ConfigurationBuilder builder, ConfigurationSource configurationSource); static final Boolean DEFAULT_IN_MEMORY; static final Boolean DEFAULT_BLOCKCACHE; static final int DEFAULT_TTL; static final String DEFAULT_BLOOMFILTER; }### Answer:
@Test public void testPrefixMatch() throws Exception { SConfiguration config = HConfiguration.getConfiguration(); Map<String, String> auths = config.prefixMatch("splice.authentication.*"); String key = "splice.authentication"; String value = auths.get(key); assertNotNull(value); assertEquals("NON-NATIVE", value); key = "splice.authentication.native.algorithm"; value = auths.get(key); assertNotNull(value); assertEquals("SHA-512", value); key = "splice.authentication.native.create.credentials.database"; value = auths.get(key); assertNotNull(value); assertEquals("false", value); } |
### Question:
RingBuffer { public boolean isFull() { return size() == buffer.length; } RingBuffer(int bufferSize); T next(); void add(T element); int size(); int bufferSize(); @SuppressWarnings("unchecked") T peek(); boolean isFull(); boolean isEmpty(); void expand(); void readReset(); void readAdvance(); void clear(); void mark(); }### Answer:
@Test public void isFull() { RingBuffer<Integer> buffer = new RingBuffer<Integer>(4); buffer.add(10); assertFalse(buffer.isFull()); buffer.add(10); assertFalse(buffer.isFull()); buffer.add(10); assertFalse(buffer.isFull()); buffer.add(10); assertTrue(buffer.isFull()); } |
### Question:
RingBuffer { public int size() { return writePosition - readPosition; } RingBuffer(int bufferSize); T next(); void add(T element); int size(); int bufferSize(); @SuppressWarnings("unchecked") T peek(); boolean isFull(); boolean isEmpty(); void expand(); void readReset(); void readAdvance(); void clear(); void mark(); }### Answer:
@Test public void size() { RingBuffer<Integer> buffer = new RingBuffer<Integer>(16); assertEquals(0, buffer.size()); buffer.add(42); assertEquals(1, buffer.size()); buffer.add(42); assertEquals(2, buffer.size()); buffer.clear(); assertEquals(0, buffer.size()); } |
### Question:
RingBuffer { public void clear() { readPosition = writePosition; offsetReadPosition = readPosition; } RingBuffer(int bufferSize); T next(); void add(T element); int size(); int bufferSize(); @SuppressWarnings("unchecked") T peek(); boolean isFull(); boolean isEmpty(); void expand(); void readReset(); void readAdvance(); void clear(); void mark(); }### Answer:
@Test public void clear() throws Exception { int bufferSize = 10; RingBuffer<Integer> buffer = new RingBuffer<Integer>(bufferSize); for (int i = 0; i < bufferSize; i++) { buffer.add(i); } buffer.clear(); assertEquals(0, buffer.size()); assertFalse(buffer.isFull()); assertTrue(buffer.isEmpty()); assertNull("Should not see another value", buffer.next()); } |
### Question:
RingBuffer { public void expand() { buffer = Arrays.copyOf(buffer, 2 * buffer.length); mask = buffer.length - 1; } RingBuffer(int bufferSize); T next(); void add(T element); int size(); int bufferSize(); @SuppressWarnings("unchecked") T peek(); boolean isFull(); boolean isEmpty(); void expand(); void readReset(); void readAdvance(); void clear(); void mark(); }### Answer:
@Test public void expand() { RingBuffer<Integer> buffer = new RingBuffer<Integer>(2); buffer.add(10); buffer.add(20); assertTrue(buffer.isFull()); buffer.expand(); assertFalse(buffer.isFull()); buffer.add(30); buffer.add(40); assertTrue(buffer.isFull()); assertEquals(4, buffer.size()); assertEquals(4, buffer.bufferSize()); assertEquals(10, buffer.next().intValue()); assertEquals(20, buffer.next().intValue()); assertEquals(30, buffer.next().intValue()); assertEquals(40, buffer.next().intValue()); } |
### Question:
Streams { @SafeVarargs public static <T> Stream<T> of(T...elements){ return new ArrayStream<>(elements); } @SafeVarargs static Stream<T> of(T...elements); static Stream<T> wrap(Iterator<T> iterator); static Stream<T> wrap(Iterable<T> iterable); static PeekableStream<T> peekingStream(Stream<T> stream); @SuppressWarnings("unchecked") static Stream<T> empty(); @SuppressWarnings("unchecked") static MeasuredStream<T,V> measuredEmpty(); }### Answer:
@Test public void of() throws StreamException { Stream<String> stream = Streams.of("111", "222", "333"); assertEquals("111", stream.next()); assertEquals("222", stream.next()); assertEquals("333", stream.next()); } |
### Question:
Streams { public static <T> Stream<T> wrap(Iterator<T> iterator){ return new IteratorStream<>(iterator); } @SafeVarargs static Stream<T> of(T...elements); static Stream<T> wrap(Iterator<T> iterator); static Stream<T> wrap(Iterable<T> iterable); static PeekableStream<T> peekingStream(Stream<T> stream); @SuppressWarnings("unchecked") static Stream<T> empty(); @SuppressWarnings("unchecked") static MeasuredStream<T,V> measuredEmpty(); }### Answer:
@Test public void wrap() throws StreamException { List<String> list = Lists.newArrayList("111", "222", "333"); Stream<String> stream1 = Streams.wrap(list); Stream<String> stream2 = Streams.wrap(list.iterator()); assertEquals("111", stream1.next()); assertEquals("111", stream2.next()); assertEquals("222", stream1.next()); assertEquals("222", stream2.next()); assertEquals("333", stream1.next()); assertEquals("333", stream2.next()); } |
### Question:
Streams { public static <T> PeekableStream<T> peekingStream(Stream<T> stream){ return new PeekingStream<>(stream); } @SafeVarargs static Stream<T> of(T...elements); static Stream<T> wrap(Iterator<T> iterator); static Stream<T> wrap(Iterable<T> iterable); static PeekableStream<T> peekingStream(Stream<T> stream); @SuppressWarnings("unchecked") static Stream<T> empty(); @SuppressWarnings("unchecked") static MeasuredStream<T,V> measuredEmpty(); }### Answer:
@Test public void peekingStream() throws StreamException { Stream<String> stream = Streams.of("111", "222", "333"); PeekableStream<String> stream1 = Streams.peekingStream(stream); assertEquals("111", stream1.peek()); assertEquals("111", stream1.next()); assertEquals("222", stream1.peek()); assertEquals("222", stream1.next()); assertEquals("333", stream1.peek()); assertEquals("333", stream1.next()); assertEquals(null, stream1.peek()); } |
### Question:
AbstractStream implements Stream<T> { @Override public void forEach(Accumulator<T> accumulator) throws StreamException { T n; while((n = next())!=null){ accumulator.accumulate(n); } } @Override Stream<V> transform(Transformer<T, V> transformer); @Override void forEach(Accumulator<T> accumulator); @Override Stream<T> filter(Predicate<T> predicate); @Override Iterator<T> asIterator(); @Override Stream<T> limit(long maxSize); }### Answer:
@Test public void forEach() throws StreamException { SumAccumulator accumulator = new SumAccumulator(); new IntegerStream().forEach(accumulator); assertEquals(45, accumulator.sum); } |
### Question:
AbstractStream implements Stream<T> { @Override public <V> Stream<V> transform(Transformer<T, V> transformer) { return new TransformingStream<>(this,transformer); } @Override Stream<V> transform(Transformer<T, V> transformer); @Override void forEach(Accumulator<T> accumulator); @Override Stream<T> filter(Predicate<T> predicate); @Override Iterator<T> asIterator(); @Override Stream<T> limit(long maxSize); }### Answer:
@Test public void transform() throws StreamException { SumAccumulator accumulator = new SumAccumulator(); new IntegerStream().transform(new NegateTransformer()).forEach(accumulator); assertEquals(-45, accumulator.sum); } |
### Question:
Threads { public static void sleep(long duration, TimeUnit timeUnit) { try { Thread.sleep(timeUnit.toMillis(duration)); } catch (InterruptedException e) { throw new IllegalStateException(e); } } private Threads(); static void sleep(long duration, TimeUnit timeUnit); }### Answer:
@Test public void sleep() { long startTime = System.currentTimeMillis(); Threads.sleep(100, TimeUnit.MILLISECONDS); long elapsedTime = System.currentTimeMillis() - startTime; assertTrue(elapsedTime < 1000); assertTrue(elapsedTime > 75); } |
### Question:
CountDownLatches { public static void uncheckedAwait(CountDownLatch countDownLatch) { try { countDownLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } } static void uncheckedAwait(CountDownLatch countDownLatch); static boolean uncheckedAwait(CountDownLatch countDownLatch, long timeout, TimeUnit timeUnit); }### Answer:
@Test public void testUncheckedAwait() throws Exception { final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { latch.countDown(); } }.start(); CountDownLatches.uncheckedAwait(latch); }
@Test public void testUncheckedAwaitWithTimeout() throws Exception { final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { latch.countDown(); } }.start(); assertTrue(CountDownLatches.uncheckedAwait(latch, 5, TimeUnit.SECONDS)); }
@Test public void testUncheckedAwaitWithTimeoutReturnsFalse() throws Exception { final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { Threads.sleep(5, TimeUnit.SECONDS); } }.start(); assertFalse(CountDownLatches.uncheckedAwait(latch, 50, TimeUnit.MILLISECONDS)); } |
### Question:
MoreExecutors { public static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon) { ThreadFactory factory = new ThreadFactoryBuilder() .setNameFormat(nameFormat) .setDaemon(isDaemon) .build(); return Executors.newSingleThreadExecutor(factory); } private MoreExecutors(); static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon); static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat); static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers,
String nameFormat,
long keepAliveSeconds,
boolean isDaemon); }### Answer:
@Test public void newSingleThreadExecutor_usesThreadWithExpectedName() throws Exception { ExecutorService executorService = MoreExecutors.namedSingleThreadExecutor("testName-%d", false); Future<String> threadName = executorService.submit(new GetThreadNameCallable()); Future<Boolean> isDaemon = executorService.submit(new IsDaemonCallable()); assertTrue(threadName.get().matches("testName-\\d")); assertEquals(false, isDaemon.get()); executorService.shutdown(); } |
### Question:
MoreExecutors { public static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat) { ThreadFactory factory = new ThreadFactoryBuilder() .setNameFormat(nameFormat) .setDaemon(true) .build(); return new LoggingScheduledThreadPoolExecutor(1, factory); } private MoreExecutors(); static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon); static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat); static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers,
String nameFormat,
long keepAliveSeconds,
boolean isDaemon); }### Answer:
@Test public void namedSingleThreadScheduledExecutor() throws Exception { ScheduledExecutorService executorService = MoreExecutors.namedSingleThreadScheduledExecutor("testName-%d"); Future<String> threadName = executorService.submit(new GetThreadNameCallable()); Future<Boolean> isDaemon = executorService.submit(new IsDaemonCallable()); assertTrue(threadName.get().matches("testName-\\d")); assertEquals(true, isDaemon.get()); executorService.shutdown(); } |
### Question:
MoreExecutors { public static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers, String nameFormat, long keepAliveSeconds, boolean isDaemon) { ThreadFactory factory = new ThreadFactoryBuilder() .setNameFormat(nameFormat) .setDaemon(isDaemon) .build(); return new ThreadPoolExecutor(coreWorkers, maxWorkers, keepAliveSeconds, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), factory); } private MoreExecutors(); static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon); static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat); static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers,
String nameFormat,
long keepAliveSeconds,
boolean isDaemon); }### Answer:
@Test public void namedThreadPool() throws Exception { final int CORE_POOL_SIZE = 1 + new Random().nextInt(9); final int MAX_POOL_SIZE = CORE_POOL_SIZE + new Random().nextInt(9); final int KEEP_ALIVE_SEC = new Random().nextInt(100); final boolean IS_DAEMON = new Random().nextBoolean(); ThreadPoolExecutor executorService = MoreExecutors.namedThreadPool(CORE_POOL_SIZE, MAX_POOL_SIZE, "testName-%d", KEEP_ALIVE_SEC, IS_DAEMON); Future<String> threadName = executorService.submit(new GetThreadNameCallable()); Future<Boolean> isDaemon = executorService.submit(new IsDaemonCallable()); assertEquals(CORE_POOL_SIZE, executorService.getCorePoolSize()); assertEquals(MAX_POOL_SIZE, executorService.getMaximumPoolSize()); assertEquals(KEEP_ALIVE_SEC, executorService.getKeepAliveTime(TimeUnit.SECONDS)); assertEquals(IS_DAEMON, isDaemon.get()); assertTrue(threadName.get().matches("testName-\\d")); executorService.shutdown(); } |
### Question:
LongStripedSynchronizer { public static LongStripedSynchronizer<ReadWriteLock> stripedReadWriteLock(int stripes, final boolean fair){ int s = getNearestPowerOf2(stripes); return new LongStripedSynchronizer<ReadWriteLock>(s,new Supplier<ReadWriteLock>() { @Override public ReadWriteLock get() { return new ReentrantReadWriteLock(fair); } }); } private LongStripedSynchronizer(int size,Supplier<T> supplier); static LongStripedSynchronizer<Lock> stripedLock(int stripes); static LongStripedSynchronizer<ReadWriteLock> stripedReadWriteLock(int stripes, final boolean fair); static LongStripedSynchronizer<Semaphore> stripedSemaphor(int stripes, final int permitSize); @SuppressWarnings("unchecked") T get(long key); }### Answer:
@Test public void stripedReadWriteLock() { LongStripedSynchronizer<ReadWriteLock> striped = LongStripedSynchronizer.stripedReadWriteLock(128, false); Set<ReadWriteLock> locks = Sets.newIdentityHashSet(); for (long i = 0; i < 2000; i++) { ReadWriteLock e = striped.get(i); locks.add(e); } assertEquals(128, locks.size()); } |
### Question:
Snowflake { public static long timestampFromUUID(long uuid) { return (uuid & TIMESTAMP_LOCATION) >> TIMESTAMP_SHIFT; } Snowflake(short machineId); static long timestampFromUUID(long uuid); byte[] nextUUIDBytes(); void nextUUIDBlock(long[] uuids); long nextUUID(); Generator newGenerator(int blockSize); @Override String toString(); static final long TIMESTAMP_MASK; static final int TIMESTAMP_SHIFT; static final int UUID_BYTE_SIZE; }### Answer:
@Test public void timestampFromUUID() { assertEquals(1402425368772L, Snowflake.timestampFromUUID(-2074918693534679039l)); assertEquals(1402425369637L, Snowflake.timestampFromUUID(-7920591009858039807l)); assertEquals(1402425368822L, Snowflake.timestampFromUUID(-903982790418145279l)); assertEquals(1402425369571L, Snowflake.timestampFromUUID(-9091526912974639103l)); assertEquals(1402425371394L, Snowflake.timestampFromUUID(2320594542789664769l)); assertEquals(1402425364788L, Snowflake.timestampFromUUID(-6857741497818464255l)); assertEquals(1402425364777L, Snowflake.timestampFromUUID(-6875755896327991295l)); assertEquals(1402425368039L, Snowflake.timestampFromUUID(-4533884090081972223l)); } |
### Question:
Snowflake { @Override public String toString() { return "Snowflake{" + "lastTimestamp=" + lastTimestamp + ", counter=" + counter + ", machineId=" + machineId + '}'; } Snowflake(short machineId); static long timestampFromUUID(long uuid); byte[] nextUUIDBytes(); void nextUUIDBlock(long[] uuids); long nextUUID(); Generator newGenerator(int blockSize); @Override String toString(); static final long TIMESTAMP_MASK; static final int TIMESTAMP_SHIFT; static final int UUID_BYTE_SIZE; }### Answer:
@Test public void toString_includesExpectedMachineId() { assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=2}", new Snowflake((short) (1 << 1)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=4}", new Snowflake((short) (1 << 2)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=8}", new Snowflake((short) (1 << 3)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=16}", new Snowflake((short) (1 << 4)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=32}", new Snowflake((short) (1 << 5)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=64}", new Snowflake((short) (1 << 6)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=2048}", new Snowflake((short) (1 << 11)).toString()); } |
### Question:
Murmur64 implements Hash64 { @Override public long hash(String elem) { assert elem!=null: "Cannot hash a null element"; int length = elem.length(); long h = initialize(seed,length); int pos =0; char[] chars = elem.toCharArray(); while(length-pos>=8){ h = hash(h, LittleEndianBits.toLong(chars, pos)); pos+=8; } h = updatePartial(chars,length-pos,h,pos); return finalize(h); } Murmur64(int seed); @Override long hash(String elem); @Override long hash(byte[] data, int offset, int length); @Override long hash(ByteBuffer byteBuffer); @Override long hash(long element); @Override long hash(int element); @Override long hash(float element); @Override long hash(double element); }### Answer:
@Test public void testByteBufferSameAsByteArray() throws Exception { long correct = hasher.hash(sampleData,0,sampleData.length); ByteBuffer bb = ByteBuffer.wrap(sampleData); long actual = hasher.hash(bb); Assert.assertEquals(correct,actual); }
@Test public void testIntSameAsByteArray() throws Exception { byte[] bytes = Bytes.toBytes(sampleValue); long correct = hasher.hash(bytes,0,bytes.length); long actual = hasher.hash(sampleValue); Assert.assertEquals("Incorrect int hash!",correct,actual); }
@Test public void testLongSameAsByteArray() throws Exception { byte[] bytes = Bytes.toBytes(sampleLong); long correct = hasher.hash(bytes,0,bytes.length); long actual = hasher.hash(sampleLong); Assert.assertEquals("Incorrect long hash!",correct,actual); } |
### Question:
QuoteTrackingTokenizer extends AbstractTokenizer { @Override public boolean readColumns(final List<String> columns) throws IOException { return readColumns(columns, null); } QuoteTrackingTokenizer(final Reader reader, final CsvPreference preferences, final boolean oneLineRecord, boolean quotedEmptyIsNull); QuoteTrackingTokenizer(final Reader reader, final CsvPreference preferences, final boolean oneLineRecord, boolean quotedEmptyIsNull,
final long scanThresold, final List<Integer> valueSizeHints); @Override boolean readColumns(final List<String> columns); boolean readColumns(final List<String> columns, final BooleanList quotedColumns); void clearRow(); String getUntokenizedRow(); }### Answer:
@Test public void quotedMultiRowRecordWithOneLineRecordSetThrowsProperly() throws Exception { String invalidRow = "\"hello\",\"wrong\ncell\",goodbye\n"; try { QuoteTrackingTokenizer qtt = new QuoteTrackingTokenizer(new StringReader(invalidRow), CsvPreference.STANDARD_PREFERENCE, true, true); List<String> columns = new ArrayList<>(); qtt.readColumns(columns); Assert.fail("expected exception to be thrown, but no exception was thrown"); } catch(Exception e) { Assert.assertTrue(e instanceof SuperCsvException); Assert.assertEquals("one-line record CSV has a record that spans over multiple lines at line 1", e.getMessage()); return; } Assert.fail("expected exception to be thrown, but no exception was thrown"); } |
### Question:
TimestampV2DescriptorSerializer extends TimestampV1DescriptorSerializer { public static long formatLong(Timestamp timestamp) throws StandardException { long millis = SQLTimestamp.checkV2Bounds(timestamp); long micros = timestamp.getNanos() / NANOS_TO_MICROS; return millis * MICROS_TO_SECOND + micros; } static long formatLong(Timestamp timestamp); static final Factory INSTANCE_FACTORY; }### Answer:
@Test public void shouldFailOnSmallDate() { String errorCode = "N/A"; try { TimestampV2DescriptorSerializer.formatLong(getTimestamp(1677)); } catch (StandardException e) { errorCode = e.getSqlState(); } assertEquals(SQLState.LANG_DATE_TIME_ARITHMETIC_OVERFLOW, errorCode); }
@Test public void shouldFailOnLargeDate() { String errorCode = "N/A"; try { TimestampV2DescriptorSerializer.formatLong(getTimestamp(2263)); } catch (StandardException e) { errorCode = e.getSqlState(); } assertEquals(SQLState.LANG_DATE_TIME_ARITHMETIC_OVERFLOW, errorCode); } |
### Question:
SpliceDateFunctions { public static Date ADD_MONTHS(Date source, Integer numOfMonths) { if (source == null || numOfMonths == null) return null; DateTime dt = new DateTime(source); return new Date(dt.plusMonths(numOfMonths).getMillis()); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }### Answer:
@Test public void testAddMonth() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.add(Calendar.MONTH, 2); Date s = new Date(c.getTime().getTime()); assertEquals(SpliceDateFunctions.ADD_MONTHS(t, 2), s); } |
### Question:
SpliceDateFunctions { public static Date ADD_DAYS(Date source, Integer numOfDays) { if (source == null || numOfDays == null) return null; DateTime dt = new DateTime(source); return new Date(dt.plusDays(numOfDays).getMillis()); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }### Answer:
@Test public void testAddDays() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.add(Calendar.DAY_OF_MONTH, 2); Date s = new Date(c.getTime().getTime()); assertEquals(SpliceDateFunctions.ADD_DAYS(t, 2), s); } |
### Question:
SpliceDateFunctions { public static Date ADD_YEARS(Date source, Integer numOfYears) { if (source == null || numOfYears == null) return null; DateTime dt = new DateTime(source); return new Date(dt.plusYears(numOfYears).getMillis()); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }### Answer:
@Test public void testAddYears() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.add(Calendar.YEAR, 2); Date s = new Date(c.getTime().getTime()); assertEquals(SpliceDateFunctions.ADD_YEARS(t, 2), s); } |
### Question:
SpliceDateFunctions { public static Date LAST_DAY(Date source) { if (source == null) { return null; } DateTime dt = new DateTime(source).dayOfMonth().withMaximumValue(); return new Date(dt.getMillis()); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }### Answer:
@Test public void testLastDay() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); Date s = new Date(c.getTime().getTime()); assertEquals(SpliceDateFunctions.LAST_DAY(t), s); } |
### Question:
FormatableBitSet implements Formatable, Cloneable { public void set(int position) { checkPosition(position); final int byteIndex = udiv8(position); final byte bitIndex = umod8(position); value[byteIndex] |= (0x80>>bitIndex); } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); }### Answer:
@Test public void testSetEmpty() { try { empty.set(-8); fail(); } catch (IllegalArgumentException ignored) { } try { empty.set(-1); fail(); } catch (IllegalArgumentException ignored) { } try { empty.set(0); fail(); } catch (IllegalArgumentException ignored) { } }
@Test public void testSet() { try { bitset18.set(-8); fail(); } catch (IllegalArgumentException ignored) { } try { bitset18.set(-1); fail(); } catch (IllegalArgumentException ignored) { } bitset18.set(0); assertTrue(bitset18.invariantHolds()); bitset18.set(1); assertTrue(bitset18.invariantHolds()); try { bitset18.set(18); fail(); } catch (IllegalArgumentException ignored) { } } |
### Question:
AbstractSequence implements Sequence, Externalizable { public long getNext() throws StandardException{ if(remaining.getAndDecrement()<=0) allocateBlock(false); return currPosition.getAndAdd(incrementSteps); } AbstractSequence(); AbstractSequence(long blockAllocationSize,long incrementSteps,long startingValue); long getNext(); long peekAtCurrentValue(); abstract void close(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); }### Answer:
@Test public void singleThreaded100BlockSingleIncrementTestWithRollover() throws Exception { Sequence sequence = new SpliceTestSequence(100,1,0); for (long i = 0; i< 1000; i++) { long next = sequence.getNext(); Assert.assertTrue(i==next); } }
@Test public void singleThreaded1BlockSingleIncrementTestWithRollover() throws Exception { Sequence sequence = new SpliceTestSequence(1,1,0); for (long i = 0; i< 1000; i++) { long next = sequence.getNext(); Assert.assertTrue(i==next); } }
@Test public void singleThreaded1BlockWithStarting20WithRollover() throws Exception { Sequence sequence = new SpliceTestSequence(1,1,20); for (long i = 0; i< 1000; i++) { long next = sequence.getNext(); Assert.assertTrue(i+20==next); } }
@Test public void singleThreaded100BlockWithStarting20Increment10WithRollover() throws Exception { Sequence sequence = new SpliceTestSequence(100,10,20); for (long i = 0; i< 1000; i++) { long next = sequence.getNext(); Assert.assertTrue((i*10+20)==next); } } |
### Question:
DMLTriggerEventMapper { public static TriggerEvent getBeforeEvent(Class<? extends DMLWriteOperation> operationClass) { for (Map.Entry<Class<? extends DMLWriteOperation>, TriggerEvent> entry : beforeMap.entrySet()) { if (entry.getKey().isAssignableFrom(operationClass)) { return entry.getValue(); } } throw new IllegalArgumentException("could not find trigger event for operation = " + operationClass); } static TriggerEvent getBeforeEvent(Class<? extends DMLWriteOperation> operationClass); static TriggerEvent getAfterEvent(Class<? extends DMLWriteOperation> operationClass); }### Answer:
@Test public void testGetBeforeEvent() throws Exception { assertEquals(TriggerEvent.BEFORE_DELETE, DMLTriggerEventMapper.getBeforeEvent(DeleteOperation.class)); assertEquals(TriggerEvent.BEFORE_INSERT, DMLTriggerEventMapper.getBeforeEvent(InsertOperation.class)); assertEquals(TriggerEvent.BEFORE_UPDATE, DMLTriggerEventMapper.getBeforeEvent(UpdateOperation.class)); } |
### Question:
DMLTriggerEventMapper { public static TriggerEvent getAfterEvent(Class<? extends DMLWriteOperation> operationClass) { for (Map.Entry<Class<? extends DMLWriteOperation>, TriggerEvent> entry : afterMap.entrySet()) { if (entry.getKey().isAssignableFrom(operationClass)) { return entry.getValue(); } } throw new IllegalArgumentException("could not find trigger event for operation = " + operationClass); } static TriggerEvent getBeforeEvent(Class<? extends DMLWriteOperation> operationClass); static TriggerEvent getAfterEvent(Class<? extends DMLWriteOperation> operationClass); }### Answer:
@Test public void testGetAfterEvent() throws Exception { assertEquals(TriggerEvent.AFTER_DELETE, DMLTriggerEventMapper.getAfterEvent(DeleteOperation.class)); assertEquals(TriggerEvent.AFTER_INSERT, DMLTriggerEventMapper.getAfterEvent(InsertOperation.class)); assertEquals(TriggerEvent.AFTER_UPDATE, DMLTriggerEventMapper.getAfterEvent(UpdateOperation.class)); } |
### Question:
IndexRowReader implements Iterator<ExecRow>, Iterable<ExecRow> { public int getMaxConcurrency() {return this.numBlocks;} IndexRowReader(Iterator<ExecRow> sourceIterator,
ExecRow outputTemplate,
TxnView txn,
int lookupBatchSize,
int numConcurrentLookups,
long mainTableConglomId,
byte[] predicateFilterBytes,
KeyHashDecoder keyDecoder,
KeyHashDecoder rowDecoder,
int[] indexCols,
TxnOperationFactory operationFactory,
PartitionFactory tableFactory); int getMaxConcurrency(); void close(); @Override @SuppressFBWarnings(value = "IT_NO_SUCH_ELEMENT", justification = "DB-9844") ExecRow next(); ExecRow nextScannedRow(); @Override void remove(); @Override boolean hasNext(); @Override Iterator<ExecRow> iterator(); }### Answer:
@Test public void testReaderConcurrency() throws Exception { IndexRowReader irr = new IndexRowReader( null, null, null, 4000, 0, 0, null, null, null, null, null, null); assertTrue("Expected a max concurrency of 2", irr.getMaxConcurrency() == 2); irr = new IndexRowReader( null, null, null, 4000, -5000, 0, null, null, null, null, null, null); assertTrue("Expected a max concurrency of 2", irr.getMaxConcurrency() == 2); } |
### Question:
ExportFile { public OutputStream getOutputStream() throws IOException { String fullyQualifiedExportFilePath = buildOutputFilePath(); OutputStream rawOutputStream =fileSystem.newOutputStream(fullyQualifiedExportFilePath, new DistributedFileOpenOption(exportParams.getReplicationCount(),StandardOpenOption.CREATE_NEW)); if (exportParams.getCompression()==COMPRESSION.BZ2) { Configuration conf = new Configuration(); CompressionCodecFactory factory = new CompressionCodecFactory(conf); CompressionCodec codec = factory.getCodecByClassName("org.apache.hadoop.io.compress.BZip2Codec"); return codec.createOutputStream(rawOutputStream); } else if (exportParams.getCompression()==COMPRESSION.GZ) { return new GZIPOutputStream(rawOutputStream); } else { return rawOutputStream; } } ExportFile(ExportParams exportParams, byte[] taskId); ExportFile(ExportParams exportParams, byte[] taskId, DistributedFileSystem fileSystem); OutputStream getOutputStream(); boolean createDirectory(); boolean delete(); boolean deleteDirectory(); boolean clearDirectory(); boolean isWritable(); static final String SUCCESS_FILE; }### Answer:
@Test public void getOutputStream_createsStreamConnectedToExpectedFile() throws IOException { ExportParams exportParams = ExportParams.withDirectory(temporaryFolder.getRoot().getAbsolutePath()); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); final byte[] EXPECTED_CONTENT = ("splice for the win" + RandomStringUtils.randomAlphanumeric(1000)).getBytes("utf-8"); OutputStream outputStream = exportFile.getOutputStream(); outputStream.write(EXPECTED_CONTENT); outputStream.close(); File expectedFile = new File(temporaryFolder.getRoot(), "export_82010203042A060708.csv"); assertTrue(expectedFile.exists()); Assert.assertArrayEquals(EXPECTED_CONTENT,IOUtils.toByteArray(new FileInputStream(expectedFile))); } |
### Question:
ExportFile { protected String buildFilenameFromTaskId(byte[] taskId) { String postfix = ""; if (exportParams.getCompression() == COMPRESSION.BZ2) { postfix = ".bz2"; } else if (exportParams.getCompression() == COMPRESSION.GZ) { postfix = ".gz"; } return "export_" + Bytes.toHex(taskId) + ".csv" + postfix; } ExportFile(ExportParams exportParams, byte[] taskId); ExportFile(ExportParams exportParams, byte[] taskId, DistributedFileSystem fileSystem); OutputStream getOutputStream(); boolean createDirectory(); boolean delete(); boolean deleteDirectory(); boolean clearDirectory(); boolean isWritable(); static final String SUCCESS_FILE; }### Answer:
@Test public void buildFilenameFromTaskId() throws IOException { ExportFile streamSetup = new ExportFile(new ExportParams(), testTaskId(),dfs); byte[] taskId = testTaskId(); assertEquals("export_82010203042A060708.csv", streamSetup.buildFilenameFromTaskId(taskId)); } |
### Question:
ExportFile { public boolean delete() throws IOException { if (LOG.isDebugEnabled()) SpliceLogUtils.debug(LOG, "delete()"); try{ fileSystem.delete(exportParams.getDirectory(),buildFilenameFromTaskId(taskId), false); return true; }catch(NoSuchFileException fnfe){ return false; } } ExportFile(ExportParams exportParams, byte[] taskId); ExportFile(ExportParams exportParams, byte[] taskId, DistributedFileSystem fileSystem); OutputStream getOutputStream(); boolean createDirectory(); boolean delete(); boolean deleteDirectory(); boolean clearDirectory(); boolean isWritable(); static final String SUCCESS_FILE; }### Answer:
@Test public void delete() throws IOException { ExportParams exportParams = ExportParams.withDirectory(temporaryFolder.getRoot().getAbsolutePath()); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); exportFile.getOutputStream(); assertTrue("export file should exist in temp dir", temporaryFolder.getRoot().list().length > 0); exportFile.delete(); assertTrue("export file should be deleted", temporaryFolder.getRoot().list().length == 0); } |
### Question:
ExportFile { public boolean createDirectory() throws StandardException { if (LOG.isDebugEnabled()) SpliceLogUtils.debug(LOG, "createDirectory(): export directory=%s", exportParams.getDirectory()); try { return fileSystem.createDirectory(exportParams.getDirectory(), false); } catch (Exception ioe) { throw StandardException.newException(SQLState.FILESYSTEM_IO_EXCEPTION, ioe.getMessage()); } } ExportFile(ExportParams exportParams, byte[] taskId); ExportFile(ExportParams exportParams, byte[] taskId, DistributedFileSystem fileSystem); OutputStream getOutputStream(); boolean createDirectory(); boolean delete(); boolean deleteDirectory(); boolean clearDirectory(); boolean isWritable(); static final String SUCCESS_FILE; }### Answer:
@Test public void createDirectory() throws IOException, StandardException { String testDir = temporaryFolder.getRoot().getAbsolutePath() + "/" + RandomStringUtils.randomAlphabetic(9); ExportParams exportParams = ExportParams.withDirectory(testDir); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); assertTrue(exportFile.createDirectory()); assertTrue(new File(testDir).exists()); assertTrue(new File(testDir).isDirectory()); }
@Ignore @Test public void createDirectory_returnsFalseWhenCannotCreate() throws IOException, StandardException { String testDir = "/noPermissionToCreateFolderInRoot"; ExportParams exportParams = ExportParams.withDirectory(testDir); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); try { assertFalse(exportFile.createDirectory()); } catch (Exception e) { assertThat(e.getMessage(), stringContainsInOrder("IOException '/noPermissionToCreateFolderInRoot","' when accessing directory")); } assertFalse(new File(testDir).exists()); assertFalse(new File(testDir).isDirectory()); } |
### Question:
ExportPermissionCheck { void verify() throws StandardException { verifyExportDirExistsOrCanBeCreated(); verifyExportDirWritable(); } ExportPermissionCheck(ExportParams exportParams,DistributedFileSystem dfs); ExportPermissionCheck(ExportParams exportParams); void cleanup(); }### Answer:
@Ignore @Test public void verify_failCase() throws IOException, StandardException { ExportParams exportParams = ExportParams.withDirectory("/ExportPermissionCheckTest"); ExportPermissionCheck permissionCheck = new ExportPermissionCheck(exportParams,dfs); try { permissionCheck.verify(); } catch (Exception e) { assertThat(e.getMessage(), stringContainsInOrder("IOException '/ExportPermissionCheckTest", "' when accessing directory")); } } |
### Question:
CostUtils { public static long add(long count1, long count2) { checkArgument(count1 >= 0); checkArgument(count2 >= 0); long sum = count1 + count2; return (sum >= 0L) ? sum : Long.MAX_VALUE; } static long add(long count1, long count2); }### Answer:
@Test public void add() { long result = CostUtils.add(20L, 20L); assertEquals(40L, result); result = CostUtils.add(Long.MAX_VALUE, 200L); assertEquals(Long.MAX_VALUE, result); } |
### Question:
SpliceClient { static String parseJDBCPassword(String jdbcUrl) throws SqlException { Properties properties = ClientDriver.tokenizeURLProperties(jdbcUrl, null); return properties.getProperty("password"); } static synchronized void setClient(boolean tokenEnabled, Mode mode); static boolean isClient(); @SuppressFBWarnings(value = "DC_PARTIALLY_CONSTRUCTED", justification = "DB-9844") static DataSource getConnectionPool(boolean debugConnections, int maxConnections); @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "DB-9844")
static boolean isRegionServer; static volatile String connectionString; static volatile byte[] token; }### Answer:
@Test public void testParseJDBCPassword() throws SqlException { String password = "Abd98*@80EFg"; String raw = "jdbc:splice: assertEquals(password, SpliceClient.parseJDBCPassword(raw)); raw = "jdbc:splice: assertEquals(password, SpliceClient.parseJDBCPassword(raw)); } |
### Question:
ConstraintContext implements Externalizable { public ConstraintContext withInsertedMessage(int index, String newMessage) { return new ConstraintContext((String[]) ArrayUtils.add(messageArgs,index,newMessage)); } @Deprecated ConstraintContext(); ConstraintContext(String... messageArgs); static ConstraintContext empty(); static ConstraintContext unique(String tableName, String constraintName); static ConstraintContext primaryKey(String tableName, String constraintName); static ConstraintContext foreignKey(FKConstraintInfo fkConstraintInfo); ConstraintContext withInsertedMessage(int index, String newMessage); ConstraintContext withoutMessage(int index); ConstraintContext withMessage(int index, String newMessage); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") String[] getMessages(); @Override boolean equals(Object o); @Override int hashCode(); @Override void readExternal(ObjectInput objectInput); @Override void writeExternal(ObjectOutput objectOutput); @Override String toString(); }### Answer:
@Test public void withInsertedMessage() { ConstraintContext context1 = new ConstraintContext("aa", "bb", "cc"); ConstraintContext context2 = context1.withInsertedMessage(0, "ZZ"); ConstraintContext context3 = context1.withInsertedMessage(1, "ZZ"); ConstraintContext context4 = context1.withInsertedMessage(2, "ZZ"); ConstraintContext context5 = context1.withInsertedMessage(3, "ZZ"); assertArrayEquals(new String[]{"ZZ", "aa", "bb", "cc"}, context2.getMessages()); assertArrayEquals(new String[]{"aa", "ZZ", "bb", "cc"}, context3.getMessages()); assertArrayEquals(new String[]{"aa", "bb", "ZZ", "cc"}, context4.getMessages()); assertArrayEquals(new String[]{"aa", "bb", "cc", "ZZ"}, context5.getMessages()); } |
### Question:
ConstraintContext implements Externalizable { public ConstraintContext withoutMessage(int index) { return new ConstraintContext((String[]) ArrayUtils.remove(messageArgs,index)); } @Deprecated ConstraintContext(); ConstraintContext(String... messageArgs); static ConstraintContext empty(); static ConstraintContext unique(String tableName, String constraintName); static ConstraintContext primaryKey(String tableName, String constraintName); static ConstraintContext foreignKey(FKConstraintInfo fkConstraintInfo); ConstraintContext withInsertedMessage(int index, String newMessage); ConstraintContext withoutMessage(int index); ConstraintContext withMessage(int index, String newMessage); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") String[] getMessages(); @Override boolean equals(Object o); @Override int hashCode(); @Override void readExternal(ObjectInput objectInput); @Override void writeExternal(ObjectOutput objectOutput); @Override String toString(); }### Answer:
@Test public void withOutMessage() { ConstraintContext context1 = new ConstraintContext("aa", "bb", "cc"); ConstraintContext context2 = context1.withoutMessage(0); ConstraintContext context3 = context1.withoutMessage(1); ConstraintContext context4 = context1.withoutMessage(2); assertArrayEquals(new String[]{"bb", "cc"}, context2.getMessages()); assertArrayEquals(new String[]{"aa", "cc"}, context3.getMessages()); assertArrayEquals(new String[]{"aa", "bb"}, context4.getMessages()); } |
### Question:
ConstraintContext implements Externalizable { public ConstraintContext withMessage(int index, String newMessage) { String[] newArgs = Arrays.copyOf(this.messageArgs, this.messageArgs.length); newArgs[index] = newMessage; return new ConstraintContext(newArgs); } @Deprecated ConstraintContext(); ConstraintContext(String... messageArgs); static ConstraintContext empty(); static ConstraintContext unique(String tableName, String constraintName); static ConstraintContext primaryKey(String tableName, String constraintName); static ConstraintContext foreignKey(FKConstraintInfo fkConstraintInfo); ConstraintContext withInsertedMessage(int index, String newMessage); ConstraintContext withoutMessage(int index); ConstraintContext withMessage(int index, String newMessage); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") String[] getMessages(); @Override boolean equals(Object o); @Override int hashCode(); @Override void readExternal(ObjectInput objectInput); @Override void writeExternal(ObjectOutput objectOutput); @Override String toString(); }### Answer:
@Test public void withMessage() { ConstraintContext context1 = new ConstraintContext("aa", "bb", "cc"); ConstraintContext context2 = context1.withMessage(0, "ZZ"); ConstraintContext context3 = context1.withMessage(1, "ZZ"); ConstraintContext context4 = context1.withMessage(2, "ZZ"); assertArrayEquals(new String[]{"ZZ", "bb", "cc"}, context2.getMessages()); assertArrayEquals(new String[]{"aa", "ZZ", "cc"}, context3.getMessages()); assertArrayEquals(new String[]{"aa", "bb", "ZZ"}, context4.getMessages()); } |
### Question:
FormatableBitSet implements Formatable, Cloneable { public void clear(int position) { checkPosition(position); final int byteIndex = udiv8(position); final byte bitIndex = umod8(position); value[byteIndex] &= ~(0x80>>bitIndex); } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); }### Answer:
@Test public void testClearEmpty() { try { empty.clear(-8); fail(); } catch (IllegalArgumentException ignored) { } try { empty.clear(-1); fail(); } catch (IllegalArgumentException ignored) { } try { empty.clear(0); fail(); } catch (IllegalArgumentException ignored) { } }
@Test public void testClear() { try { bitset18.clear(-8); fail(); } catch (IllegalArgumentException ignored) { } try { bitset18.clear(-1); fail(); } catch (IllegalArgumentException ignored) { } bitset18.clear(0); assertTrue(bitset18.invariantHolds()); bitset18.clear(1); assertTrue(bitset18.invariantHolds()); try { bitset18.clear(18); fail(); } catch (IllegalArgumentException ignored) { } } |
### Question:
ArrayInputStream extends InputStream implements LimitObjectInput { public long skip(long count) throws IOException { if (count <= 0) { return 0; } long toSkip = Math.min(count, available()); position += toSkip; return toSkip; } ArrayInputStream(); ArrayInputStream(byte[] data); void setData(byte[] data); byte[] getData(); int read(); int read(byte b[], int off, int len); long skip(long count); int getPosition(); final void setPosition(int newPosition); int available(); void setLimit(int offset, int length); final void setLimit(int length); final int clearLimit(); final void readFully(byte b[]); final void readFully(byte b[], int off, int len); final int skipBytes(int n); final boolean readBoolean(); final byte readByte(); final int readUnsignedByte(); final short readShort(); final int readUnsignedShort(); final char readChar(); final int readInt(); final long readLong(); final float readFloat(); final double readDouble(); final String readLine(); final String readUTF(); final int readDerbyUTF(char[][] rawData_array, int utflen); final int readCompressedInt(); final long readCompressedLong(); Object readObject(); String getErrorInfo(); Exception getNestedException(); }### Answer:
@Test public void testSkipNegative() throws IOException { ArrayInputStream ais = new ArrayInputStream(new byte[1000]); assertEquals(0, ais.skip(-1)); } |
### Question:
ArrayInputStream extends InputStream implements LimitObjectInput { public final int skipBytes(int n) throws IOException { return (int) skip(n); } ArrayInputStream(); ArrayInputStream(byte[] data); void setData(byte[] data); byte[] getData(); int read(); int read(byte b[], int off, int len); long skip(long count); int getPosition(); final void setPosition(int newPosition); int available(); void setLimit(int offset, int length); final void setLimit(int length); final int clearLimit(); final void readFully(byte b[]); final void readFully(byte b[], int off, int len); final int skipBytes(int n); final boolean readBoolean(); final byte readByte(); final int readUnsignedByte(); final short readShort(); final int readUnsignedShort(); final char readChar(); final int readInt(); final long readLong(); final float readFloat(); final double readDouble(); final String readLine(); final String readUTF(); final int readDerbyUTF(char[][] rawData_array, int utflen); final int readCompressedInt(); final long readCompressedLong(); Object readObject(); String getErrorInfo(); Exception getNestedException(); }### Answer:
@Test public void testSkipBytesNegative() throws IOException { ArrayInputStream ais = new ArrayInputStream(new byte[1000]); assertEquals(0, ais.skipBytes(-1)); } |
### Question:
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long nullCount() { return nullCount; } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testNullCount() throws StandardException { Assert.assertEquals(0, impl.nullCount()); } |
### Question:
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long notNullCount() { return quantilesSketch.getN(); } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testNotNullCount() throws StandardException { Assert.assertEquals(10000,impl.notNullCount()); } |
### Question:
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long totalCount() { return quantilesSketch.getN()+nullCount; } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testTotalCount() throws StandardException { Assert.assertEquals(10000,impl.totalCount()); } |
### Question:
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow maxValue() { return quantilesSketch.getMaxValue(); } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testMaxValue() throws StandardException { Assert.assertEquals(maxRow,impl.maxValue()); } |
### Question:
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow minValue() { return quantilesSketch.getMinValue(); } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testMinValue() throws StandardException { Assert.assertEquals(minRow,impl.minValue()); } |
### Question:
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long selectivity(ExecRow element) { return 1L; } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testNullSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(null)); }
@Test public void testEmptySelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(new ValueRow(3))); }
@Test public void testIndividualSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(minRow)); } |
### Question:
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long nullCount() { return nullCount; } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testNullCount() throws StandardException { Assert.assertEquals(0, impl.nullCount()); } |
### Question:
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long notNullCount() { return quantilesSketch.getN(); } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testNotNullCount() throws StandardException { Assert.assertEquals(10000,impl.notNullCount()); } |
### Question:
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long totalCount() { return quantilesSketch.getN()+nullCount; } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testTotalCount() throws StandardException { Assert.assertEquals(10000,impl.totalCount()); } |
### Question:
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow maxValue() { return quantilesSketch.getMaxValue(); } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testMaxValue() throws StandardException { Assert.assertEquals(maxRow,impl.maxValue()); } |
### Question:
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow minValue() { return quantilesSketch.getMinValue(); } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testMinValue() throws StandardException { Assert.assertEquals(minRow,impl.minValue()); } |
### Question:
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long selectivity(ExecRow element) { return 1L; } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
long nullCount
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testNullSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(null)); }
@Test public void testEmptySelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(new ValueRow(3))); }
@Test public void testIndividualSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(minRow)); } |
### Question:
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long nullCount() { return 0; } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch,
Sketch thetaSketch
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testNullCount() throws StandardException { Assert.assertEquals(0, impl.nullCount()); } |
### Question:
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long notNullCount() { return quantilesSketch.getN(); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch,
Sketch thetaSketch
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testNotNullCount() throws StandardException { Assert.assertEquals(10000,impl.notNullCount()); } |
### Question:
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long totalCount() { return quantilesSketch.getN(); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch,
com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch,
Sketch thetaSketch
); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer:
@Test public void testTotalCount() throws StandardException { Assert.assertEquals(10000,impl.totalCount()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.