method2testcases
stringlengths
118
3.08k
### Question: Platform { static Platform get() { return PLATFORM; } Platform(boolean hasJava8Types); }### Answer: @Test public void isAndroid() { assertFalse(Platform.get() instanceof Platform.Android); }
### Question: Invocation { public static Invocation of(Method method, List<?> arguments) { Objects.requireNonNull(method, "method == null"); Objects.requireNonNull(arguments, "arguments == null"); return new Invocation(method, new ArrayList<>(arguments)); } Invocation(Method method, List<?> arguments); static Invocation of(Method method, List<?> arguments); Method method(); List<?> arguments(); @Override String toString(); }### Answer: @Test public void nullMethod() { try { Invocation.of(null, Arrays.asList("one", "two")); fail(); } catch (NullPointerException expected) { assertThat(expected).hasMessage("method == null"); } } @Test public void nullArguments() { try { Invocation.of(Example.class.getDeclaredMethods()[0], null); fail(); } catch (NullPointerException expected) { assertThat(expected).hasMessage("arguments == null"); } }
### Question: HttpException extends RuntimeException { public @Nullable Response<?> response() { return response; } HttpException(Response<?> response); int code(); String message(); @Nullable Response<?> response(); }### Answer: @Test public void response() { Response<String> response = Response.success("Hi"); HttpException exception = new HttpException(response); assertThat(exception.code()).isEqualTo(200); assertThat(exception.message()).isEqualTo("OK"); assertThat(exception.response()).isSameAs(response); }
### Question: Retrofit { public @Nullable Executor callbackExecutor() { return callbackExecutor; } Retrofit( okhttp3.Call.Factory callFactory, HttpUrl baseUrl, List<Converter.Factory> converterFactories, List<CallAdapter.Factory> callAdapterFactories, @Nullable Executor callbackExecutor, boolean validateEagerly); @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety. T create(final Class<T> service); okhttp3.Call.Factory callFactory(); HttpUrl baseUrl(); List<CallAdapter.Factory> callAdapterFactories(); CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations); CallAdapter<?, ?> nextCallAdapter( @Nullable CallAdapter.Factory skipPast, Type returnType, Annotation[] annotations); List<Converter.Factory> converterFactories(); Converter<T, RequestBody> requestBodyConverter( Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations); Converter<T, RequestBody> nextRequestBodyConverter( @Nullable Converter.Factory skipPast, Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations); Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations); Converter<ResponseBody, T> nextResponseBodyConverter( @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations); Converter<T, String> stringConverter(Type type, Annotation[] annotations); @Nullable Executor callbackExecutor(); Builder newBuilder(); }### Answer: @Test public void callbackExecutorNullThrows() { try { new Retrofit.Builder().callbackExecutor(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("executor == null"); } }
### Question: NetworkBehavior { public Throwable failureException() { return failureException; } private NetworkBehavior(Random random); static NetworkBehavior create(); @SuppressWarnings("ConstantConditions") // Guarding API nullability. static NetworkBehavior create(Random random); void setDelay(long amount, TimeUnit unit); long delay(TimeUnit unit); void setVariancePercent(int variancePercent); int variancePercent(); void setFailurePercent(int failurePercent); int failurePercent(); @SuppressWarnings("ConstantConditions") // Guarding API nullability. void setFailureException(Throwable exception); Throwable failureException(); int errorPercent(); void setErrorPercent(int errorPercent); @SuppressWarnings("ConstantConditions") // Guarding API nullability. void setErrorFactory(Callable<Response<?>> errorFactory); Response<?> createErrorResponse(); boolean calculateIsFailure(); boolean calculateIsError(); long calculateDelay(TimeUnit unit); }### Answer: @Test public void defaultThrowable() { Throwable t = behavior.failureException(); assertThat(t) .isInstanceOf(IOException.class) .isExactlyInstanceOf(MockRetrofitIOException.class); assertThat(t.getStackTrace()).isEmpty(); }
### Question: NetworkBehavior { public void setDelay(long amount, TimeUnit unit) { if (amount < 0) { throw new IllegalArgumentException("Amount must be positive value."); } this.delayMs = unit.toMillis(amount); } private NetworkBehavior(Random random); static NetworkBehavior create(); @SuppressWarnings("ConstantConditions") // Guarding API nullability. static NetworkBehavior create(Random random); void setDelay(long amount, TimeUnit unit); long delay(TimeUnit unit); void setVariancePercent(int variancePercent); int variancePercent(); void setFailurePercent(int failurePercent); int failurePercent(); @SuppressWarnings("ConstantConditions") // Guarding API nullability. void setFailureException(Throwable exception); Throwable failureException(); int errorPercent(); void setErrorPercent(int errorPercent); @SuppressWarnings("ConstantConditions") // Guarding API nullability. void setErrorFactory(Callable<Response<?>> errorFactory); Response<?> createErrorResponse(); boolean calculateIsFailure(); boolean calculateIsError(); long calculateDelay(TimeUnit unit); }### Answer: @Test public void delayMustBePositive() { try { behavior.setDelay(-1, SECONDS); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Amount must be positive value."); } }
### Question: UriTemplateParser { public static void parse(String template, Handler handler) { assert template != null; assert handler != null; int pos = 0; final int length = template.length(); State state = State.OutsideParam; StringBuilder builder = new StringBuilder(); while (pos < length) { char c = template.charAt(pos++); switch (state) { case InsideParam: { if (c == '}') { if (builder.length() > 0) { handler.handleParam(builder.toString()); builder.setLength(0); } state = State.OutsideParam; } else { builder.append(c); } break; } case OutsideParam: { if (c == '{') { if (builder.length() > 0) { handler.handleText(builder.toString()); builder.setLength(0); } state = State.InsideParam; } else { builder.append(c); } break; } } } if (builder.length() > 0) { switch (state) { case InsideParam: handler.handleParam(builder.toString()); break; case OutsideParam: handler.handleText(builder.toString()); break; } } } static void parse(String template, Handler handler); }### Answer: @Test public void shouldParseParameterFirst() { UriTemplateParser.parse("{a}/bc", handler); verify(handler).handleParam("a"); verify(handler).handleText("/bc"); verifyNoMoreInteractions(handler); } @Test public void shouldParseParameterLast() { UriTemplateParser.parse("bc/{a}", handler); verify(handler).handleText("bc/"); verify(handler).handleParam("a"); verifyNoMoreInteractions(handler); } @Test public void shouldParseMultipleParameters() { UriTemplateParser.parse("bc/{a}{b}", handler); verify(handler).handleText("bc/"); verify(handler).handleParam("a"); verify(handler).handleParam("b"); verifyNoMoreInteractions(handler); } @Test public void shouldParseEmpty() { UriTemplateParser.parse("", handler); verifyNoMoreInteractions(handler); }
### Question: WadlXsltUtils { public static String hypernizeURI(String uri) { String result = uri.replaceAll("/", "/&#8203;"); return result; } static InputStream getUpgradeTransformAsStream(); static InputStream getWadlSummaryTransform(); static String hypernizeURI(String uri); }### Answer: @Test public void hypernizUriTest() { String uri = "http: String result = WadlXsltUtils.hypernizeURI(uri); assertThat(5, equalTo(result.split("&").length)); }
### Question: WadlAstBuilder { public ApplicationNode buildAst(URI rootFile) throws InvalidWADLException, IOException { try { Application a = processDescription(rootFile); return buildAst(a,rootFile); } catch (JAXBException ex) { throw new RuntimeException("Internal error",ex); } } WadlAstBuilder( SchemaCallback schemaCallback, MessageListener messageListener); Map<String, ResourceTypeNode> getInterfaceMap(); ApplicationNode buildAst(URI rootFile); static InvalidWADLException messageStringFromObject(String message, Object obj); }### Answer: @Test public void testSoapUIYahooSearch() throws InvalidWADLException, IOException, URISyntaxException { WadlAstBuilder builder = new WadlAstBuilder( new WadlAstBuilder.SchemaCallback() { public void processSchema(InputSource is) { } public void processSchema(String uri, Element node) { } }, new MessageListener() { public void warning(String message, Throwable throwable) { } public void info(String message) { } public void error(String message, Throwable throwable) { } }); ApplicationNode an = builder.buildAst(WadlAstBuilderTest.class.getResource("SoapUIYahooSearch.wadl").toURI()); List<MethodNode> methods = an.getResources().get(0).getChildResources().get(0).getMethods(); assertThat("Only one method", methods.size(), equalTo(1)); List<RepresentationNode> supportedOutputs = new ArrayList<RepresentationNode>(); for (List<RepresentationNode> nodeList : methods.get(0).getSupportedOutputs().values()) { for (RepresentationNode node : nodeList) { supportedOutputs.add(node); } } assertThat("Only one output", supportedOutputs.size(), equalTo(1)); assertThat("Only one fault", methods.get(0).getFaults().size(), equalTo(1)); }
### Question: JModule { public String name() { return name; } JModule(final String name); String name(); void _exports(final JPackage pkg); void _exports(final Collection<JPackage> pkgs, final boolean addEmpty); void _requires(final String name, final boolean isPublic, final boolean isStatic); void _requires(final String name); void _requires(final boolean isPublic, final boolean isStatic, final String ...names); void _requires(final String ...names); JFormatter generate(final JFormatter f); }### Answer: @Test public void testName() { final JModule instance = new JModule(MODULE_NAME); assertEquals(MODULE_NAME, instance.name()); }
### Question: JModule { public void _exports(final JPackage pkg) { directives.add(new JExportsDirective(pkg.name())); } JModule(final String name); String name(); void _exports(final JPackage pkg); void _exports(final Collection<JPackage> pkgs, final boolean addEmpty); void _requires(final String name, final boolean isPublic, final boolean isStatic); void _requires(final String name); void _requires(final boolean isPublic, final boolean isStatic, final String ...names); void _requires(final String ...names); JFormatter generate(final JFormatter f); }### Answer: @Test public void test_exports() { final JModule instance = new JModule(MODULE_NAME); final JCodeModel cm = new JCodeModel(); final JPackage pkg = new JPackage(PKG_NAME, cm); instance._exports(pkg); JModuleDirective directive = directivesSingleElementCheck(instance); assertTrue(directive instanceof JExportsDirective); assertEquals(PKG_NAME, directive.name); }
### Question: JModule { public void _requires(final String name, final boolean isPublic, final boolean isStatic) { directives.add(new JRequiresDirective(name, isPublic, isStatic)); } JModule(final String name); String name(); void _exports(final JPackage pkg); void _exports(final Collection<JPackage> pkgs, final boolean addEmpty); void _requires(final String name, final boolean isPublic, final boolean isStatic); void _requires(final String name); void _requires(final boolean isPublic, final boolean isStatic, final String ...names); void _requires(final String ...names); JFormatter generate(final JFormatter f); }### Answer: @Test public void test_requires() { final JModule instance = new JModule(MODULE_NAME); instance._requires(DEP_MODULE_NAME); JModuleDirective directive = directivesSingleElementCheck(instance); assertTrue(directive instanceof JRequiresDirective); assertEquals(DEP_MODULE_NAME, directive.name); }
### Question: JModule { public JFormatter generate(final JFormatter f) { f.p("module").p(name); f.p('{').nl(); if (!directives.isEmpty()) { f.i(); for (final JModuleDirective directive : directives) { directive.generate(f); } f.o(); } f.p('}').nl(); return f; } JModule(final String name); String name(); void _exports(final JPackage pkg); void _exports(final Collection<JPackage> pkgs, final boolean addEmpty); void _requires(final String name, final boolean isPublic, final boolean isStatic); void _requires(final String name); void _requires(final boolean isPublic, final boolean isStatic, final String ...names); void _requires(final String ...names); JFormatter generate(final JFormatter f); }### Answer: @Test public void testGenerate() { final JModule instance = new JModule(MODULE_NAME); instance.generate(jf); final String output = normalizeWhiteSpaces(out.toString()); verifyModuleEnvelope(output, instance); }
### Question: SchemaGenerator { private static String setClasspath(String givenClasspath) { StringBuilder cp = new StringBuilder(); appendPath(cp, givenClasspath); ClassLoader cl = Thread.currentThread().getContextClassLoader(); while (cl != null) { if (cl instanceof URLClassLoader) { for (URL url : ((URLClassLoader) cl).getURLs()) { try { appendPath(cp,new File(url.toURI()).getPath()); } catch(URISyntaxException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } } } cl = cl.getParent(); } appendPath(cp, findJaxbApiJar()); return cp.toString(); } static void main(String[] args); static int run(String[] args); static int run(String[] args, ClassLoader classLoader); }### Answer: @Test public void setClassPathTest() throws Exception { final URL cUrl = new MockUp<URL>() { String path = "C:"; @Mock public String getPath() { return "/" + path; } @Mock public URI toURI() { return new File(path).toURI(); } }.getMockInstance(); new MockUp<URLClassLoader>() { @Mock URL[] getURLs() { URL[] urls = { cUrl }; return urls; } }; new Expectations(SchemaGenerator.class) {{ invoke(SchemaGenerator.class, "findJaxbApiJar"); result = ""; }}; String result = invoke(SchemaGenerator.class, "setClasspath", ""); String sepChar = File.pathSeparator; assertFalse("Result classpath contains incorrect drive path", result.contains(sepChar+"/C:")); }
### Question: PluginImpl extends Plugin { public boolean run(@NotNull Outline model, Options opt, ErrorHandler errorHandler) { checkAndInject(model.getClasses()); checkAndInject(model.getEnums()); return true; } String getOptionName(); List<String> getCustomizationURIs(); boolean isCustomizationTagName(String nsUri, String localName); String getUsage(); boolean run(@NotNull Outline model, Options opt, ErrorHandler errorHandler); }### Answer: @Test public void pluginRunTest(final @Mocked Outline model, @Mocked Options opt, @Mocked ErrorHandler errorHandler) { new Expectations() {{ Collection<? extends CustomizableOutline> target = Collections.emptyList(); model.getClasses(); result = target; Deencapsulation.invoke(PluginImpl.class, "checkAndInject", target); model.getEnums(); result = target; Deencapsulation.invoke(PluginImpl.class, "checkAndInject", target); }}; new PluginImpl().run(model, opt, errorHandler); }
### Question: AuthenticationKey implements Writable { @Override public int hashCode() { int result = id; result = 31 * result + (int) (expirationDate ^ (expirationDate >>> 32)); result = 31 * result + ((secret == null) ? 0 : Arrays.hashCode(secret.getEncoded())); return result; } AuthenticationKey(); AuthenticationKey(int keyId, long expirationDate, SecretKey key); int getKeyId(); long getExpiration(); void setExpiration(long timestamp); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override void write(DataOutput out); @Override void readFields(DataInput in); }### Answer: @Test public void test() throws UnsupportedEncodingException { SecretKey secret = Mockito.mock(SecretKey.class); Mockito.when(secret.getEncoded()).thenReturn("secret".getBytes("UTF-8")); AuthenticationKey key = new AuthenticationKey(0, 1234, secret); assertEquals(key.hashCode(), new AuthenticationKey(0, 1234, secret).hashCode()); assertEquals(key, new AuthenticationKey(0, 1234, secret)); AuthenticationKey otherID = new AuthenticationKey(1, 1234, secret); assertNotEquals(key.hashCode(), otherID.hashCode()); assertNotEquals(key, otherID); AuthenticationKey otherExpiry = new AuthenticationKey(0, 8765, secret); assertNotEquals(key.hashCode(), otherExpiry.hashCode()); assertNotEquals(key, otherExpiry); SecretKey other = Mockito.mock(SecretKey.class); Mockito.when(secret.getEncoded()).thenReturn("other".getBytes("UTF-8")); AuthenticationKey otherSecret = new AuthenticationKey(0, 1234, other); assertNotEquals(key.hashCode(), otherSecret.hashCode()); assertNotEquals(key, otherSecret); }
### Question: MultiTableSnapshotInputFormatImpl { public Map<String, Collection<Scan>> getSnapshotsToScans(Configuration conf) throws IOException { Map<String, Collection<Scan>> rtn = Maps.newHashMap(); for (Map.Entry<String, String> entry : ConfigurationUtil .getKeyValues(conf, SNAPSHOT_TO_SCANS_KEY)) { String snapshotName = entry.getKey(); String scan = entry.getValue(); Collection<Scan> snapshotScans = rtn.get(snapshotName); if (snapshotScans == null) { snapshotScans = Lists.newArrayList(); rtn.put(snapshotName, snapshotScans); } snapshotScans.add(TableMapReduceUtil.convertStringToScan(scan)); } return rtn; } void setInput(Configuration conf, Map<String, Collection<Scan>> snapshotScans, Path restoreDir); List<TableSnapshotInputFormatImpl.InputSplit> getSplits(Configuration conf); Map<String, Collection<Scan>> getSnapshotsToScans(Configuration conf); void setSnapshotToScans(Configuration conf, Map<String, Collection<Scan>> snapshotScans); Map<String, Path> getSnapshotDirs(Configuration conf); void setSnapshotDirs(Configuration conf, Map<String, Path> snapshotDirs); void restoreSnapshots(Configuration conf, Map<String, Path> snapshotToDir, FileSystem fs); static final String RESTORE_DIRS_KEY; static final String SNAPSHOT_TO_SCANS_KEY; }### Answer: @Test public void testSetInputSetsSnapshotToScans() throws Exception { callSetInput(); Map<String, Collection<Scan>> actual = subject.getSnapshotsToScans(conf); Map<String, Collection<ScanWithEquals>> actualWithEquals = toScanWithEquals(actual); Map<String, Collection<ScanWithEquals>> expectedWithEquals = toScanWithEquals(snapshotScans); assertEquals(expectedWithEquals, actualWithEquals); }
### Question: MultiTableSnapshotInputFormatImpl { public Map<String, Path> getSnapshotDirs(Configuration conf) throws IOException { List<Map.Entry<String, String>> kvps = ConfigurationUtil.getKeyValues(conf, RESTORE_DIRS_KEY); Map<String, Path> rtn = Maps.newHashMapWithExpectedSize(kvps.size()); for (Map.Entry<String, String> kvp : kvps) { rtn.put(kvp.getKey(), new Path(kvp.getValue())); } return rtn; } void setInput(Configuration conf, Map<String, Collection<Scan>> snapshotScans, Path restoreDir); List<TableSnapshotInputFormatImpl.InputSplit> getSplits(Configuration conf); Map<String, Collection<Scan>> getSnapshotsToScans(Configuration conf); void setSnapshotToScans(Configuration conf, Map<String, Collection<Scan>> snapshotScans); Map<String, Path> getSnapshotDirs(Configuration conf); void setSnapshotDirs(Configuration conf, Map<String, Path> snapshotDirs); void restoreSnapshots(Configuration conf, Map<String, Path> snapshotToDir, FileSystem fs); static final String RESTORE_DIRS_KEY; static final String SNAPSHOT_TO_SCANS_KEY; }### Answer: @Test public void testSetInputPushesRestoreDirectories() throws Exception { callSetInput(); Map<String, Path> restoreDirs = subject.getSnapshotDirs(conf); assertEquals(this.snapshotScans.keySet(), restoreDirs.keySet()); } @Test public void testSetInputCreatesRestoreDirectoriesUnderRootRestoreDir() throws Exception { callSetInput(); Map<String, Path> restoreDirs = subject.getSnapshotDirs(conf); for (Path snapshotDir : restoreDirs.values()) { assertEquals("Expected " + snapshotDir + " to be a child of " + restoreDir, restoreDir, snapshotDir.getParent()); } }
### Question: TableSplit extends InputSplit implements Writable, Comparable<TableSplit> { @Override public long getLength() { return length; } TableSplit(); @Deprecated TableSplit(final byte [] tableName, Scan scan, byte [] startRow, byte [] endRow, final String location); TableSplit(TableName tableName, Scan scan, byte [] startRow, byte [] endRow, final String location); TableSplit(TableName tableName, Scan scan, byte [] startRow, byte [] endRow, final String location, long length); @Deprecated TableSplit(final byte [] tableName, byte[] startRow, byte[] endRow, final String location); TableSplit(TableName tableName, byte[] startRow, byte[] endRow, final String location); TableSplit(TableName tableName, byte[] startRow, byte[] endRow, final String location, long length); Scan getScan(); byte [] getTableName(); TableName getTable(); byte [] getStartRow(); byte [] getEndRow(); String getRegionLocation(); @Override String[] getLocations(); @Override long getLength(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override String toString(); @Override int compareTo(TableSplit split); @Override boolean equals(Object o); @Override int hashCode(); @Deprecated static final Log LOG; }### Answer: @Test public void testLengthIsSerialized() throws Exception { TableSplit split1 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location", 666); TableSplit deserialized = new TableSplit(TableName.valueOf("table"), "row-start2".getBytes(), "row-end2".getBytes(), "location1"); ReflectionUtils.copy(new Configuration(), split1, deserialized); Assert.assertEquals(666, deserialized.getLength()); }
### Question: CopyTable extends Configured implements Tool { public CopyTable(Configuration conf) { super(conf); } CopyTable(Configuration conf); Job createSubmittableJob(String[] args); static void main(String[] args); @Override int run(String[] args); }### Answer: @Test public void testCopyTable() throws Exception { doCopyTableTest(false); }
### Question: CopyTable extends Configured implements Tool { public static void main(String[] args) throws Exception { int ret = ToolRunner.run(new CopyTable(HBaseConfiguration.create()), args); System.exit(ret); } CopyTable(Configuration conf); Job createSubmittableJob(String[] args); static void main(String[] args); @Override int run(String[] args); }### Answer: @Test public void testMainMethod() throws Exception { String[] emptyArgs = { "-h" }; PrintStream oldWriter = System.err; ByteArrayOutputStream data = new ByteArrayOutputStream(); PrintStream writer = new PrintStream(data); System.setErr(writer); SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager= new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); try { CopyTable.main(emptyArgs); fail("should be exit"); } catch (SecurityException e) { assertEquals(1, newSecurityManager.getExitCode()); } finally { System.setErr(oldWriter); System.setSecurityManager(SECURITY_MANAGER); } assertTrue(data.toString().contains("rs.class")); assertTrue(data.toString().contains("Usage:")); }
### Question: FSHDFSUtils extends FSUtils { boolean recoverLease(final DistributedFileSystem dfs, final int nbAttempt, final Path p, final long startWaiting) throws FileNotFoundException { boolean recovered = false; try { recovered = dfs.recoverLease(p); LOG.info((recovered? "Recovered lease, ": "Failed to recover lease, ") + getLogMessageDetail(nbAttempt, p, startWaiting)); } catch (IOException e) { if (e instanceof LeaseExpiredException && e.getMessage().contains("File does not exist")) { throw new FileNotFoundException("The given WAL wasn't found at " + p); } else if (e instanceof FileNotFoundException) { throw (FileNotFoundException)e; } LOG.warn(getLogMessageDetail(nbAttempt, p, startWaiting), e); } return recovered; } static boolean isSameHdfs(Configuration conf, FileSystem srcFs, FileSystem desFs); @Override void recoverFileLease(final FileSystem fs, final Path p, Configuration conf, CancelableProgressable reporter); }### Answer: @Test (timeout = 30000) public void testRecoverLease() throws IOException { HTU.getConfiguration().setInt("hbase.lease.recovery.dfs.timeout", 1000); CancelableProgressable reporter = Mockito.mock(CancelableProgressable.class); Mockito.when(reporter.progress()).thenReturn(true); DistributedFileSystem dfs = Mockito.mock(DistributedFileSystem.class); Mockito.when(dfs.recoverLease(FILE)). thenReturn(false).thenReturn(false).thenReturn(false).thenReturn(false).thenReturn(true); assertTrue(this.fsHDFSUtils.recoverDFSFileLease(dfs, FILE, HTU.getConfiguration(), reporter)); Mockito.verify(dfs, Mockito.times(5)).recoverLease(FILE); assertTrue((EnvironmentEdgeManager.currentTime() - this.startTime) > (3 * HTU.getConfiguration().getInt("hbase.lease.recovery.dfs.timeout", 61000))); }
### Question: HFileOutputFormat extends FileOutputFormat<ImmutableBytesWritable, KeyValue> { public static void configureIncrementalLoad(Job job, HTable table) throws IOException { HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(), table.getRegionLocator()); } @Override RecordWriter<ImmutableBytesWritable, KeyValue> getRecordWriter( final TaskAttemptContext context); static void configureIncrementalLoad(Job job, HTable table); static final String DATABLOCK_ENCODING_OVERRIDE_CONF_KEY; }### Answer: @Test public void testJobConfiguration() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); conf.set("hbase.fs.tmp.dir", util.getDataTestDir("testJobConfiguration").toString()); Job job = new Job(conf); job.setWorkingDirectory(util.getDataTestDir("testJobConfiguration")); HTableDescriptor tableDescriptor = Mockito.mock(HTableDescriptor.class); RegionLocator regionLocator = Mockito.mock(RegionLocator.class); setupMockStartKeys(regionLocator); HFileOutputFormat2.configureIncrementalLoad(job, tableDescriptor, regionLocator); assertEquals(job.getNumReduceTasks(), 4); }
### Question: SyncTable extends Configured implements Tool { public SyncTable(Configuration conf) { super(conf); } SyncTable(Configuration conf); Job createSubmittableJob(String[] args); static void main(String[] args); @Override int run(String[] args); }### Answer: @Test public void testSyncTable() throws Exception { String sourceTableName = "testSourceTable"; String targetTableName = "testTargetTable"; Path testDir = TEST_UTIL.getDataTestDirOnTestFS("testSyncTable"); writeTestData(sourceTableName, targetTableName); hashSourceTable(sourceTableName, testDir); Counters syncCounters = syncTables(sourceTableName, targetTableName, testDir); assertEqualTables(90, sourceTableName, targetTableName); assertEquals(60, syncCounters.findCounter(Counter.ROWSWITHDIFFS).getValue()); assertEquals(10, syncCounters.findCounter(Counter.SOURCEMISSINGROWS).getValue()); assertEquals(10, syncCounters.findCounter(Counter.TARGETMISSINGROWS).getValue()); assertEquals(50, syncCounters.findCounter(Counter.SOURCEMISSINGCELLS).getValue()); assertEquals(50, syncCounters.findCounter(Counter.TARGETMISSINGCELLS).getValue()); assertEquals(20, syncCounters.findCounter(Counter.DIFFERENTCELLVALUES).getValue()); TEST_UTIL.deleteTable(sourceTableName); TEST_UTIL.deleteTable(targetTableName); TEST_UTIL.cleanupDataTestDirOnTestFS(); }
### Question: HFileOutputFormat2 extends FileOutputFormat<ImmutableBytesWritable, Cell> { @Deprecated public static void configureIncrementalLoad(Job job, HTable table) throws IOException { configureIncrementalLoad(job, table.getTableDescriptor(), table.getRegionLocator()); } @Override RecordWriter<ImmutableBytesWritable, Cell> getRecordWriter( final TaskAttemptContext context); @Deprecated static void configureIncrementalLoad(Job job, HTable table); static void configureIncrementalLoad(Job job, Table table, RegionLocator regionLocator); static void configureIncrementalLoad(Job job, HTableDescriptor tableDescriptor, RegionLocator regionLocator); static void configureIncrementalLoadMap(Job job, Table table); static final String DATABLOCK_ENCODING_OVERRIDE_CONF_KEY; }### Answer: @Ignore("Goes zombie too frequently; needs work. See HBASE-14563") @Test public void testJobConfiguration() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); conf.set(HConstants.TEMPORARY_FS_DIRECTORY_KEY, util.getDataTestDir("testJobConfiguration") .toString()); Job job = new Job(conf); job.setWorkingDirectory(util.getDataTestDir("testJobConfiguration")); RegionLocator regionLocator = Mockito.mock(RegionLocator.class); setupMockStartKeys(regionLocator); HFileOutputFormat2.configureIncrementalLoad(job, new HTableDescriptor(), regionLocator); assertEquals(job.getNumReduceTasks(), 4); }
### Question: JarFinder { public static String getJar(Class klass) { Preconditions.checkNotNull(klass, "klass"); ClassLoader loader = klass.getClassLoader(); if (loader != null) { String class_file = klass.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(class_file); itr.hasMoreElements(); ) { URL url = (URL) itr.nextElement(); String path = url.getPath(); if (path.startsWith("file:")) { path = path.substring("file:".length()); } path = URLDecoder.decode(path, "UTF-8"); if ("jar".equals(url.getProtocol())) { path = URLDecoder.decode(path, "UTF-8"); return path.replaceAll("!.*$", ""); } else if ("file".equals(url.getProtocol())) { String klassName = klass.getName(); klassName = klassName.replace(".", "/") + ".class"; path = path.substring(0, path.length() - klassName.length()); File baseDir = new File(path); File testDir = new File(System.getProperty("test.build.dir", "target/test-dir")); testDir = testDir.getAbsoluteFile(); if (!testDir.exists()) { testDir.mkdirs(); } File tempJar = File.createTempFile("hadoop-", "", testDir); tempJar = new File(tempJar.getAbsolutePath() + ".jar"); tempJar.deleteOnExit(); createJar(baseDir, tempJar); return tempJar.getAbsolutePath(); } } } catch (IOException e) { throw new RuntimeException(e); } } return null; } static void jarDir(File dir, String relativePath, ZipOutputStream zos); static String getJar(Class klass); }### Answer: @Test public void testJar() throws Exception { String jar = JarFinder.getJar(LogFactory.class); Assert.assertTrue(new File(jar).exists()); } @Test public void testExpandedClasspath() throws Exception { String jar = JarFinder.getJar(TestJarFinder.class); Assert.assertTrue(new File(jar).exists()); }
### Question: ReplicationSinkManager { public synchronized void chooseSinks() { List<ServerName> slaveAddresses = endpoint.getRegionServers(); Collections.shuffle(slaveAddresses, random); int numSinks = (int) Math.ceil(slaveAddresses.size() * ratio); sinks = slaveAddresses.subList(0, numSinks); lastUpdateToPeers = System.currentTimeMillis(); badReportCounts.clear(); } ReplicationSinkManager(HConnection conn, String peerClusterId, HBaseReplicationEndpoint endpoint, Configuration conf); synchronized SinkPeer getReplicationSink(); synchronized void reportBadSink(SinkPeer sinkPeer); synchronized void reportSinkSuccess(SinkPeer sinkPeer); synchronized void chooseSinks(); synchronized int getNumSinks(); }### Answer: @Test public void testChooseSinks() { List<ServerName> serverNames = Lists.newArrayList(); for (int i = 0; i < 20; i++) { serverNames.add(mock(ServerName.class)); } when(replicationEndpoint.getRegionServers()) .thenReturn(serverNames); sinkManager.chooseSinks(); assertEquals(2, sinkManager.getNumSinks()); }
### Question: ReplicationSinkManager { public synchronized void reportBadSink(SinkPeer sinkPeer) { ServerName serverName = sinkPeer.getServerName(); int badReportCount = (badReportCounts.containsKey(serverName) ? badReportCounts.get(serverName) : 0) + 1; badReportCounts.put(serverName, badReportCount); if (badReportCount > badSinkThreshold) { this.sinks.remove(serverName); if (sinks.isEmpty()) { chooseSinks(); } } } ReplicationSinkManager(HConnection conn, String peerClusterId, HBaseReplicationEndpoint endpoint, Configuration conf); synchronized SinkPeer getReplicationSink(); synchronized void reportBadSink(SinkPeer sinkPeer); synchronized void reportSinkSuccess(SinkPeer sinkPeer); synchronized void chooseSinks(); synchronized int getNumSinks(); }### Answer: @Test public void testReportBadSink() { ServerName serverNameA = mock(ServerName.class); ServerName serverNameB = mock(ServerName.class); when(replicationEndpoint.getRegionServers()) .thenReturn(Lists.newArrayList(serverNameA, serverNameB)); sinkManager.chooseSinks(); assertEquals(1, sinkManager.getNumSinks()); SinkPeer sinkPeer = new SinkPeer(serverNameA, mock(AdminService.BlockingInterface.class)); sinkManager.reportBadSink(sinkPeer); assertEquals(1, sinkManager.getNumSinks()); }
### Question: ConfigurationManager { public void notifyAllObservers(Configuration conf) { LOG.info("Starting to notify all observers that config changed."); synchronized (configurationObservers) { for (ConfigurationObserver observer : configurationObservers) { try { if (observer != null) { observer.onConfigurationChange(conf); } } catch (Throwable t) { LOG.error("Encountered a throwable while notifying observers: " + " of type : " + observer.getClass().getCanonicalName() + "(" + observer + ")", t); } } } } void registerObserver(ConfigurationObserver observer); void deregisterObserver(ConfigurationObserver observer); void notifyAllObservers(Configuration conf); int getNumObservers(); }### Answer: @Test public void testCheckIfObserversNotified() { Configuration conf = new Configuration(); ConfigurationManager cm = new ConfigurationManager(); DummyConfigurationObserver d1 = new DummyConfigurationObserver(cm); cm.notifyAllObservers(conf); assertTrue(d1.wasNotifiedOnChange()); d1.resetNotifiedOnChange(); DummyConfigurationObserver d2 = new DummyConfigurationObserver(cm); cm.notifyAllObservers(conf); assertTrue(d1.wasNotifiedOnChange()); d1.resetNotifiedOnChange(); assertTrue(d2.wasNotifiedOnChange()); d2.resetNotifiedOnChange(); d2.deregister(); cm.notifyAllObservers(conf); assertTrue(d1.wasNotifiedOnChange()); d1.resetNotifiedOnChange(); assertFalse(d2.wasNotifiedOnChange()); }
### Question: BoundedRegionGroupingProvider extends RegionGroupingProvider { @Override public void close() throws IOException { IOException failure = null; for (WALProvider provider : delegates) { try { provider.close(); } catch (IOException exception) { LOG.error("Problem closing provider '" + provider + "': " + exception.getMessage()); LOG.debug("Details of problem shutting down provider '" + provider + "'", exception); failure = exception; } } if (failure != null) { throw failure; } } @Override void init(final WALFactory factory, final Configuration conf, final List<WALActionsListener> listeners, final String providerId); @Override void shutdown(); @Override void close(); static long getNumLogFiles(WALFactory walFactory); static long getLogFileSize(WALFactory walFactory); }### Answer: @Test public void setMembershipDedups() throws IOException { final int temp = conf.getInt(NUM_REGION_GROUPS, DEFAULT_NUM_REGION_GROUPS); WALFactory wals = null; try { conf.setInt(NUM_REGION_GROUPS, temp*4); FSUtils.setRootDir(conf, TEST_UTIL.getDataTestDirOnTestFS()); wals = new WALFactory(conf, null, currentTest.getMethodName()); final Set<WAL> seen = new HashSet<WAL>(temp*4); final Random random = new Random(); int count = 0; for (int i = 0; i < temp*8; i++) { final WAL maybeNewWAL = wals.getWAL(Bytes.toBytes(random.nextInt())); LOG.info("Iteration " + i + ", checking wal " + maybeNewWAL); if (seen.add(maybeNewWAL)) { count++; } } assertEquals("received back a different number of WALs that are not equal() to each other " + "than the bound we placed.", temp*4, count); } finally { if (wals != null) { wals.close(); } conf.setInt(NUM_REGION_GROUPS, temp); } }
### Question: ZooKeeperMainServer { public String parse(final Configuration c) { return ZKConfig.getZKQuorumServersString(c); } String parse(final Configuration c); static void main(String args[]); }### Answer: @Test public void testHostPortParse() { ZooKeeperMainServer parser = new ZooKeeperMainServer(); Configuration c = HBaseConfiguration.create(); assertEquals("localhost:" + c.get(HConstants.ZOOKEEPER_CLIENT_PORT), parser.parse(c)); final String port = "1234"; c.set(HConstants.ZOOKEEPER_CLIENT_PORT, port); c.set("hbase.zookeeper.quorum", "example.com"); assertEquals("example.com:" + port, parser.parse(c)); c.set("hbase.zookeeper.quorum", "example1.com,example2.com,example3.com"); String ensemble = parser.parse(c); assertTrue(port, ensemble.matches("(example[1-3]\\.com:1234,){2}example[1-3]\\.com:" + port)); c.set("hbase.zookeeper.quorum", "example1.com:5678,example2.com:9012,example3.com:3456"); ensemble = parser.parse(c); assertEquals(ensemble, "example1.com:5678,example2.com:9012,example3.com:3456"); c.set("hbase.zookeeper.quorum", "example1.com:5678,example2.com:9012,example3.com"); ensemble = parser.parse(c); assertEquals(ensemble, "example1.com:5678,example2.com:9012,example3.com:" + port); }
### Question: RegionPlan implements Comparable<RegionPlan> { @Override public int hashCode() { return getRegionName().hashCode(); } RegionPlan(final HRegionInfo hri, ServerName source, ServerName dest); void setDestination(ServerName dest); ServerName getSource(); ServerName getDestination(); String getRegionName(); HRegionInfo getRegionInfo(); @Override int compareTo(RegionPlan o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void test() { HRegionInfo hri = new HRegionInfo(TableName.valueOf("table")); ServerName source = ServerName.valueOf("source", 1234, 2345); ServerName dest = ServerName.valueOf("dest", 1234, 2345); RegionPlan plan = new RegionPlan(hri, source, dest); assertEquals(plan.hashCode(), new RegionPlan(hri, source, dest).hashCode()); assertEquals(plan, new RegionPlan(hri, source, dest)); assertEquals(plan.hashCode(), new RegionPlan(hri, dest, source).hashCode()); assertEquals(plan, new RegionPlan(hri, dest, source)); HRegionInfo other = new HRegionInfo(TableName.valueOf("other")); assertNotEquals(plan.hashCode(), new RegionPlan(other, source, dest).hashCode()); assertNotEquals(plan, new RegionPlan(other, source, dest)); }
### Question: ServerAndLoad implements Comparable<ServerAndLoad>, Serializable { @Override public int hashCode() { int result = load; result = 31 * result + ((sn == null) ? 0 : sn.hashCode()); return result; } ServerAndLoad(final ServerName sn, final int load); @Override int compareTo(ServerAndLoad other); @Override int hashCode(); @Override boolean equals(Object o); }### Answer: @Test public void test() { ServerName server = ServerName.valueOf("host", 12345, 112244); int startcode = 12; ServerAndLoad sal = new ServerAndLoad(server, startcode); assertEquals(sal.hashCode(), new ServerAndLoad(server, startcode).hashCode()); assertEquals(sal, new ServerAndLoad(server, startcode)); assertNotEquals(sal.hashCode(), new ServerAndLoad(server, startcode + 1).hashCode()); assertNotEquals(sal, new ServerAndLoad(server, startcode + 1)); ServerName other = ServerName.valueOf("other", 12345, 112244); assertNotEquals(sal.hashCode(), new ServerAndLoad(other, startcode).hashCode()); assertNotEquals(sal, new ServerAndLoad(other, startcode)); }
### Question: RegionLocationFinder { protected HDFSBlocksDistribution internalGetTopBlockLocation(HRegionInfo region) { try { HTableDescriptor tableDescriptor = getTableDescriptor(region.getTable()); if (tableDescriptor != null) { HDFSBlocksDistribution blocksDistribution = HRegion.computeHDFSBlocksDistribution(getConf(), tableDescriptor, region); return blocksDistribution; } } catch (IOException ioe) { LOG.warn("IOException during HDFSBlocksDistribution computation. for " + "region = " + region.getEncodedName(), ioe); } return new HDFSBlocksDistribution(); } RegionLocationFinder(); Configuration getConf(); void setConf(Configuration conf); void setServices(MasterServices services); void setClusterStatus(ClusterStatus status); HDFSBlocksDistribution getBlockDistribution(HRegionInfo hri); }### Answer: @Test public void testInternalGetTopBlockLocation() throws Exception { for (int i = 0; i < ServerNum; i++) { HRegionServer server = cluster.getRegionServer(i); for (Region region : server.getOnlineRegions(tableName)) { HDFSBlocksDistribution blocksDistribution1 = region.getHDFSBlocksDistribution(); HDFSBlocksDistribution blocksDistribution2 = finder.getBlockDistribution(region .getRegionInfo()); assertEquals(blocksDistribution1.getUniqueBlocksTotalWeight(), blocksDistribution2.getUniqueBlocksTotalWeight()); if (blocksDistribution1.getUniqueBlocksTotalWeight() != 0) { assertEquals(blocksDistribution1.getTopHosts().get(0), blocksDistribution2.getTopHosts() .get(0)); } } } }
### Question: RegionLocationFinder { protected List<ServerName> mapHostNameToServerName(List<String> hosts) { if (hosts == null || status == null) { if (hosts == null) { LOG.warn("RegionLocationFinder top hosts is null"); } return Lists.newArrayList(); } List<ServerName> topServerNames = new ArrayList<ServerName>(); Collection<ServerName> regionServers = status.getServers(); HashMap<String, List<ServerName>> hostToServerName = new HashMap<String, List<ServerName>>(); for (ServerName sn : regionServers) { String host = sn.getHostname(); if (!hostToServerName.containsKey(host)) { hostToServerName.put(host, new ArrayList<ServerName>()); } hostToServerName.get(host).add(sn); } for (String host : hosts) { if (!hostToServerName.containsKey(host)) { continue; } for (ServerName sn : hostToServerName.get(host)) { if (sn != null) { topServerNames.add(sn); } } } return topServerNames; } RegionLocationFinder(); Configuration getConf(); void setConf(Configuration conf); void setServices(MasterServices services); void setClusterStatus(ClusterStatus status); HDFSBlocksDistribution getBlockDistribution(HRegionInfo hri); }### Answer: @Test public void testMapHostNameToServerName() throws Exception { List<String> topHosts = new ArrayList<String>(); for (int i = 0; i < ServerNum; i++) { HRegionServer server = cluster.getRegionServer(i); String serverHost = server.getServerName().getHostname(); if (!topHosts.contains(serverHost)) { topHosts.add(serverHost); } } List<ServerName> servers = finder.mapHostNameToServerName(topHosts); assertEquals(1, topHosts.size()); for (int i = 0; i < ServerNum; i++) { ServerName server = cluster.getRegionServer(i).getServerName(); assertTrue(servers.contains(server)); } }
### Question: RegionLocationFinder { protected List<ServerName> getTopBlockLocations(HRegionInfo region) { HDFSBlocksDistribution blocksDistribution = getBlockDistribution(region); List<String> topHosts = blocksDistribution.getTopHosts(); return mapHostNameToServerName(topHosts); } RegionLocationFinder(); Configuration getConf(); void setConf(Configuration conf); void setServices(MasterServices services); void setClusterStatus(ClusterStatus status); HDFSBlocksDistribution getBlockDistribution(HRegionInfo hri); }### Answer: @Test public void testGetTopBlockLocations() throws Exception { for (int i = 0; i < ServerNum; i++) { HRegionServer server = cluster.getRegionServer(i); for (Region region : server.getOnlineRegions(tableName)) { List<ServerName> servers = finder.getTopBlockLocations(region.getRegionInfo()); if (region.getHDFSBlocksDistribution().getUniqueBlocksTotalWeight() == 0) { continue; } List<String> topHosts = region.getHDFSBlocksDistribution().getTopHosts(); if (!topHosts.contains(server.getServerName().getHostname())) { continue; } for (int j = 0; j < ServerNum; j++) { ServerName serverName = cluster.getRegionServer(j).getServerName(); assertTrue(servers.contains(serverName)); } } } }
### Question: StochasticLoadBalancer extends BaseLoadBalancer { @Override public synchronized void setClusterStatus(ClusterStatus st) { super.setClusterStatus(st); updateRegionLoad(); for(CostFromRegionLoadFunction cost : regionLoadFunctions) { cost.setClusterStatus(st); } } @Override void onConfigurationChange(Configuration conf); @Override synchronized void setConf(Configuration conf); @Override synchronized void setClusterStatus(ClusterStatus st); @Override synchronized void setMasterServices(MasterServices masterServices); @Override synchronized List<RegionPlan> balanceCluster(Map<ServerName, List<HRegionInfo>> clusterState); }### Answer: @Test public void testKeepRegionLoad() throws Exception { ServerName sn = ServerName.valueOf("test:8080", 100); int numClusterStatusToAdd = 20000; for (int i = 0; i < numClusterStatusToAdd; i++) { ServerLoad sl = mock(ServerLoad.class); RegionLoad rl = mock(RegionLoad.class); when(rl.getStores()).thenReturn(i); Map<byte[], RegionLoad> regionLoadMap = new TreeMap<byte[], RegionLoad>(Bytes.BYTES_COMPARATOR); regionLoadMap.put(Bytes.toBytes(REGION_KEY), rl); when(sl.getRegionsLoad()).thenReturn(regionLoadMap); ClusterStatus clusterStatus = mock(ClusterStatus.class); when(clusterStatus.getServers()).thenReturn(Arrays.asList(sn)); when(clusterStatus.getLoad(sn)).thenReturn(sl); loadBalancer.setClusterStatus(clusterStatus); } assertTrue(loadBalancer.loads.get(REGION_KEY) != null); assertTrue(loadBalancer.loads.get(REGION_KEY).size() == 15); Queue<RegionLoad> loads = loadBalancer.loads.get(REGION_KEY); int i = 0; while(loads.size() > 0) { RegionLoad rl = loads.remove(); assertEquals(i + (numClusterStatusToAdd - 15), rl.getStores()); i ++; } }
### Question: DeadServer { public synchronized boolean areDeadServersInProgress() { return processing; } synchronized boolean cleanPreviousInstance(final ServerName newServerName); synchronized boolean isDeadServer(final ServerName serverName); synchronized boolean areDeadServersInProgress(); synchronized Set<ServerName> copyServerNames(); synchronized void add(ServerName sn); synchronized void notifyServer(ServerName sn); synchronized void finish(ServerName sn); synchronized int size(); synchronized boolean isEmpty(); synchronized void cleanAllPreviousInstances(final ServerName newServerName); synchronized String toString(); synchronized List<Pair<ServerName, Long>> copyDeadServersSince(long ts); synchronized Date getTimeOfDeath(final ServerName deadServerName); }### Answer: @Test(timeout = 15000) public void testCrashProcedureReplay() { HMaster master = TEST_UTIL.getHBaseCluster().getMaster(); ProcedureExecutor pExecutor = master.getMasterProcedureExecutor(); ServerCrashProcedure proc = new ServerCrashProcedure(hostname123, false, false); ProcedureTestingUtility.submitAndWait(pExecutor, proc); assertFalse(master.getServerManager().getDeadServers().areDeadServersInProgress()); }
### Question: SplitLogManager { public long splitLogDistributed(final Path logDir) throws IOException { List<Path> logDirs = new ArrayList<Path>(); logDirs.add(logDir); return splitLogDistributed(logDirs); } SplitLogManager(Server server, Configuration conf, Stoppable stopper, MasterServices master, ServerName serverName); @VisibleForTesting static FileStatus[] getFileList(final Configuration conf, final List<Path> logDirs, final PathFilter filter); long splitLogDistributed(final Path logDir); long splitLogDistributed(final List<Path> logDirs); long splitLogDistributed(final Set<ServerName> serverNames, final List<Path> logDirs, PathFilter filter); void stop(); void setRecoveryMode(boolean isForInitialization); void markRegionsRecovering(ServerName server, Set<HRegionInfo> userRegions); boolean isLogReplaying(); boolean isLogSplitting(); RecoveryMode getRecoveryMode(); static final int DEFAULT_UNASSIGNED_TIMEOUT; }### Answer: @Test (timeout=180000) public void testEmptyLogDir() throws Exception { LOG.info("testEmptyLogDir"); slm = new SplitLogManager(ds, conf, stopper, master, DUMMY_MASTER); FileSystem fs = TEST_UTIL.getTestFileSystem(); Path emptyLogDirPath = new Path(fs.getWorkingDirectory(), UUID.randomUUID().toString()); fs.mkdirs(emptyLogDirPath); slm.splitLogDistributed(emptyLogDirPath); assertFalse(fs.exists(emptyLogDirPath)); }
### Question: StealJobQueue extends PriorityBlockingQueue<T> { @Override public T take() throws InterruptedException { lock.lockInterruptibly(); try { while (true) { T retVal = this.poll(); if (retVal == null) { retVal = stealFromQueue.poll(); } if (retVal == null) { notEmpty.await(); } else { return retVal; } } } finally { lock.unlock(); } } StealJobQueue(); BlockingQueue<T> getStealFromQueue(); @Override boolean offer(T t); @Override T take(); @Override T poll(long timeout, TimeUnit unit); }### Answer: @Test public void testTake() throws InterruptedException { stealJobQueue.offer(3); stealFromQueue.offer(10); stealJobQueue.offer(15); stealJobQueue.offer(4); assertEquals(3, stealJobQueue.take().intValue()); assertEquals(4, stealJobQueue.take().intValue()); assertEquals("always take from the main queue before trying to steal", 15, stealJobQueue.take().intValue()); assertEquals(10, stealJobQueue.take().intValue()); assertTrue(stealFromQueue.isEmpty()); assertTrue(stealJobQueue.isEmpty()); }
### Question: ServerNonceManager { public void endOperation(long group, long nonce, boolean success) { if (nonce == HConstants.NO_NONCE) return; NonceKey nk = new NonceKey(group, nonce); OperationContext newResult = nonces.get(nk); assert newResult != null; synchronized (newResult) { assert newResult.getState() == OperationContext.WAIT; newResult.setState(success ? OperationContext.DONT_PROCEED : OperationContext.PROCEED); if (success) { newResult.reportActivity(); } else { OperationContext val = nonces.remove(nk); assert val == newResult; } if (newResult.hasWait()) { LOG.debug("Conflict with running op ended: " + nk + ", " + newResult); newResult.notifyAll(); } } } ServerNonceManager(Configuration conf); @VisibleForTesting void setConflictWaitIterationMs(int conflictWaitIterationMs); boolean startOperation(long group, long nonce, Stoppable stoppable); void endOperation(long group, long nonce, boolean success); void reportOperationFromWal(long group, long nonce, long writeTime); ScheduledChore createCleanupScheduledChore(Stoppable stoppable); static final String HASH_NONCE_GRACE_PERIOD_KEY; }### Answer: @Test public void testNoEndWithoutStart() { ServerNonceManager nm = createManager(); try { nm.endOperation(NO_NONCE, 1, true); fail("Should have thrown"); } catch (AssertionError err) {} }
### Question: RegionSplitPolicy extends Configured { protected byte[] getSplitPoint() { byte[] explicitSplitPoint = this.region.getExplicitSplitPoint(); if (explicitSplitPoint != null) { return explicitSplitPoint; } List<Store> stores = region.getStores(); byte[] splitPointFromLargestStore = null; long largestStoreSize = 0; for (Store s : stores) { byte[] splitPoint = s.getSplitPoint(); long storeSize = s.getSize(); if (splitPoint != null && largestStoreSize < storeSize) { splitPointFromLargestStore = splitPoint; largestStoreSize = storeSize; } } return splitPointFromLargestStore; } static RegionSplitPolicy create(HRegion region, Configuration conf); static Class<? extends RegionSplitPolicy> getSplitPolicyClass( HTableDescriptor htd, Configuration conf); }### Answer: @Test public void testGetSplitPoint() throws IOException { ConstantSizeRegionSplitPolicy policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create(mockRegion, conf); assertFalse(policy.shouldSplit()); assertNull(policy.getSplitPoint()); HStore mockStore = Mockito.mock(HStore.class); Mockito.doReturn(2000L).when(mockStore).getSize(); Mockito.doReturn(true).when(mockStore).canSplit(); Mockito.doReturn(Bytes.toBytes("store 1 split")) .when(mockStore).getSplitPoint(); stores.add(mockStore); assertEquals("store 1 split", Bytes.toString(policy.getSplitPoint())); HStore mockStore2 = Mockito.mock(HStore.class); Mockito.doReturn(4000L).when(mockStore2).getSize(); Mockito.doReturn(true).when(mockStore2).canSplit(); Mockito.doReturn(Bytes.toBytes("store 2 split")) .when(mockStore2).getSplitPoint(); stores.add(mockStore2); assertEquals("store 2 split", Bytes.toString(policy.getSplitPoint())); }
### Question: MetricsWAL extends WALActionsListener.Base { @Override public void logRollRequested(boolean underReplicated) { source.incrementLogRollRequested(); if (underReplicated) { source.incrementLowReplicationLogRoll(); } } MetricsWAL(); @VisibleForTesting MetricsWAL(MetricsWALSource s); @Override void postSync(final long timeInNanos, final int handlerSyncs); @Override void postAppend(final long size, final long time); @Override void logRollRequested(boolean underReplicated); }### Answer: @Test public void testLogRollRequested() throws Exception { MetricsWALSource source = mock(MetricsWALSourceImpl.class); MetricsWAL metricsWAL = new MetricsWAL(source); metricsWAL.logRollRequested(false); metricsWAL.logRollRequested(true); verify(source, times(2)).incrementLogRollRequested(); verify(source, times(1)).incrementLowReplicationLogRoll(); }
### Question: MetricsWAL extends WALActionsListener.Base { @Override public void postSync(final long timeInNanos, final int handlerSyncs) { source.incrementSyncTime(timeInNanos/1000000L); } MetricsWAL(); @VisibleForTesting MetricsWAL(MetricsWALSource s); @Override void postSync(final long timeInNanos, final int handlerSyncs); @Override void postAppend(final long size, final long time); @Override void logRollRequested(boolean underReplicated); }### Answer: @Test public void testPostSync() throws Exception { long nanos = TimeUnit.MILLISECONDS.toNanos(145); MetricsWALSource source = mock(MetricsWALSourceImpl.class); MetricsWAL metricsWAL = new MetricsWAL(source); metricsWAL.postSync(nanos, 1); verify(source, times(1)).incrementSyncTime(145); }
### Question: StealJobQueue extends PriorityBlockingQueue<T> { public BlockingQueue<T> getStealFromQueue() { return stealFromQueue; } StealJobQueue(); BlockingQueue<T> getStealFromQueue(); @Override boolean offer(T t); @Override T take(); @Override T poll(long timeout, TimeUnit unit); }### Answer: @Test public void testInteractWithThreadPool() throws InterruptedException { StealJobQueue<Runnable> stealTasksQueue = new StealJobQueue<>(); final CountDownLatch stealJobCountDown = new CountDownLatch(3); final CountDownLatch stealFromCountDown = new CountDownLatch(3); ThreadPoolExecutor stealPool = new ThreadPoolExecutor(3, 3, 1, TimeUnit.DAYS, stealTasksQueue) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); stealJobCountDown.countDown(); } }; stealPool.prestartAllCoreThreads(); ThreadPoolExecutor stealFromPool = new ThreadPoolExecutor(3, 3, 1, TimeUnit.DAYS, stealTasksQueue.getStealFromQueue()) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); stealFromCountDown.countDown(); } }; for (int i = 0; i < 4; i++) { TestTask task = new TestTask(); stealFromPool.execute(task); } for (int i = 0; i < 2; i++) { TestTask task = new TestTask(); stealPool.execute(task); } stealJobCountDown.await(1, TimeUnit.SECONDS); stealFromCountDown.await(1, TimeUnit.SECONDS); assertEquals(0, stealFromCountDown.getCount()); assertEquals(0, stealJobCountDown.getCount()); }
### Question: SequenceIdAccounting { byte[][] findLower(Map<byte[], Long> sequenceids) { List<byte[]> toFlush = null; synchronized (tieLock) { for (Map.Entry<byte[], Long> e: sequenceids.entrySet()) { Map<byte[], Long> m = this.lowestUnflushedSequenceIds.get(e.getKey()); if (m == null) continue; long lowest = getLowestSequenceId(m); if (lowest != HConstants.NO_SEQNUM && lowest <= e.getValue()) { if (toFlush == null) toFlush = new ArrayList<byte[]>(); toFlush.add(e.getKey()); } } } return toFlush == null? null: toFlush.toArray(new byte[][] { HConstants.EMPTY_BYTE_ARRAY }); } }### Answer: @Test public void testFindLower() { SequenceIdAccounting sida = new SequenceIdAccounting(); sida.getOrCreateLowestSequenceIds(ENCODED_REGION_NAME); Map<byte[], Long> m = new HashMap<byte[], Long>(); m.put(ENCODED_REGION_NAME, HConstants.NO_SEQNUM); long sequenceid = 1; sida.update(ENCODED_REGION_NAME, FAMILIES, sequenceid, true); sida.update(ENCODED_REGION_NAME, FAMILIES, sequenceid++, true); sida.update(ENCODED_REGION_NAME, FAMILIES, sequenceid++, true); assertTrue(sida.findLower(m) == null); m.put(ENCODED_REGION_NAME, sida.getLowestSequenceId(ENCODED_REGION_NAME)); assertTrue(sida.findLower(m).length == 1); m.put(ENCODED_REGION_NAME, sida.getLowestSequenceId(ENCODED_REGION_NAME) - 1); assertTrue(sida.findLower(m) == null); }
### Question: IdLock { void assertMapEmpty() { assert map.size() == 0; } Entry getLockEntry(long id); void releaseLockEntry(Entry entry); @VisibleForTesting void waitForWaiters(long id, int numWaiters); }### Answer: @Test public void testMultipleClients() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); try { ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(exec); for (int i = 0; i < NUM_THREADS; ++i) ecs.submit(new IdLockTestThread("client_" + i)); for (int i = 0; i < NUM_THREADS; ++i) { Future<Boolean> result = ecs.take(); assertTrue(result.get()); } idLock.assertMapEmpty(); } finally { exec.shutdown(); exec.awaitTermination(5000, TimeUnit.MILLISECONDS); } }
### Question: SnapshotManifest { public static SnapshotManifest open(final Configuration conf, final FileSystem fs, final Path workingDir, final SnapshotDescription desc) throws IOException { SnapshotManifest manifest = new SnapshotManifest(conf, fs, workingDir, desc, null); manifest.load(); return manifest; } private SnapshotManifest(final Configuration conf, final FileSystem fs, final Path workingDir, final SnapshotDescription desc, final ForeignExceptionSnare monitor); static SnapshotManifest create(final Configuration conf, final FileSystem fs, final Path workingDir, final SnapshotDescription desc, final ForeignExceptionSnare monitor); static SnapshotManifest open(final Configuration conf, final FileSystem fs, final Path workingDir, final SnapshotDescription desc); void addTableDescriptor(final HTableDescriptor htd); void addRegion(final HRegion region); void addRegion(final Path tableDir, final HRegionInfo regionInfo); Path getSnapshotDir(); SnapshotDescription getSnapshotDescription(); HTableDescriptor getTableDescriptor(); List<SnapshotRegionManifest> getRegionManifests(); Map<String, SnapshotRegionManifest> getRegionManifestsMap(); void consolidate(); static ThreadPoolExecutor createExecutor(final Configuration conf, final String name); static final String SNAPSHOT_MANIFEST_SIZE_LIMIT_CONF_KEY; static final String DATA_MANIFEST_NAME; }### Answer: @Test public void testReadSnapshotManifest() throws IOException { try { SnapshotManifest.open(conf, fs, snapshotDir, snapshotDesc); fail("fail to test snapshot manifest because message size is too small."); } catch (InvalidProtocolBufferException ipbe) { try { conf.setInt(SnapshotManifest.SNAPSHOT_MANIFEST_SIZE_LIMIT_CONF_KEY, 128 * 1024 * 1024); SnapshotManifest.open(conf, fs, snapshotDir, snapshotDesc); LOG.info("open snapshot manifest succeed."); } catch (InvalidProtocolBufferException ipbe2) { fail("fail to take snapshot because Manifest proto-message too large."); } } }
### Question: JMXListener implements Coprocessor { @Override public void stop(CoprocessorEnvironment env) throws IOException { stopConnectorServer(); } static JMXServiceURL buildJMXServiceURL(int rmiRegistryPort, int rmiConnectorPort); void startConnectorServer(int rmiRegistryPort, int rmiConnectorPort); void stopConnectorServer(); @Override void start(CoprocessorEnvironment env); @Override void stop(CoprocessorEnvironment env); static final String RMI_REGISTRY_PORT_CONF_KEY; static final String RMI_CONNECTOR_PORT_CONF_KEY; static final int defMasterRMIRegistryPort; static final int defRegionserverRMIRegistryPort; }### Answer: @Test public void testStop() throws Exception { MiniHBaseCluster cluster = UTIL.getHBaseCluster(); LOG.info("shutdown hbase cluster..."); cluster.shutdown(); LOG.info("wait for the hbase cluster shutdown..."); cluster.waitUntilShutDown(); JMXConnector connector = JMXConnectorFactory.newJMXConnector( JMXListener.buildJMXServiceURL(connectorPort,connectorPort), null); expectedEx.expect(IOException.class); connector.connect(); }
### Question: KeyLocker { public ReentrantLock acquireLock(K key) { if (key == null) throw new IllegalArgumentException("key must not be null"); lockPool.purge(); ReentrantLock lock = lockPool.get(key); lock.lock(); return lock; } ReentrantLock acquireLock(K key); Map<K, Lock> acquireLocks(Set<? extends K> keys); }### Answer: @Test public void testLocker(){ KeyLocker<String> locker = new KeyLocker<String>(); ReentrantLock lock1 = locker.acquireLock("l1"); Assert.assertTrue(lock1.isHeldByCurrentThread()); ReentrantLock lock2 = locker.acquireLock("l2"); Assert.assertTrue(lock2.isHeldByCurrentThread()); Assert.assertTrue(lock1 != lock2); ReentrantLock lock20 = locker.acquireLock("l2"); Assert.assertTrue(lock20 == lock2); Assert.assertTrue(lock2.isHeldByCurrentThread()); Assert.assertTrue(lock20.isHeldByCurrentThread()); lock20.unlock(); Assert.assertTrue(lock20.isHeldByCurrentThread()); lock2.unlock(); Assert.assertFalse(lock20.isHeldByCurrentThread()); int lock2Hash = System.identityHashCode(lock2); lock2 = null; lock20 = null; System.gc(); System.gc(); System.gc(); ReentrantLock lock200 = locker.acquireLock("l2"); Assert.assertNotEquals(lock2Hash, System.identityHashCode(lock200)); lock200.unlock(); Assert.assertFalse(lock200.isHeldByCurrentThread()); Assert.assertTrue(lock1.isHeldByCurrentThread()); lock1.unlock(); Assert.assertFalse(lock1.isHeldByCurrentThread()); }
### Question: SimpleMutableByteRange extends AbstractByteRange { @Override public boolean equals(Object thatObject) { if (thatObject == null) { return false; } if (this == thatObject) { return true; } if (hashCode() != thatObject.hashCode()) { return false; } if (!(thatObject instanceof SimpleMutableByteRange)) { return false; } SimpleMutableByteRange that = (SimpleMutableByteRange) thatObject; return Bytes.equals(bytes, offset, length, that.bytes, that.offset, that.length); } SimpleMutableByteRange(); SimpleMutableByteRange(int capacity); SimpleMutableByteRange(byte[] bytes); SimpleMutableByteRange(byte[] bytes, int offset, int length); @Override ByteRange unset(); @Override ByteRange put(int index, byte val); @Override ByteRange put(int index, byte[] val); @Override ByteRange put(int index, byte[] val, int offset, int length); @Override ByteRange putShort(int index, short val); @Override ByteRange putInt(int index, int val); @Override ByteRange putLong(int index, long val); @Override int putVLong(int index, long val); @Override ByteRange deepCopy(); @Override ByteRange shallowCopy(); @Override ByteRange shallowCopySubRange(int innerOffset, int copyLength); @Override boolean equals(Object thatObject); }### Answer: @Test public void testEmpty(){ Assert.assertTrue(SimpleMutableByteRange.isEmpty(null)); ByteRange r = new SimpleMutableByteRange(); Assert.assertTrue(SimpleMutableByteRange.isEmpty(r)); Assert.assertTrue(r.isEmpty()); r.set(new byte[0]); Assert.assertEquals(0, r.getBytes().length); Assert.assertEquals(0, r.getOffset()); Assert.assertEquals(0, r.getLength()); Assert.assertTrue(Bytes.equals(new byte[0], r.deepCopyToNewArray())); Assert.assertEquals(0, r.compareTo(new SimpleMutableByteRange(new byte[0], 0, 0))); Assert.assertEquals(0, r.hashCode()); }
### Question: AES extends Cipher { @VisibleForTesting SecureRandom getRNG() { return rng; } AES(CipherProvider provider); @Override String getName(); @Override int getKeyLength(); @Override int getIvLength(); @Override Key getRandomKey(); @Override Encryptor getEncryptor(); @Override Decryptor getDecryptor(); @Override OutputStream createEncryptionStream(OutputStream out, Context context, byte[] iv); @Override OutputStream createEncryptionStream(OutputStream out, Encryptor e); @Override InputStream createDecryptionStream(InputStream in, Context context, byte[] iv); @Override InputStream createDecryptionStream(InputStream in, Decryptor d); static final int KEY_LENGTH; static final int KEY_LENGTH_BITS; static final int BLOCK_SIZE; static final int IV_LENGTH; static final String CIPHER_MODE_KEY; static final String CIPHER_PROVIDER_KEY; static final String RNG_ALGORITHM_KEY; static final String RNG_PROVIDER_KEY; }### Answer: @Test public void testAlternateRNG() throws Exception { Security.addProvider(new TestProvider()); Configuration conf = new Configuration(); conf.set(AES.RNG_ALGORITHM_KEY, "TestRNG"); conf.set(AES.RNG_PROVIDER_KEY, "TEST"); DefaultCipherProvider.getInstance().setConf(conf); AES aes = new AES(DefaultCipherProvider.getInstance()); assertEquals("AES did not find alternate RNG", aes.getRNG().getAlgorithm(), "TestRNG"); }
### Question: BoundedByteBufferPool { public void putBuffer(ByteBuffer bb) { if (bb.capacity() > this.maxByteBufferSizeToCache) return; boolean success = false; int average = 0; lock.lock(); try { success = this.buffers.offer(bb); if (success) { this.totalReservoirCapacity += bb.capacity(); average = this.totalReservoirCapacity / this.buffers.size(); } } finally { lock.unlock(); } if (!success) { LOG.warn("At capacity: " + this.buffers.size()); } else { if (average > this.runningAverage && average < this.maxByteBufferSizeToCache) { this.runningAverage = average; } } } BoundedByteBufferPool(final int maxByteBufferSizeToCache, final int initialByteBufferSize, final int maxToCache); ByteBuffer getBuffer(); void putBuffer(ByteBuffer bb); }### Answer: @Test public void testEquivalence() { ByteBuffer bb = ByteBuffer.allocate(1); this.reservoir.putBuffer(bb); this.reservoir.putBuffer(bb); this.reservoir.putBuffer(bb); assertEquals(3, this.reservoir.buffers.size()); }
### Question: ChoreService implements ChoreServicer { @Override public synchronized void cancelChore(ScheduledChore chore) { cancelChore(chore, true); } @VisibleForTesting ChoreService(final String coreThreadPoolPrefix); ChoreService(final String coreThreadPoolPrefix, final boolean jitter); ChoreService(final String coreThreadPoolPrefix, int corePoolSize, boolean jitter); static ChoreService getInstance(final String coreThreadPoolPrefix); synchronized boolean scheduleChore(ScheduledChore chore); @Override synchronized void cancelChore(ScheduledChore chore); @Override synchronized void cancelChore(ScheduledChore chore, boolean mayInterruptIfRunning); @Override synchronized boolean isChoreScheduled(ScheduledChore chore); @Override synchronized boolean triggerNow(ScheduledChore chore); @Override synchronized void onChoreMissedStartTime(ScheduledChore chore); synchronized void shutdown(); boolean isShutdown(); boolean isTerminated(); final static int MIN_CORE_POOL_SIZE; }### Answer: @Test (timeout=20000) public void testCancelChore() throws InterruptedException { final int period = 100; ScheduledChore chore1 = new DoNothingChore("chore1", period); ChoreService service = ChoreService.getInstance("testCancelChore"); try { service.scheduleChore(chore1); assertTrue(chore1.isScheduled()); chore1.cancel(true); assertFalse(chore1.isScheduled()); assertTrue(service.getNumberOfScheduledChores() == 0); } finally { shutdownService(service); } }
### Question: ChoreService implements ChoreServicer { int getCorePoolSize() { return scheduler.getCorePoolSize(); } @VisibleForTesting ChoreService(final String coreThreadPoolPrefix); ChoreService(final String coreThreadPoolPrefix, final boolean jitter); ChoreService(final String coreThreadPoolPrefix, int corePoolSize, boolean jitter); static ChoreService getInstance(final String coreThreadPoolPrefix); synchronized boolean scheduleChore(ScheduledChore chore); @Override synchronized void cancelChore(ScheduledChore chore); @Override synchronized void cancelChore(ScheduledChore chore, boolean mayInterruptIfRunning); @Override synchronized boolean isChoreScheduled(ScheduledChore chore); @Override synchronized boolean triggerNow(ScheduledChore chore); @Override synchronized void onChoreMissedStartTime(ScheduledChore chore); synchronized void shutdown(); boolean isShutdown(); boolean isTerminated(); final static int MIN_CORE_POOL_SIZE; }### Answer: @Test (timeout=20000) public void testChoreServiceConstruction() throws InterruptedException { final int corePoolSize = 10; final int defaultCorePoolSize = ChoreService.MIN_CORE_POOL_SIZE; ChoreService customInit = new ChoreService("testChoreServiceConstruction_custom", corePoolSize, false); try { assertEquals(corePoolSize, customInit.getCorePoolSize()); } finally { shutdownService(customInit); } ChoreService defaultInit = new ChoreService("testChoreServiceConstruction_default"); try { assertEquals(defaultCorePoolSize, defaultInit.getCorePoolSize()); } finally { shutdownService(defaultInit); } ChoreService invalidInit = new ChoreService("testChoreServiceConstruction_invalid", -10, false); try { assertEquals(defaultCorePoolSize, invalidInit.getCorePoolSize()); } finally { shutdownService(invalidInit); } }
### Question: ZKConfig { public static Properties makeZKProps(Configuration conf) { Properties zkProperties = makeZKPropsFromZooCfg(conf); if (zkProperties == null) { zkProperties = makeZKPropsFromHbaseConfig(conf); } return zkProperties; } private ZKConfig(); static Properties makeZKProps(Configuration conf); @Deprecated static Properties parseZooCfg(Configuration conf, InputStream inputStream); static String getZKQuorumServersString(Configuration conf); static String buildZKQuorumServerString(String[] serverHosts, String clientPort); static void validateClusterKey(String key); static ZKClusterKey transformClusterKey(String key); static String getZooKeeperClusterKey(Configuration conf); static String getZooKeeperClusterKey(Configuration conf, String name); @VisibleForTesting static String standardizeZKQuorumServerString(String quorumStringInput, String clientPort); }### Answer: @Test public void testZKConfigLoading() throws Exception { Configuration conf = HBaseConfiguration.create(); conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, 2181); Properties props = ZKConfig.makeZKProps(conf); assertEquals("Property client port should have been default from the HBase config", "2181", props.getProperty("clientPort")); }
### Question: ZKConfig { public static String getZooKeeperClusterKey(Configuration conf) { return getZooKeeperClusterKey(conf, null); } private ZKConfig(); static Properties makeZKProps(Configuration conf); @Deprecated static Properties parseZooCfg(Configuration conf, InputStream inputStream); static String getZKQuorumServersString(Configuration conf); static String buildZKQuorumServerString(String[] serverHosts, String clientPort); static void validateClusterKey(String key); static ZKClusterKey transformClusterKey(String key); static String getZooKeeperClusterKey(Configuration conf); static String getZooKeeperClusterKey(Configuration conf, String name); @VisibleForTesting static String standardizeZKQuorumServerString(String quorumStringInput, String clientPort); }### Answer: @Test public void testGetZooKeeperClusterKey() { Configuration conf = HBaseConfiguration.create(); conf.set(HConstants.ZOOKEEPER_QUORUM, "\tlocalhost\n"); conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, "3333"); conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "hbase"); String clusterKey = ZKConfig.getZooKeeperClusterKey(conf, "test"); assertTrue(!clusterKey.contains("\t") && !clusterKey.contains("\n")); assertEquals("localhost:3333:hbase,test", clusterKey); }
### Question: ZKConfig { public static void validateClusterKey(String key) throws IOException { transformClusterKey(key); } private ZKConfig(); static Properties makeZKProps(Configuration conf); @Deprecated static Properties parseZooCfg(Configuration conf, InputStream inputStream); static String getZKQuorumServersString(Configuration conf); static String buildZKQuorumServerString(String[] serverHosts, String clientPort); static void validateClusterKey(String key); static ZKClusterKey transformClusterKey(String key); static String getZooKeeperClusterKey(Configuration conf); static String getZooKeeperClusterKey(Configuration conf, String name); @VisibleForTesting static String standardizeZKQuorumServerString(String quorumStringInput, String clientPort); }### Answer: @Test public void testClusterKey() throws Exception { testKey("server", 2181, "hbase"); testKey("server1,server2,server3", 2181, "hbase"); try { ZKConfig.validateClusterKey("2181:hbase"); } catch (IOException ex) { } }
### Question: FixedLengthWrapper implements DataType<T> { @Override public T decode(PositionedByteRange src) { if (src.getRemaining() < length) { throw new IllegalArgumentException("Not enough buffer remaining. src.offset: " + src.getOffset() + " src.length: " + src.getLength() + " src.position: " + src.getPosition() + " max length: " + length); } PositionedByteRange b = new SimplePositionedMutableByteRange(length); src.get(b.getBytes()); return base.decode(b); } FixedLengthWrapper(DataType<T> base, int length); int getLength(); @Override boolean isOrderPreserving(); @Override Order getOrder(); @Override boolean isNullable(); @Override boolean isSkippable(); @Override int encodedLength(T val); @Override Class<T> encodedClass(); @Override int skip(PositionedByteRange src); @Override T decode(PositionedByteRange src); @Override int encode(PositionedByteRange dst, T val); }### Answer: @Test(expected = IllegalArgumentException.class) public void testInsufficientRemainingRead() { PositionedByteRange buff = new SimplePositionedMutableByteRange(0); DataType<byte[]> type = new FixedLengthWrapper<byte[]>(new RawBytes(), 3); type.decode(buff); }
### Question: TimeoutBlockingQueue { public TimeoutBlockingQueue(TimeoutRetriever<? super E> timeoutRetriever) { this(32, timeoutRetriever); } TimeoutBlockingQueue(TimeoutRetriever<? super E> timeoutRetriever); @SuppressWarnings("unchecked") TimeoutBlockingQueue(int capacity, TimeoutRetriever<? super E> timeoutRetriever); void dump(); void clear(); void add(E e); @edu.umd.cs.findbugs.annotations.SuppressWarnings("WA_AWAIT_NOT_IN_LOOP") E poll(); int size(); boolean isEmpty(); void signalAll(); }### Answer: @Test public void testTimeoutBlockingQueue() { TimeoutBlockingQueue<TestObject> queue; int[][] testArray = new int[][] { {200, 400, 600}, {200, 400, 100}, {200, 400, 300}, }; for (int i = 0; i < testArray.length; ++i) { int[] sortedArray = Arrays.copyOf(testArray[i], testArray[i].length); Arrays.sort(sortedArray); queue = new TimeoutBlockingQueue<TestObject>(2, new TestObjectTimeoutRetriever()); for (int j = 0; j < testArray[i].length; ++j) { queue.add(new TestObject(j, testArray[i][j])); queue.dump(); } for (int j = 0; !queue.isEmpty(); ++j) { assertEquals(sortedArray[j], queue.poll().getTimeout()); } queue = new TimeoutBlockingQueue<TestObject>(2, new TestObjectTimeoutRetriever()); queue.add(new TestObject(0, 50)); assertEquals(50, queue.poll().getTimeout()); for (int j = 0; j < testArray[i].length; ++j) { queue.add(new TestObject(j, testArray[i][j])); queue.dump(); } for (int j = 0; !queue.isEmpty(); ++j) { assertEquals(sortedArray[j], queue.poll().getTimeout()); } } }
### Question: ProcedureStoreTracker { public boolean isTracking(long minId, long maxId) { return map.floorEntry(minId) != null || map.floorEntry(maxId) != null; } void insert(long procId); void insert(final long procId, final long[] subProcIds); void update(long procId); void delete(long procId); long getUpdatedMinProcId(); long getUpdatedMaxProcId(); @InterfaceAudience.Private void setDeleted(final long procId, final boolean isDeleted); void reset(); DeleteState isDeleted(long procId); long getMinProcId(); void setKeepDeletes(boolean keepDeletes); void setPartialFlag(boolean isPartial); boolean isEmpty(); boolean isUpdated(); boolean isTracking(long minId, long maxId); void resetUpdates(); void undeleteAll(); void dump(); void writeTo(final OutputStream stream); void readFrom(final InputStream stream); }### Answer: @Test public void testIsTracking() { long[][] procIds = new long[][] {{4, 7}, {1024, 1027}, {8192, 8194}}; long[][] checkIds = new long[][] {{2, 8}, {1023, 1025}, {8193, 8191}}; ProcedureStoreTracker tracker = new ProcedureStoreTracker(); for (int i = 0; i < procIds.length; ++i) { long[] seq = procIds[i]; tracker.insert(seq[0]); tracker.insert(seq[1]); } for (int i = 0; i < procIds.length; ++i) { long[] check = checkIds[i]; long[] seq = procIds[i]; assertTrue(tracker.isTracking(seq[0], seq[1])); assertTrue(tracker.isTracking(check[0], check[1])); tracker.delete(seq[0]); tracker.delete(seq[1]); assertFalse(tracker.isTracking(seq[0], seq[1])); assertFalse(tracker.isTracking(check[0], check[1])); } assertTrue(tracker.isEmpty()); }
### Question: ProcedureStoreTracker { public void delete(long procId) { Map.Entry<Long, BitSetNode> entry = map.floorEntry(procId); assert entry != null : "expected node to delete procId=" + procId; BitSetNode node = entry.getValue(); assert node.contains(procId) : "expected procId in the node"; node.delete(procId); if (!keepDeletes && node.isEmpty()) { map.remove(entry.getKey()); } trackProcIds(procId); } void insert(long procId); void insert(final long procId, final long[] subProcIds); void update(long procId); void delete(long procId); long getUpdatedMinProcId(); long getUpdatedMaxProcId(); @InterfaceAudience.Private void setDeleted(final long procId, final boolean isDeleted); void reset(); DeleteState isDeleted(long procId); long getMinProcId(); void setKeepDeletes(boolean keepDeletes); void setPartialFlag(boolean isPartial); boolean isEmpty(); boolean isUpdated(); boolean isTracking(long minId, long maxId); void resetUpdates(); void undeleteAll(); void dump(); void writeTo(final OutputStream stream); void readFrom(final InputStream stream); }### Answer: @Test public void testDelete() { final ProcedureStoreTracker tracker = new ProcedureStoreTracker(); long[] procIds = new long[] { 65, 1, 193 }; for (int i = 0; i < procIds.length; ++i) { tracker.insert(procIds[i]); tracker.dump(); } for (int i = 0; i < (64 * 4); ++i) { boolean hasProc = false; for (int j = 0; j < procIds.length; ++j) { if (procIds[j] == i) { hasProc = true; break; } } if (hasProc) { assertEquals(ProcedureStoreTracker.DeleteState.NO, tracker.isDeleted(i)); } else { assertEquals("procId=" + i, ProcedureStoreTracker.DeleteState.YES, tracker.isDeleted(i)); } } }
### Question: WALProcedureStore extends ProcedureStoreBase { @VisibleForTesting protected void periodicRollForTesting() throws IOException { lock.lock(); try { periodicRoll(); } finally { lock.unlock(); } } WALProcedureStore(final Configuration conf, final FileSystem fs, final Path logDir, final LeaseRecovery leaseRecovery); @Override void start(int numSlots); @Override void stop(boolean abort); @Override int getNumThreads(); ProcedureStoreTracker getStoreTracker(); ArrayList<ProcedureWALFile> getActiveLogs(); Set<ProcedureWALFile> getCorruptedLogs(); @Override void recoverLease(); @Override void load(final ProcedureLoader loader); @Override void insert(final Procedure proc, final Procedure[] subprocs); @Override void update(final Procedure proc); @Override void delete(final long procId); Path getLogDir(); FileSystem getFileSystem(); }### Answer: @Test public void testEmptyRoll() throws Exception { for (int i = 0; i < 10; ++i) { procStore.periodicRollForTesting(); } FileStatus[] status = fs.listStatus(logDir); assertEquals(1, status.length); }
### Question: ClientExceptionsUtil { public static Throwable findException(Object exception) { if (exception == null || !(exception instanceof Throwable)) { return null; } Throwable cur = (Throwable) exception; while (cur != null) { if (isSpecialException(cur)) { return cur; } if (cur instanceof RemoteException) { RemoteException re = (RemoteException) cur; cur = re.unwrapRemoteException( RegionOpeningException.class, RegionMovedException.class, RegionTooBusyException.class); if (cur == null) { cur = re.unwrapRemoteException(); } if (cur == re) { return cur; } } else if (cur.getCause() != null) { cur = cur.getCause(); } else { return cur; } } return null; } private ClientExceptionsUtil(); static boolean isMetaClearingException(Throwable cur); static boolean isSpecialException(Throwable cur); static Throwable findException(Object exception); }### Answer: @Test public void testFindException() throws Exception { IOException ioe = new IOException("Tesst"); ServiceException se = new ServiceException(ioe); assertEquals(ioe, ClientExceptionsUtil.findException(se)); }
### Question: LongComparator extends ByteArrayComparable { @Override public int compareTo(byte[] value, int offset, int length) { Long that = Bytes.toLong(value, offset, length); return this.longValue.compareTo(that); } LongComparator(long value); @Override int compareTo(byte[] value, int offset, int length); @Override byte [] toByteArray(); static LongComparator parseFrom(final byte [] pbBytes); }### Answer: @Test public void testSimple() { for (int i = 1; i < values.length ; i++) { for (int j = 0; j < i; j++) { LongComparator cp = new LongComparator(values[i]); assertEquals(1, cp.compareTo(Bytes.toBytes(values[j]))); } } }
### Question: IPCUtil { @SuppressWarnings("resource") public ByteBuffer buildCellBlock(final Codec codec, final CompressionCodec compressor, final CellScanner cellScanner) throws IOException { return buildCellBlock(codec, compressor, cellScanner, null); } IPCUtil(final Configuration conf); @SuppressWarnings("resource") ByteBuffer buildCellBlock(final Codec codec, final CompressionCodec compressor, final CellScanner cellScanner); @SuppressWarnings("resource") ByteBuffer buildCellBlock(final Codec codec, final CompressionCodec compressor, final CellScanner cellScanner, final BoundedByteBufferPool pool); CellScanner createCellScanner(final Codec codec, final CompressionCodec compressor, final byte [] cellBlock); CellScanner createCellScanner(final Codec codec, final CompressionCodec compressor, final byte [] cellBlock, final int offset, final int length); static ByteBuffer getDelimitedMessageAsByteBuffer(final Message m); static int write(final OutputStream dos, final Message header, final Message param, final ByteBuffer cellBlock); static void readChunked(final DataInput in, byte[] dest, int offset, int len); static int getTotalSizeWhenWrittenDelimited(Message ... messages); static final Log LOG; }### Answer: @Test public void testBuildCellBlock() throws IOException { doBuildCellBlockUndoCellBlock(this.util, new KeyValueCodec(), null); doBuildCellBlockUndoCellBlock(this.util, new KeyValueCodec(), new DefaultCodec()); doBuildCellBlockUndoCellBlock(this.util, new KeyValueCodec(), new GzipCodec()); }
### Question: PayloadCarryingRpcController extends TimeLimitedRpcController implements CellScannable { public CellScanner cellScanner() { return cellScanner; } PayloadCarryingRpcController(); PayloadCarryingRpcController(final CellScanner cellScanner); PayloadCarryingRpcController(final List<CellScannable> cellIterables); CellScanner cellScanner(); void setCellScanner(final CellScanner cellScanner); void setPriority(int priority); void setPriority(final TableName tn); int getPriority(); @Override void reset(); }### Answer: @Test public void testListOfCellScannerables() throws IOException { List<CellScannable> cells = new ArrayList<CellScannable>(); final int count = 10; for (int i = 0; i < count; i++) { cells.add(createCell(i)); } PayloadCarryingRpcController controller = new PayloadCarryingRpcController(cells); CellScanner cellScanner = controller.cellScanner(); int index = 0; for (; cellScanner.advance(); index++) { Cell cell = cellScanner.current(); byte [] indexBytes = Bytes.toBytes(index); assertTrue("" + index, Bytes.equals(indexBytes, 0, indexBytes.length, cell.getValueArray(), cell.getValueOffset(), cell.getValueLength())); } assertEquals(count, index); }
### Question: AsyncProcess { @VisibleForTesting void waitUntilDone() throws InterruptedIOException { waitForMaximumCurrentTasks(0); } AsyncProcess(ClusterConnection hc, Configuration conf, ExecutorService pool, RpcRetryingCallerFactory rpcCaller, boolean useGlobalErrors, RpcControllerFactory rpcFactory); AsyncRequestFuture submit(TableName tableName, List<? extends Row> rows, boolean atLeastOne, Batch.Callback<CResult> callback, boolean needResults); AsyncRequestFuture submit(ExecutorService pool, TableName tableName, List<? extends Row> rows, boolean atLeastOne, Batch.Callback<CResult> callback, boolean needResults); AsyncRequestFuture submitAll(TableName tableName, List<? extends Row> rows, Batch.Callback<CResult> callback, Object[] results); AsyncRequestFuture submitAll(ExecutorService pool, TableName tableName, List<? extends Row> rows, Batch.Callback<CResult> callback, Object[] results); boolean hasError(); RetriesExhaustedWithDetailsException waitForAllPreviousOpsAndReset( List<Row> failedRows); static final String PRIMARY_CALL_TIMEOUT_KEY; static final String START_LOG_ERRORS_AFTER_COUNT_KEY; static final int DEFAULT_START_LOG_ERRORS_AFTER_COUNT; }### Answer: @Test public void testHTableFailedPutAndNewPut() throws Exception { ClusterConnection conn = createHConnection(); BufferedMutatorImpl mutator = new BufferedMutatorImpl(conn, null, null, new BufferedMutatorParams(DUMMY_TABLE).writeBufferSize(0)); MyAsyncProcess ap = new MyAsyncProcess(conn, conf, true); mutator.ap = ap; Put p = createPut(1, false); mutator.mutate(p); ap.waitUntilDone(); p = createPut(1, true); Assert.assertEquals(0, mutator.getWriteBuffer().size()); try { mutator.mutate(p); Assert.fail(); } catch (RetriesExhaustedException expected) { } Assert.assertEquals("the put should not been inserted.", 0, mutator.getWriteBuffer().size()); }
### Question: DelayingRunner implements Runnable { public DelayingRunner(long sleepTime, Map.Entry<byte[], List<Action<T>>> e) { this.sleepTime = sleepTime; add(e); } DelayingRunner(long sleepTime, Map.Entry<byte[], List<Action<T>>> e); void setRunner(Runnable runner); @Override void run(); void add(Map.Entry<byte[], List<Action<T>>> e); MultiAction<T> getActions(); long getSleepTime(); }### Answer: @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testDelayingRunner() throws Exception{ MultiAction<Row> ma = new MultiAction<Row>(); ma.add(hri1.getRegionName(), new Action<Row>(new Put(DUMMY_BYTES_1), 0)); final AtomicLong endTime = new AtomicLong(); final long sleepTime = 1000; DelayingRunner runner = new DelayingRunner(sleepTime, ma.actions.entrySet().iterator().next()); runner.setRunner(new Runnable() { @Override public void run() { endTime.set(EnvironmentEdgeManager.currentTime()); } }); long startTime = EnvironmentEdgeManager.currentTime(); runner.run(); long delay = endTime.get() - startTime; assertTrue("DelayingRunner did not delay long enough", delay >= sleepTime); assertFalse("DelayingRunner delayed too long", delay > sleepTime + sleepTime*0.2); }
### Question: ClientScanner extends AbstractClientScanner { @Override public Result next() throws IOException { if (cache.size() == 0 && this.closed) { return null; } if (cache.size() == 0) { loadCache(); } if (cache.size() > 0) { return cache.poll(); } writeScanMetrics(); return null; } ClientScanner(final Configuration conf, final Scan scan, final TableName tableName, ClusterConnection connection, RpcRetryingCallerFactory rpcFactory, RpcControllerFactory controllerFactory, ExecutorService pool, int primaryOperationTimeout); @Override Result next(); @VisibleForTesting int getCacheSize(); @Override void close(); @Override boolean renewLease(); }### Answer: @Test (timeout = 30000) public void testExceptionsFromReplicasArePropagated() throws IOException { scan.setConsistency(Consistency.TIMELINE); rpcFactory = new MockRpcRetryingCallerFactory(conf); conf.set(RpcRetryingCallerFactory.CUSTOM_CALLER_CONF_KEY, MockRpcRetryingCallerFactory.class.getName()); when(clusterConn.locateRegion((TableName)any(), (byte[])any(), anyBoolean(), anyBoolean(), anyInt())).thenReturn(new RegionLocations(null, null, null)); try (MockClientScanner scanner = new MockClientScanner(conf, scan, TableName.valueOf("table"), clusterConn, rpcFactory, controllerFactory, pool, Integer.MAX_VALUE)) { Iterator<Result> iter = scanner.iterator(); while (iter.hasNext()) { iter.next(); } fail("Should have failed with RetriesExhaustedException"); } catch (RetriesExhaustedException expected) { } }
### Question: IdReadWriteLock { @VisibleForTesting int purgeAndGetEntryPoolSize() { gc(); Threads.sleep(200); lockPool.purge(); return lockPool.size(); } ReentrantReadWriteLock getLock(long id); @VisibleForTesting void waitForWaiters(long id, int numWaiters); }### Answer: @Test(timeout = 60000) public void testMultipleClients() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); try { ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(exec); for (int i = 0; i < NUM_THREADS; ++i) ecs.submit(new IdLockTestThread("client_" + i)); for (int i = 0; i < NUM_THREADS; ++i) { Future<Boolean> result = ecs.take(); assertTrue(result.get()); } int entryPoolSize = idLock.purgeAndGetEntryPoolSize(); LOG.debug("Size of entry pool after gc and purge: " + entryPoolSize); assertEquals(0, entryPoolSize); } finally { exec.shutdown(); exec.awaitTermination(5000, TimeUnit.MILLISECONDS); } }
### Question: ConnectionCache { ConnectionInfo getCurrentConnection() throws IOException { String userName = getEffectiveUser(); ConnectionInfo connInfo = connections.get(userName); if (connInfo == null || !connInfo.updateAccessTime()) { Lock lock = locker.acquireLock(userName); try { connInfo = connections.get(userName); if (connInfo == null) { UserGroupInformation ugi = realUser; if (!userName.equals(realUserName)) { ugi = UserGroupInformation.createProxyUser(userName, realUser); } User user = userProvider.create(ugi); Connection conn = ConnectionFactory.createConnection(conf, user); connInfo = new ConnectionInfo(conn, userName); connections.put(userName, connInfo); } } finally { lock.unlock(); } } return connInfo; } ConnectionCache(final Configuration conf, final UserProvider userProvider, final int cleanInterval, final int maxIdleTime); void setEffectiveUser(String user); String getEffectiveUser(); void shutdown(); Admin getAdmin(); Table getTable(String tableName); RegionLocator getRegionLocator(byte[] tableName); }### Answer: @Test public void testConnectionChore() throws Exception { UTIL.startMiniCluster(); ConnectionCache cache = new ConnectionCache(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration()), 1000, 5000); ConnectionCache.ConnectionInfo info = cache.getCurrentConnection(); assertEquals(false, info.connection.isClosed()); Thread.sleep(7000); assertEquals(true, info.connection.isClosed()); UTIL.shutdownMiniCluster(); }
### Question: RegionSizeCalculator { public long getRegionSize(byte[] regionId) { Long size = sizeMap.get(regionId); if (size == null) { LOG.debug("Unknown region:" + Arrays.toString(regionId)); return 0; } else { return size; } } @Deprecated RegionSizeCalculator(HTable table); RegionSizeCalculator(RegionLocator regionLocator, Admin admin); long getRegionSize(byte[] regionId); Map<byte[], Long> getRegionSizeMap(); }### Answer: @Test public void testLargeRegion() throws Exception { RegionLocator regionLocator = mockRegionLocator("largeRegion"); Admin admin = mockAdmin( mockServer( mockRegion("largeRegion", Integer.MAX_VALUE) ) ); RegionSizeCalculator calculator = new RegionSizeCalculator(regionLocator, admin); assertEquals(((long) Integer.MAX_VALUE) * megabyte, calculator.getRegionSize("largeRegion".getBytes())); }
### Question: FSVisitor { public static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor) throws IOException { FileStatus[] regions = FSUtils.listStatus(fs, tableDir, new FSUtils.RegionDirFilter(fs)); if (regions == null) { if (LOG.isTraceEnabled()) { LOG.trace("No regions under directory:" + tableDir); } return; } for (FileStatus region: regions) { visitRegionStoreFiles(fs, region.getPath(), visitor); } } private FSVisitor(); static void visitRegions(final FileSystem fs, final Path tableDir, final RegionVisitor visitor); static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor); static void visitRegionStoreFiles(final FileSystem fs, final Path regionDir, final StoreFileVisitor visitor); static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitRegionRecoveredEdits(final FileSystem fs, final Path regionDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor); }### Answer: @Test public void testVisitStoreFiles() throws IOException { final Set<String> regions = new HashSet<String>(); final Set<String> families = new HashSet<String>(); final Set<String> hfiles = new HashSet<String>(); FSVisitor.visitTableStoreFiles(fs, tableDir, new FSVisitor.StoreFileVisitor() { public void storeFile(final String region, final String family, final String hfileName) throws IOException { regions.add(region); families.add(family); hfiles.add(hfileName); } }); assertEquals(tableRegions, regions); assertEquals(tableFamilies, families); assertEquals(tableHFiles, hfiles); }
### Question: FSVisitor { public static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor) throws IOException { FileStatus[] regions = FSUtils.listStatus(fs, tableDir, new FSUtils.RegionDirFilter(fs)); if (regions == null) { if (LOG.isTraceEnabled()) { LOG.trace("No recoveredEdits regions under directory:" + tableDir); } return; } for (FileStatus region: regions) { visitRegionRecoveredEdits(fs, region.getPath(), visitor); } } private FSVisitor(); static void visitRegions(final FileSystem fs, final Path tableDir, final RegionVisitor visitor); static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor); static void visitRegionStoreFiles(final FileSystem fs, final Path regionDir, final StoreFileVisitor visitor); static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitRegionRecoveredEdits(final FileSystem fs, final Path regionDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor); }### Answer: @Test public void testVisitRecoveredEdits() throws IOException { final Set<String> regions = new HashSet<String>(); final Set<String> edits = new HashSet<String>(); FSVisitor.visitTableRecoveredEdits(fs, tableDir, new FSVisitor.RecoveredEditsVisitor() { public void recoveredEdits (final String region, final String logfile) throws IOException { regions.add(region); edits.add(logfile); } }); assertEquals(tableRegions, regions); assertEquals(recoveredEdits, edits); }
### Question: FileLink { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this.getClass().equals(obj.getClass())) { return Arrays.equals(this.locations, ((FileLink) obj).locations); } return false; } protected FileLink(); FileLink(Path originPath, Path... alternativePaths); FileLink(final Collection<Path> locations); Path[] getLocations(); @Override String toString(); boolean exists(final FileSystem fs); Path getAvailablePath(FileSystem fs); FileStatus getFileStatus(FileSystem fs); FSDataInputStream open(final FileSystem fs); FSDataInputStream open(final FileSystem fs, int bufferSize); static Path getBackReferencesDir(final Path storeDir, final String fileName); static String getBackReferenceFileName(final Path dirPath); static boolean isBackReferencesDir(final Path dirPath); @Override boolean equals(Object obj); @Override int hashCode(); static final String BACK_REFERENCES_DIRECTORY_PREFIX; }### Answer: @Test public void testEquals() { Path p1 = new Path("/p1"); Path p2 = new Path("/p2"); Path p3 = new Path("/p3"); assertEquals(new FileLink(), new FileLink()); assertEquals(new FileLink(p1), new FileLink(p1)); assertEquals(new FileLink(p1, p2), new FileLink(p1, p2)); assertEquals(new FileLink(p1, p2, p3), new FileLink(p1, p2, p3)); assertNotEquals(new FileLink(p1), new FileLink(p3)); assertNotEquals(new FileLink(p1, p2), new FileLink(p1)); assertNotEquals(new FileLink(p1, p2), new FileLink(p2)); assertNotEquals(new FileLink(p1, p2), new FileLink(p2, p1)); }
### Question: FileLink { @Override public int hashCode() { return Arrays.hashCode(locations); } protected FileLink(); FileLink(Path originPath, Path... alternativePaths); FileLink(final Collection<Path> locations); Path[] getLocations(); @Override String toString(); boolean exists(final FileSystem fs); Path getAvailablePath(FileSystem fs); FileStatus getFileStatus(FileSystem fs); FSDataInputStream open(final FileSystem fs); FSDataInputStream open(final FileSystem fs, int bufferSize); static Path getBackReferencesDir(final Path storeDir, final String fileName); static String getBackReferenceFileName(final Path dirPath); static boolean isBackReferencesDir(final Path dirPath); @Override boolean equals(Object obj); @Override int hashCode(); static final String BACK_REFERENCES_DIRECTORY_PREFIX; }### Answer: @Test public void testHashCode() { Path p1 = new Path("/p1"); Path p2 = new Path("/p2"); Path p3 = new Path("/p3"); assertEquals(new FileLink().hashCode(), new FileLink().hashCode()); assertEquals(new FileLink(p1).hashCode(), new FileLink(p1).hashCode()); assertEquals(new FileLink(p1, p2).hashCode(), new FileLink(p1, p2).hashCode()); assertEquals(new FileLink(p1, p2, p3).hashCode(), new FileLink(p1, p2, p3).hashCode()); assertNotEquals(new FileLink(p1).hashCode(), new FileLink(p3).hashCode()); assertNotEquals(new FileLink(p1, p2).hashCode(), new FileLink(p1).hashCode()); assertNotEquals(new FileLink(p1, p2).hashCode(), new FileLink(p2).hashCode()); assertNotEquals(new FileLink(p1, p2).hashCode(), new FileLink(p2, p1).hashCode()); }
### Question: LruCachedBlock implements HeapSize, Comparable<LruCachedBlock> { @Override public int hashCode() { return (int)(accessTime ^ (accessTime >>> 32)); } LruCachedBlock(BlockCacheKey cacheKey, Cacheable buf, long accessTime); LruCachedBlock(BlockCacheKey cacheKey, Cacheable buf, long accessTime, boolean inMemory); void access(long accessTime); long getCachedTime(); long heapSize(); @Override int compareTo(LruCachedBlock that); @Override int hashCode(); @Override boolean equals(Object obj); Cacheable getBuffer(); BlockCacheKey getCacheKey(); BlockPriority getPriority(); final static long PER_BLOCK_OVERHEAD; }### Answer: @Test public void testEquality() { assertEquals(block.hashCode(), blockEqual.hashCode()); assertNotEquals(block.hashCode(), blockNotEqual.hashCode()); assertEquals(block, blockEqual); assertNotEquals(block, blockNotEqual); }
### Question: BucketCache implements BlockCache, HeapSize { void stopWriterThreads() throws InterruptedException { for (WriterThread writerThread : writerThreads) { writerThread.disableWriter(); writerThread.interrupt(); writerThread.join(); } } BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes, int writerThreadNum, int writerQLen, String persistencePath); BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes, int writerThreadNum, int writerQLen, String persistencePath, int ioErrorsTolerationDuration); long getMaxSize(); String getIoEngine(); @Override void cacheBlock(BlockCacheKey cacheKey, Cacheable buf); @Override void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory, final boolean cacheDataInL1); void cacheBlockWithWait(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory, boolean wait); @Override Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat, boolean updateCacheMetrics); @Override boolean evictBlock(BlockCacheKey cacheKey); void logStats(); long getRealCacheSize(); @Override void shutdown(); @Override CacheStats getStats(); BucketAllocator getAllocator(); @Override long heapSize(); @Override long size(); @Override long getFreeSize(); @Override long getBlockCount(); @Override long getCurrentSize(); @Override int evictBlocksByHfileName(String hfileName); @Override Iterator<CachedBlock> iterator(); @Override BlockCache[] getBlockCaches(); static final int DEFAULT_ERROR_TOLERATION_DURATION; }### Answer: @Test public void testHeapSizeChanges() throws Exception { cache.stopWriterThreads(); CacheTestUtils.testHeapSizeChanges(cache, BLOCK_SIZE); }
### Question: Reference { public static Reference read(final FileSystem fs, final Path p) throws IOException { InputStream in = fs.open(p); try { in = in.markSupported()? in: new BufferedInputStream(in); int pblen = ProtobufUtil.lengthOfPBMagic(); in.mark(pblen); byte [] pbuf = new byte[pblen]; int read = in.read(pbuf); if (read != pblen) throw new IOException("read=" + read + ", wanted=" + pblen); if (ProtobufUtil.isPBMagicPrefix(pbuf)) return convert(FSProtos.Reference.parseFrom(in)); in.reset(); Reference r = new Reference(); DataInputStream dis = new DataInputStream(in); in = dis; r.readFields(dis); return r; } finally { in.close(); } } Reference(final byte [] splitRow, final Range fr); @Deprecated // Make this private when it comes time to let go of this constructor. // Needed by pb serialization. Reference(); static Reference createTopReference(final byte [] splitRow); static Reference createBottomReference(final byte [] splitRow); Range getFileRegion(); byte [] getSplitKey(); @Override String toString(); static boolean isTopFileRegion(final Range r); @Deprecated void readFields(DataInput in); Path write(final FileSystem fs, final Path p); static Reference read(final FileSystem fs, final Path p); FSProtos.Reference convert(); static Reference convert(final FSProtos.Reference r); @Override int hashCode(); boolean equals(Object o); }### Answer: @Test public void testParsingWritableReference() throws IOException { final String datafile = System.getProperty("test.build.classes", "target/test-classes") + File.separator + "a6a6562b777440fd9c34885428f5cb61.21e75333ada3d5bafb34bb918f29576c"; FileSystem fs = FileSystem.get(HTU.getConfiguration()); Reference.read(fs, new Path(datafile)); }
### Question: MetaMigrationConvertingToPB { static boolean isMetaTableUpdated(final HConnection hConnection) throws IOException { List<Result> results = MetaTableAccessor.fullScanOfMeta(hConnection); if (results == null || results.isEmpty()) { LOG.info("hbase:meta doesn't have any entries to update."); return true; } for (Result r : results) { byte[] value = r.getValue(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER); if (!isMigrated(value)) { return false; } } return true; } static long updateMetaIfNecessary(final MasterServices services); }### Answer: @Test public void testMetaUpdatedFlagInROOT() throws Exception { HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster(); boolean metaUpdated = MetaMigrationConvertingToPB. isMetaTableUpdated(master.getConnection()); assertEquals(true, metaUpdated); verifyMetaRowsAreUpdated(master.getConnection()); }
### Question: WsImportMojo extends AbstractJaxwsMojo { static String getActiveHttpProxy(Settings s) { String retVal = null; for (Proxy p : s.getProxies()) { if (p.isActive() && "http".equals(p.getProtocol())) { StringBuilder sb = new StringBuilder(); String user = p.getUsername(); String pwd = p.getPassword(); if (user != null) { sb.append(user); if (pwd != null) { sb.append(":"); sb.append(pwd); } sb.append("@"); } sb.append(p.getHost()); sb.append(":"); sb.append(p.getPort()); retVal = sb.toString().trim(); break; } } return retVal; } @Override void execute(); final File[] getBindingFiles(); }### Answer: @Test public void testGetActiveHttpProxy() throws IOException, XmlPullParserException { SettingsXpp3Reader r = new SettingsXpp3Reader(); Settings s = r.read(WsImportMojoTest.class.getResourceAsStream("proxy1.xml")); String proxyString = WsImportMojo.getActiveHttpProxy(s); Assert.assertEquals(proxyString, "proxyActive:8099"); s = r.read(WsImportMojoTest.class.getResourceAsStream("proxy2.xml")); proxyString = WsImportMojo.getActiveHttpProxy(s); Assert.assertNull(proxyString, proxyString); s = r.read(WsImportMojoTest.class.getResourceAsStream("proxy3.xml")); proxyString = WsImportMojo.getActiveHttpProxy(s); Assert.assertEquals(proxyString, "proxyuser:proxypwd@proxy1-auth:8080"); s = r.read(WsImportMojoTest.class.getResourceAsStream("proxy4.xml")); proxyString = WsImportMojo.getActiveHttpProxy(s); Assert.assertEquals(proxyString, "proxyuser2@proxy1-auth2:7777"); }
### Question: TracingHttpClientBuilder extends HttpClientBuilder { public TracingHttpClientBuilder disableInjection() { this.injectDisabled = true; return this; } TracingHttpClientBuilder(); TracingHttpClientBuilder( RedirectStrategy redirectStrategy, boolean redirectHandlingDisabled); TracingHttpClientBuilder( RedirectStrategy redirectStrategy, boolean redirectHandlingDisabled, Tracer tracer, List<ApacheClientSpanDecorator> spanDecorators); static TracingHttpClientBuilder create(); TracingHttpClientBuilder withTracer(Tracer tracer); TracingHttpClientBuilder withSpanDecorators(List<ApacheClientSpanDecorator> decorators); TracingHttpClientBuilder disableInjection(); }### Answer: @Test public void testDisablePropagation() throws IOException { { HttpClient client = ((TracingHttpClientBuilder)clientBuilder).disableInjection().build(); client.execute(new HttpGet(serverUrl(RedirectHandler.MAPPING))); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(3, mockSpans.size()); MockSpan mockSpan = mockSpans.get(1); Assert.assertEquals(PropagationHandler.lastRequest.getFirstHeader("traceId"), null); Assert.assertEquals(PropagationHandler.lastRequest.getFirstHeader("spanId"), null); assertLocalSpan(mockSpans.get(2)); }
### Question: WXBizMsgCrypt { public String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr) throws AesException { String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr); if (!signature.equals(msgSignature)) { throw new AesException(AesException.ValidateSignatureError); } String result = decrypt(echoStr); return result; } WXBizMsgCrypt(String token, String encodingAesKey, String appId); String getRandomStr(); String encrypt(String randomStr, String text); String decrypt(String text); String encryptMsg(String replyMsg, String timeStamp, String nonce); String decryptMsg(String msgSignature, String timeStamp, String nonce, String encrypt); String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr); }### Answer: @Test public void testVerifyUrl() throws AesException { WXBizMsgCrypt wxcpt = new WXBizMsgCrypt("QDG6eK", "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C", "wx5823bf96d3bd56c7"); String verifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; String timeStamp = "1409659589"; String nonce = "263014780"; String echoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; wxcpt.verifyUrl(verifyMsgSig, timeStamp, nonce, echoStr); }
### Question: MainActivityPresenter implements MainActivityContract.Presenter { @VisibleForTesting void checkAndroidVersionCompatibility() { if (!supportedByArtist()) { mView.showIncompatibleAndroidVersionDialog(); } } MainActivityPresenter(MainActivityContract.View view, SettingsManager settingsManager, Context context); @Override void start(); @Override void checkCompatibility(); static boolean isDeviceCompatible(Context context); @Override void openDex2OatHelpPage(); @Override void selectFragment(@selectableFragment int id); @Override void saveInstanceState(Bundle outState); @Override void restoreSavedInstanceState(Bundle savedInstanceState, FragmentManager fragmentManager); }### Answer: @Test public void incompatibilityTest() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), Build.VERSION_CODES.LOLLIPOP); mPresenter.checkAndroidVersionCompatibility(); verify(mView).showIncompatibleAndroidVersionDialog(); } @Test public void compatibilityTest() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), Build.VERSION_CODES.N); mPresenter.checkAndroidVersionCompatibility(); verify(mView, never()).showIncompatibleAndroidVersionDialog(); }
### Question: MainActivityPresenter implements MainActivityContract.Presenter { @Override public void selectFragment(@selectableFragment int id) { Fragment selectedFragment = null; switch (id) { case INFO_FRAGMENT: if (mInfoFragment == null) { mInfoFragment = new InfoFragment(); } selectedFragment = mInfoFragment; break; case INSTRUMENTATION_FRAGMENT: if (mAppListFragment == null) { mAppListFragment = new AppListFragment(); } selectedFragment = mAppListFragment; break; case MODULES_FRAGMENT: if (mModuleFragment == null) { mModuleFragment = new ModuleFragment(); new ModulePresenter(mContext, mModuleFragment); } selectedFragment = mModuleFragment; break; } mSelectedFragmentId = id; mView.showSelectedFragment(selectedFragment); } MainActivityPresenter(MainActivityContract.View view, SettingsManager settingsManager, Context context); @Override void start(); @Override void checkCompatibility(); static boolean isDeviceCompatible(Context context); @Override void openDex2OatHelpPage(); @Override void selectFragment(@selectableFragment int id); @Override void saveInstanceState(Bundle outState); @Override void restoreSavedInstanceState(Bundle savedInstanceState, FragmentManager fragmentManager); }### Answer: @Test public void selectInfoFragment() throws Exception { mPresenter.selectFragment(MainActivityPresenter.INFO_FRAGMENT); verify(mView).showSelectedFragment(mArgumentCaptor.capture()); assertTrue(mArgumentCaptor.getValue() instanceof InfoFragment); } @Test public void selectAppListFragment() throws Exception { mPresenter.selectFragment(MainActivityPresenter.INSTRUMENTATION_FRAGMENT); verify(mView).showSelectedFragment(mArgumentCaptor.capture()); assertTrue(mArgumentCaptor.getValue() instanceof AppListFragment); }
### Question: POP3Store extends Store { @Override public synchronized boolean isConnected() { if (!super.isConnected()) return false; try { if (port == null) port = getPort(null); else if (!port.noop()) throw new IOException("NOOP failed"); return true; } catch (IOException ioex) { try { super.close(); } catch (MessagingException mex) { } return false; } } POP3Store(Session session, URLName url); POP3Store(Session session, URLName url, String name, boolean isSSL); @Override synchronized boolean isConnected(); @Override synchronized void close(); @Override Folder getDefaultFolder(); @Override Folder getFolder(String name); @Override Folder getFolder(URLName url); Map<String, String> capabilities(); synchronized boolean isSSL(); }### Answer: @Test public void testIsConnected() { TestServer server = null; try { final POP3Handler handler = new POP3HandlerNoopErr(); server = new TestServer(handler); server.start(); final Properties properties = new Properties(); properties.setProperty("mail.pop3.host", "localhost"); properties.setProperty("mail.pop3.port", "" + server.getPort()); final Session session = Session.getInstance(properties); final Store store = session.getStore("pop3"); try { store.connect("test", "test"); final Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); assertFalse(folder.isOpen()); } finally { store.close(); } } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (server != null) { server.quit(); } } }
### Question: PropUtil { @Deprecated public static int getIntSessionProperty(Session session, String name, int def) { return getInt(getProp(session.getProperties(), name), def); } private PropUtil(); static int getIntProperty(Properties props, String name, int def); static boolean getBooleanProperty(Properties props, String name, boolean def); @Deprecated static int getIntSessionProperty(Session session, String name, int def); @Deprecated static boolean getBooleanSessionProperty(Session session, String name, boolean def); static boolean getBooleanSystemProperty(String name, boolean def); }### Answer: @Test @SuppressWarnings("deprecation") public void testSessionIntDef() throws Exception { Properties props = new Properties(); Session sess = Session.getInstance(props, null); assertEquals(PropUtil.getIntSessionProperty(sess, "test", 1), 1); } @Test @SuppressWarnings("deprecation") public void testSessionIntDefProp() throws Exception { Properties defprops = new Properties(); defprops.setProperty("test", "2"); Properties props = new Properties(defprops); Session sess = Session.getInstance(props, null); assertEquals(PropUtil.getIntSessionProperty(sess, "test", 1), 2); } @Test @SuppressWarnings("deprecation") public void testSessionInteger() throws Exception { Properties props = new Properties(); props.put("test", 2); Session sess = Session.getInstance(props, null); assertEquals(PropUtil.getIntSessionProperty(sess, "test", 1), 2); } @Test @SuppressWarnings("deprecation") public void testSessionInt() throws Exception { Properties props = new Properties(); props.setProperty("test", "2"); Session sess = Session.getInstance(props, null); assertEquals(PropUtil.getIntSessionProperty(sess, "test", 1), 2); }
### Question: SeverityComparator implements Comparator<LogRecord>, Serializable { @Override public boolean equals(final Object o) { return o == null ? false : o.getClass() == getClass(); } Throwable apply(final Throwable chain); final int applyThenCompare(Throwable tc1, Throwable tc2); int compareThrowable(final Throwable t1, final Throwable t2); @SuppressWarnings("override") //JDK-6954234 int compare(final LogRecord o1, final LogRecord o2); @Override boolean equals(final Object o); @Override int hashCode(); boolean isNormal(final Throwable t); }### Answer: @Test @SuppressWarnings("ObjectEqualsNull") public void testEquals() { final SeverityComparator a = new SeverityComparator(); final SeverityComparator b = new SeverityComparator(); assertNotSame(a, b); assertNotNull(a); assertFalse(a.equals(null)); assertNotNull(b); assertFalse(b.equals(null)); assertTrue(a.equals(a)); assertTrue(b.equals(b)); assertTrue(a.equals(b)); assertTrue(b.equals(a)); }
### Question: SeverityComparator implements Comparator<LogRecord>, Serializable { @Override public int hashCode() { return 31 * getClass().hashCode(); } Throwable apply(final Throwable chain); final int applyThenCompare(Throwable tc1, Throwable tc2); int compareThrowable(final Throwable t1, final Throwable t2); @SuppressWarnings("override") //JDK-6954234 int compare(final LogRecord o1, final LogRecord o2); @Override boolean equals(final Object o); @Override int hashCode(); boolean isNormal(final Throwable t); }### Answer: @Test public void testHashCode() { final SeverityComparator a = new SeverityComparator(); final SeverityComparator b = new SeverityComparator(); assertNotSame(a, b); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertEquals(a.hashCode(), b.hashCode()); }
### Question: PropUtil { @Deprecated public static boolean getBooleanSessionProperty(Session session, String name, boolean def) { return getBoolean(getProp(session.getProperties(), name), def); } private PropUtil(); static int getIntProperty(Properties props, String name, int def); static boolean getBooleanProperty(Properties props, String name, boolean def); @Deprecated static int getIntSessionProperty(Session session, String name, int def); @Deprecated static boolean getBooleanSessionProperty(Session session, String name, boolean def); static boolean getBooleanSystemProperty(String name, boolean def); }### Answer: @Test @SuppressWarnings("deprecation") public void testSessionBool() throws Exception { Properties props = new Properties(); props.setProperty("test", "true"); Session sess = Session.getInstance(props, null); assertTrue(PropUtil.getBooleanSessionProperty(sess, "test", false)); } @Test @SuppressWarnings("deprecation") public void testSessionBoolDef() throws Exception { Properties props = new Properties(); Session sess = Session.getInstance(props, null); assertTrue(PropUtil.getBooleanSessionProperty(sess, "test", true)); } @Test @SuppressWarnings("deprecation") public void testSessionBoolDefProp() throws Exception { Properties defprops = new Properties(); defprops.setProperty("test", "true"); Properties props = new Properties(defprops); Session sess = Session.getInstance(props, null); assertTrue(PropUtil.getBooleanSessionProperty(sess, "test", false)); } @Test @SuppressWarnings("deprecation") public void testSessionBoolean() throws Exception { Properties props = new Properties(); props.put("test", true); Session sess = Session.getInstance(props, null); assertTrue(PropUtil.getBooleanSessionProperty(sess, "test", false)); }
### Question: CompactFormatter extends java.util.logging.Formatter { public String formatLevel(final LogRecord record) { return record.getLevel().getLocalizedName(); } CompactFormatter(); CompactFormatter(final String format); @Override String format(final LogRecord record); @Override String formatMessage(final LogRecord record); String formatMessage(final Throwable t); String formatLevel(final LogRecord record); String formatSource(final LogRecord record); String formatLoggerName(final LogRecord record); Number formatThreadID(final LogRecord record); String formatThrown(final LogRecord record); String formatError(final LogRecord record); String formatBackTrace(final LogRecord record); }### Answer: @Test public void testFormatLevel() { CompactFormatter cf = new CompactFormatter(); LogRecord record = new LogRecord(Level.SEVERE, ""); String result = cf.formatLevel(record); assertEquals(record.getLevel().getLocalizedName(), result); } @Test(expected = NullPointerException.class) public void testFormatLevelNull() { CompactFormatter cf = new CompactFormatter(); cf.formatLevel((LogRecord) null); fail(cf.toString()); }
### Question: CompactFormatter extends java.util.logging.Formatter { public String formatLoggerName(final LogRecord record) { return simpleClassName(record.getLoggerName()); } CompactFormatter(); CompactFormatter(final String format); @Override String format(final LogRecord record); @Override String formatMessage(final LogRecord record); String formatMessage(final Throwable t); String formatLevel(final LogRecord record); String formatSource(final LogRecord record); String formatLoggerName(final LogRecord record); Number formatThreadID(final LogRecord record); String formatThrown(final LogRecord record); String formatError(final LogRecord record); String formatBackTrace(final LogRecord record); }### Answer: @Test public void testFormatLogger() { CompactFormatter cf = new CompactFormatter(); LogRecord record = new LogRecord(Level.SEVERE, ""); record.setSourceMethodName(null); record.setSourceClassName(null); record.setLoggerName(Object.class.getName()); String result = cf.formatLoggerName(record); assertEquals(Object.class.getSimpleName(), result); } @Test(expected = NullPointerException.class) public void testFormatLoggerNull() { CompactFormatter cf = new CompactFormatter(); cf.formatLoggerName((LogRecord) null); fail(cf.toString()); }
### Question: CompactFormatter extends java.util.logging.Formatter { public Number formatThreadID(final LogRecord record) { return (((long) record.getThreadID()) & 0xffffffffL); } CompactFormatter(); CompactFormatter(final String format); @Override String format(final LogRecord record); @Override String formatMessage(final LogRecord record); String formatMessage(final Throwable t); String formatLevel(final LogRecord record); String formatSource(final LogRecord record); String formatLoggerName(final LogRecord record); Number formatThreadID(final LogRecord record); String formatThrown(final LogRecord record); String formatError(final LogRecord record); String formatBackTrace(final LogRecord record); }### Answer: @Test public void testFormatThreadID() { CompactFormatter cf = new CompactFormatter("%10$d"); LogRecord record = new LogRecord(Level.SEVERE, ""); record.setThreadID(10); String output = cf.format(record); String expect = Long.toString(record.getThreadID()); assertEquals(expect, output); record.setThreadID(-1); output = cf.format(record); expect = Long.toString((1L << 32L) - 1L); assertEquals(expect, output); Number id = cf.formatThreadID(record); assertEquals(record.getThreadID(), id.intValue()); assertEquals(expect, Long.toString(id.longValue())); } @Test(expected = NullPointerException.class) public void testFormatThreadIDNull() { CompactFormatter cf = new CompactFormatter(); cf.formatThreadID((LogRecord) null); }
### Question: CompactFormatter extends java.util.logging.Formatter { public String formatError(final LogRecord record) { return formatMessage(record.getThrown()); } CompactFormatter(); CompactFormatter(final String format); @Override String format(final LogRecord record); @Override String formatMessage(final LogRecord record); String formatMessage(final Throwable t); String formatLevel(final LogRecord record); String formatSource(final LogRecord record); String formatLoggerName(final LogRecord record); Number formatThreadID(final LogRecord record); String formatThrown(final LogRecord record); String formatError(final LogRecord record); String formatBackTrace(final LogRecord record); }### Answer: @Test public void testFormatError() { CompactFormatter cf = new CompactFormatter("%11$s"); LogRecord record = new LogRecord(Level.SEVERE, "message"); record.setThrown(new Throwable("error")); String output = cf.format(record); assertTrue(output.startsWith(record.getThrown() .getClass().getSimpleName())); assertTrue(output.endsWith(record.getThrown().getMessage())); } @Test(expected = NullPointerException.class) public void testFormatErrorNull() { CompactFormatter cf = new CompactFormatter(); cf.formatError((LogRecord) null); }
### Question: PropUtil { public static boolean getBooleanSystemProperty(String name, boolean def) { try { return getBoolean(getProp(System.getProperties(), name), def); } catch (SecurityException sex) { } try { String value = System.getProperty(name); if (value == null) return def; if (def) return !value.equalsIgnoreCase("false"); else return value.equalsIgnoreCase("true"); } catch (SecurityException sex) { return def; } } private PropUtil(); static int getIntProperty(Properties props, String name, int def); static boolean getBooleanProperty(Properties props, String name, boolean def); @Deprecated static int getIntSessionProperty(Session session, String name, int def); @Deprecated static boolean getBooleanSessionProperty(Session session, String name, boolean def); static boolean getBooleanSystemProperty(String name, boolean def); }### Answer: @Test public void testSystemBool() throws Exception { System.setProperty("test", "true"); assertTrue(PropUtil.getBooleanSystemProperty("test", false)); } @Test public void testSystemBoolDef() throws Exception { assertTrue(PropUtil.getBooleanSystemProperty("testnotset", true)); } @Test public void testSystemBoolean() throws Exception { System.getProperties().put("testboolean", true); assertTrue(PropUtil.getBooleanSystemProperty("testboolean", false)); }
### Question: CompactFormatter extends java.util.logging.Formatter { protected Throwable apply(final Throwable t) { return SeverityComparator.getInstance().apply(t); } CompactFormatter(); CompactFormatter(final String format); @Override String format(final LogRecord record); @Override String formatMessage(final LogRecord record); String formatMessage(final Throwable t); String formatLevel(final LogRecord record); String formatSource(final LogRecord record); String formatLoggerName(final LogRecord record); Number formatThreadID(final LogRecord record); String formatThrown(final LogRecord record); String formatError(final LogRecord record); String formatBackTrace(final LogRecord record); }### Answer: @Test public void testApply() { CompactFormatter cf = new CompactFormatter(); assertNull(cf.apply((Throwable) null)); final Throwable t = new Throwable(); Throwable e = cf.apply(t); assertSame(t, e); } @Test public void testApplyNull() { assertNull(new CompactFormatter().apply(null)); } @Test(timeout = 30000) public void testApplyEvil() { CompactFormatter cf = new CompactFormatter(); assertNotNull(cf.apply(createEvilThrowable())); }
### Question: PropUtil { public static int getIntProperty(Properties props, String name, int def) { return getInt(getProp(props, name), def); } private PropUtil(); static int getIntProperty(Properties props, String name, int def); static boolean getBooleanProperty(Properties props, String name, boolean def); @Deprecated static int getIntSessionProperty(Session session, String name, int def); @Deprecated static boolean getBooleanSessionProperty(Session session, String name, boolean def); static boolean getBooleanSystemProperty(String name, boolean def); }### Answer: @Test public void testInt() throws Exception { Properties props = new Properties(); props.setProperty("test", "2"); assertEquals(PropUtil.getIntProperty(props, "test", 1), 2); } @Test public void testIntDef() throws Exception { Properties props = new Properties(); assertEquals(PropUtil.getIntProperty(props, "test", 1), 1); } @Test public void testIntDefProp() throws Exception { Properties defprops = new Properties(); defprops.setProperty("test", "2"); Properties props = new Properties(defprops); assertEquals(PropUtil.getIntProperty(props, "test", 1), 2); } @Test public void testInteger() throws Exception { Properties props = new Properties(); props.put("test", 2); assertEquals(PropUtil.getIntProperty(props, "test", 1), 2); }
### Question: CompactFormatter extends java.util.logging.Formatter { protected String toAlternate(final String s) { return s != null ? s.replaceAll("[\\x00-\\x1F\\x7F]+", "") : null; } CompactFormatter(); CompactFormatter(final String format); @Override String format(final LogRecord record); @Override String formatMessage(final LogRecord record); String formatMessage(final Throwable t); String formatLevel(final LogRecord record); String formatSource(final LogRecord record); String formatLoggerName(final LogRecord record); Number formatThreadID(final LogRecord record); String formatThrown(final LogRecord record); String formatError(final LogRecord record); String formatBackTrace(final LogRecord record); }### Answer: @Test public void testToAlternate() { CompactFormatter cf = new CompactFormatter(); assertEquals("", cf.toAlternate(LINE_SEP)); } @Test public void testToAlternateNull() { CompactFormatter cf = new CompactFormatter(); assertNull(cf.toAlternate((String) null)); }
### Question: CollectorFormatter extends Formatter { @Override public String toString() { String result; try { result = formatRecord((Handler) null, false); } catch (final RuntimeException ignore) { result = super.toString(); } return result; } CollectorFormatter(); CollectorFormatter(String format); CollectorFormatter(String format, Formatter f, Comparator<? super LogRecord> c); @Override String format(final LogRecord record); @Override String getTail(final Handler h); @Override String toString(); }### Answer: @Test public void testDeclaredClasses() throws Exception { Class<?>[] declared = CollectorFormatter.class.getDeclaredClasses(); assertEquals(Arrays.toString(declared), 0, declared.length); }