method2testcases
stringlengths
118
3.08k
### Question: DefaultLoadBalancer implements LoadBalancer { public Map<HRegionInfo, ServerName> immediateAssignment( List<HRegionInfo> regions, List<ServerName> servers) { Map<HRegionInfo,ServerName> assignments = new TreeMap<HRegionInfo,ServerName>(); for(HRegionInfo region : regions) { assignments.put(region, servers.get(RANDOM.nextInt(servers.size()))); } return assignments; } void setClusterStatus(ClusterStatus st); void setMasterServices(MasterServices masterServices); @Override void setConf(Configuration conf); @Override Configuration getConf(); List<RegionPlan> balanceCluster( Map<ServerName, List<HRegionInfo>> clusterState); Map<ServerName, List<HRegionInfo>> roundRobinAssignment( List<HRegionInfo> regions, List<ServerName> servers); Map<ServerName, List<HRegionInfo>> retainAssignment( Map<HRegionInfo, ServerName> regions, List<ServerName> servers); Map<HRegionInfo, ServerName> immediateAssignment( List<HRegionInfo> regions, List<ServerName> servers); ServerName randomAssignment(List<ServerName> servers); }### Answer: @Test public void testImmediateAssignment() throws Exception { for(int [] mock : regionsAndServersMocks) { LOG.debug("testImmediateAssignment with " + mock[0] + " regions and " + mock[1] + " servers"); List<HRegionInfo> regions = randomRegions(mock[0]); List<ServerAndLoad> servers = randomServers(mock[1], 0); List<ServerName> list = getListOfServerNames(servers); Map<HRegionInfo,ServerName> assignments = loadBalancer.immediateAssignment(regions, list); assertImmediateAssignment(regions, list, assignments); returnRegions(regions); returnServers(list); } }
### Question: SchemaConfigured implements HeapSize, SchemaAware { public String schemaConfAsJSON() { return "{\"tableName\":\"" + tableName + "\",\"cfName\":\"" + cfName + "\"}"; } private SchemaConfigured(Configuration conf); SchemaConfigured(); SchemaConfigured(Configuration conf, Path path); SchemaConfigured(Path path); SchemaConfigured(Configuration conf, String tableName, String cfName); SchemaConfigured(SchemaAware that); static SchemaConfigured createUnknown(); @Override String getTableName(); @Override String getColumnFamilyName(); @Override SchemaMetrics getSchemaMetrics(); void passSchemaMetricsTo(SchemaConfigured target); static void resetSchemaMetricsConf(SchemaConfigured target); @Override long heapSize(); String schemaConfAsJSON(); static final int SCHEMA_CONFIGURED_UNALIGNED_HEAP_SIZE; }### Answer: @Test public void testToString() throws JSONException { SchemaConfigured sc = new SchemaConfigured(null, TABLE_NAME, CF_NAME); JSONStringer json = new JSONStringer(); json.object(); json.key("tableName"); json.value(TABLE_NAME); json.key("cfName"); json.value(CF_NAME); json.endObject(); assertEquals(json.toString(), sc.schemaConfAsJSON()); }
### Question: SchemaConfigured implements HeapSize, SchemaAware { public static void resetSchemaMetricsConf(SchemaConfigured target) { target.tableName = null; target.cfName = null; target.schemaMetrics = null; target.schemaConfigurationChanged(); } private SchemaConfigured(Configuration conf); SchemaConfigured(); SchemaConfigured(Configuration conf, Path path); SchemaConfigured(Path path); SchemaConfigured(Configuration conf, String tableName, String cfName); SchemaConfigured(SchemaAware that); static SchemaConfigured createUnknown(); @Override String getTableName(); @Override String getColumnFamilyName(); @Override SchemaMetrics getSchemaMetrics(); void passSchemaMetricsTo(SchemaConfigured target); static void resetSchemaMetricsConf(SchemaConfigured target); @Override long heapSize(); String schemaConfAsJSON(); static final int SCHEMA_CONFIGURED_UNALIGNED_HEAP_SIZE; }### Answer: @Test public void testResetSchemaMetricsConf() { SchemaConfigured target = new SchemaConfigured(null, "t1", "cf1"); SchemaConfigured.resetSchemaMetricsConf(target); new SchemaConfigured(null, "t2", "cf2").passSchemaMetricsTo(target); assertEquals("t2", target.getTableName()); assertEquals("cf2", target.getColumnFamilyName()); }
### Question: RegionSplitPolicy extends Configured { public static RegionSplitPolicy create(HRegion region, Configuration conf) throws IOException { Class<? extends RegionSplitPolicy> clazz = getSplitPolicyClass( region.getTableDesc(), conf); RegionSplitPolicy policy = ReflectionUtils.newInstance(clazz, conf); policy.configureForRegion(region); return policy; } static RegionSplitPolicy create(HRegion region, Configuration conf); }### Answer: @Test public void testCreateDefault() throws IOException { conf.setLong(HConstants.HREGION_MAX_FILESIZE, 1234L); ConstantSizeRegionSplitPolicy policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create( mockRegion, conf); assertEquals(1234L, policy.getDesiredMaxFileSize()); htd.setMaxFileSize(9999L); policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create( mockRegion, conf); assertEquals(9999L, policy.getDesiredMaxFileSize()); } @Test public void testConstantSizePolicy() throws IOException { htd.setMaxFileSize(1024L); ConstantSizeRegionSplitPolicy policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create(mockRegion, conf); doConstantSizePolicyTests(policy); }
### Question: LRUDictionary implements Dictionary { @Override public short addEntry(byte[] data, int offset, int length) { if (length <= 0) return NOT_IN_DICTIONARY; return backingStore.put(data, offset, length); } @Override byte[] getEntry(short idx); @Override short findEntry(byte[] data, int offset, int length); @Override short addEntry(byte[] data, int offset, int length); @Override void clear(); }### Answer: @Test public void testPassingSameArrayToAddEntry() { int len = HConstants.CATALOG_FAMILY.length; int index = testee.addEntry(HConstants.CATALOG_FAMILY, 0, len); assertFalse(index == testee.addEntry(HConstants.CATALOG_FAMILY, 0, len)); assertFalse(index == testee.addEntry(HConstants.CATALOG_FAMILY, 0, len)); }
### Question: LRUDictionary implements Dictionary { @Override public short findEntry(byte[] data, int offset, int length) { short ret = backingStore.findIdx(data, offset, length); if (ret == NOT_IN_DICTIONARY) { addEntry(data, offset, length); } return ret; } @Override byte[] getEntry(short idx); @Override short findEntry(byte[] data, int offset, int length); @Override short addEntry(byte[] data, int offset, int length); @Override void clear(); }### Answer: @Test public void TestLRUPolicy(){ for (int i = 0; i < LRUDictionary.BidirectionalLRUMap.MAX_SIZE; i++) { testee.findEntry((BigInteger.valueOf(i)).toByteArray(), 0, (BigInteger.valueOf(i)).toByteArray().length); } assertTrue(testee.findEntry(BigInteger.ZERO.toByteArray(), 0, BigInteger.ZERO.toByteArray().length) != -1); assertTrue(testee.findEntry(BigInteger.valueOf(Integer.MAX_VALUE).toByteArray(), 0, BigInteger.valueOf(Integer.MAX_VALUE).toByteArray().length) == -1); assertTrue(testee.findEntry(BigInteger.valueOf(Integer.MAX_VALUE).toByteArray(), 0, BigInteger.valueOf(Integer.MAX_VALUE).toByteArray().length) != -1); assertTrue(testee.findEntry(BigInteger.ZERO.toByteArray(), 0, BigInteger.ZERO.toByteArray().length) != -1); for(int i = 1; i < LRUDictionary.BidirectionalLRUMap.MAX_SIZE; i++) { assertTrue(testee.findEntry(BigInteger.valueOf(i).toByteArray(), 0, BigInteger.valueOf(i).toByteArray().length) == -1); } for (int i = 0; i < LRUDictionary.BidirectionalLRUMap.MAX_SIZE; i++) { assertTrue(testee.findEntry(BigInteger.valueOf(i).toByteArray(), 0, BigInteger.valueOf(i).toByteArray().length) != -1); } }
### Question: SnapshotTask implements ForeignExceptionSnare, Callable<Void> { public void snapshotFailure(String message, Exception e) { ForeignException ee = new ForeignException(message, e); errorMonitor.receive(ee); } SnapshotTask(SnapshotDescription snapshot, ForeignExceptionDispatcher monitor); void snapshotFailure(String message, Exception e); @Override void rethrowException(); @Override boolean hasException(); @Override ForeignException getException(); }### Answer: @Test public void testErrorPropagation() throws Exception { ForeignExceptionDispatcher error = mock(ForeignExceptionDispatcher.class); SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName("snapshot") .setTable("table").build(); final Exception thrown = new Exception("Failed!"); SnapshotTask fail = new SnapshotTask(snapshot, error) { @Override public Void call() { snapshotFailure("Injected failure", thrown); return null; } }; fail.call(); verify(error, Mockito.times(1)).receive(any(ForeignException.class)); }
### Question: CatalogTracker { public boolean verifyRootRegionLocation(final long timeout) throws InterruptedException, IOException { HRegionInterface connection = null; try { connection = waitForRootServerConnection(timeout); } catch (NotAllMetaRegionsOnlineException e) { } catch (ServerNotRunningYetException e) { } catch (UnknownHostException e) { } return (connection == null)? false: verifyRegionLocation(connection, this.rootRegionTracker.getRootRegionLocation(), ROOT_REGION_NAME); } CatalogTracker(final Configuration conf); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf, Abortable abortable); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf, HConnection connection, Abortable abortable); void start(); void stop(); ServerName getRootLocation(); ServerName getMetaLocation(); ServerName getMetaLocationOrReadLocationFromRoot(); void waitForRoot(); HRegionInterface waitForRootServerConnection(long timeout); void waitForMeta(); ServerName waitForMeta(long timeout); HRegionInterface waitForMetaServerConnection(long timeout); void resetMetaLocation(); boolean verifyRootRegionLocation(final long timeout); boolean verifyMetaRegionLocation(final long timeout); HConnection getConnection(); }### Answer: @Test public void testVerifyRootRegionLocationFails() throws IOException, InterruptedException, KeeperException { HConnection connection = Mockito.mock(HConnection.class); ConnectException connectException = new ConnectException("Connection refused"); final HRegionInterface implementation = Mockito.mock(HRegionInterface.class); Mockito.when(implementation.getRegionInfo((byte [])Mockito.any())). thenThrow(connectException); Mockito.when(connection.getHRegionConnection(Mockito.anyString(), Mockito.anyInt(), Mockito.anyBoolean())). thenReturn(implementation); final CatalogTracker ct = constructAndStartCatalogTracker(connection); try { RootLocationEditor.setRootLocation(this.watcher, new ServerName("example.com", 1234, System.currentTimeMillis())); Assert.assertFalse(ct.verifyRootRegionLocation(100)); } finally { RootLocationEditor.deleteRootLocation(this.watcher); } }
### Question: CatalogTracker { public void waitForRoot() throws InterruptedException { this.rootRegionTracker.blockUntilAvailable(); } CatalogTracker(final Configuration conf); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf, Abortable abortable); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf, HConnection connection, Abortable abortable); void start(); void stop(); ServerName getRootLocation(); ServerName getMetaLocation(); ServerName getMetaLocationOrReadLocationFromRoot(); void waitForRoot(); HRegionInterface waitForRootServerConnection(long timeout); void waitForMeta(); ServerName waitForMeta(long timeout); HRegionInterface waitForMetaServerConnection(long timeout); void resetMetaLocation(); boolean verifyRootRegionLocation(final long timeout); boolean verifyMetaRegionLocation(final long timeout); HConnection getConnection(); }### Answer: @Test (expected = NotAllMetaRegionsOnlineException.class) public void testTimeoutWaitForRoot() throws IOException, InterruptedException { HConnection connection = Mockito.mock(HConnection.class); final CatalogTracker ct = constructAndStartCatalogTracker(connection); ct.waitForRoot(100); }
### Question: HRegionLocation implements Comparable<HRegionLocation> { public int compareTo(HRegionLocation o) { int result = this.hostname.compareTo(o.getHostname()); if (result != 0) return result; return this.port - o.getPort(); } HRegionLocation(HRegionInfo regionInfo, final String hostname, final int port); @Override synchronized String toString(); @Override boolean equals(Object o); @Override int hashCode(); HRegionInfo getRegionInfo(); HServerAddress getServerAddress(); String getHostname(); int getPort(); synchronized String getHostnamePort(); int compareTo(HRegionLocation o); }### Answer: @Test public void testCompareTo() { ServerName hsa1 = new ServerName("localhost", 1234, -1L); HRegionLocation hsl1 = new HRegionLocation(HRegionInfo.ROOT_REGIONINFO, hsa1.getHostname(), hsa1.getPort()); ServerName hsa2 = new ServerName("localhost", 1235, -1L); HRegionLocation hsl2 = new HRegionLocation(HRegionInfo.ROOT_REGIONINFO, hsa2.getHostname(), hsa2.getPort()); assertTrue(hsl1.compareTo(hsl1) == 0); assertTrue(hsl2.compareTo(hsl2) == 0); int compare1 = hsl1.compareTo(hsl2); int compare2 = hsl2.compareTo(hsl1); assertTrue((compare1 > 0)? compare2 < 0: compare2 > 0); }
### Question: CatalogTracker { public void waitForMeta() throws InterruptedException { while (!this.stopped) { try { if (waitForMeta(100) != null) break; } catch (NotAllMetaRegionsOnlineException e) { if (LOG.isTraceEnabled()) { LOG.info(".META. still not available, sleeping and retrying." + " Reason: " + e.getMessage()); } } catch (IOException e) { LOG.info("Retrying", e); } } } CatalogTracker(final Configuration conf); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf, Abortable abortable); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf, HConnection connection, Abortable abortable); void start(); void stop(); ServerName getRootLocation(); ServerName getMetaLocation(); ServerName getMetaLocationOrReadLocationFromRoot(); void waitForRoot(); HRegionInterface waitForRootServerConnection(long timeout); void waitForMeta(); ServerName waitForMeta(long timeout); HRegionInterface waitForMetaServerConnection(long timeout); void resetMetaLocation(); boolean verifyRootRegionLocation(final long timeout); boolean verifyMetaRegionLocation(final long timeout); HConnection getConnection(); }### Answer: @Test (expected = RetriesExhaustedException.class) public void testTimeoutWaitForMeta() throws IOException, InterruptedException { HConnection connection = HConnectionTestingUtility.getMockedConnection(UTIL.getConfiguration()); try { final CatalogTracker ct = constructAndStartCatalogTracker(connection); ct.waitForMeta(100); } finally { HConnectionManager.deleteConnection(UTIL.getConfiguration()); } }
### Question: CatalogTracker { public ServerName getRootLocation() throws InterruptedException { return this.rootRegionTracker.getRootRegionLocation(); } CatalogTracker(final Configuration conf); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf, Abortable abortable); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf, HConnection connection, Abortable abortable); void start(); void stop(); ServerName getRootLocation(); ServerName getMetaLocation(); ServerName getMetaLocationOrReadLocationFromRoot(); void waitForRoot(); HRegionInterface waitForRootServerConnection(long timeout); void waitForMeta(); ServerName waitForMeta(long timeout); HRegionInterface waitForMetaServerConnection(long timeout); void resetMetaLocation(); boolean verifyRootRegionLocation(final long timeout); boolean verifyMetaRegionLocation(final long timeout); HConnection getConnection(); }### Answer: @Test public void testNoTimeoutWaitForRoot() throws IOException, InterruptedException, KeeperException { HConnection connection = Mockito.mock(HConnection.class); final CatalogTracker ct = constructAndStartCatalogTracker(connection); ServerName hsa = ct.getRootLocation(); Assert.assertNull(hsa); Thread t = new WaitOnMetaThread(ct); startWaitAliveThenWaitItLives(t, 1000); hsa = setRootLocation(); t.join(); Assert.assertTrue(ct.getRootLocation().equals(hsa)); }
### Question: IdLock { void assertMapEmpty() { assert map.size() == 0; } Entry getLockEntry(long id); void releaseLockEntry(Entry entry); }### 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(); } } @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: MRApps extends Apps { public static JobId toJobID(String jid) { return TypeConverter.toYarn(JobID.forName(jid)); } if(userClassesTakesPrecedence); static String toString(JobId jid); static JobId toJobID(String jid); static String toString(TaskId tid); static TaskId toTaskID(String tid); static String toString(TaskAttemptId taid); static TaskAttemptId toTaskAttemptID(String taid); static String taskSymbol(TaskType type); static TaskType taskType(String symbol); static TaskAttemptStateUI taskAttemptState(String attemptStateStr); @SuppressWarnings("deprecation") static void setClasspath(Map<String, String> environment, Configuration conf); }### Answer: @Test public void testToJobID() { JobId jid = MRApps.toJobID("job_1_1"); assertEquals(1, jid.getAppId().getClusterTimestamp()); assertEquals(1, jid.getAppId().getId()); assertEquals(1, jid.getId()); } @Test(expected=IllegalArgumentException.class) public void testJobIDShort() { MRApps.toJobID("job_0_0_0"); }
### Question: MRApps extends Apps { public static TaskId toTaskID(String tid) { return TypeConverter.toYarn(TaskID.forName(tid)); } if(userClassesTakesPrecedence); static String toString(JobId jid); static JobId toJobID(String jid); static String toString(TaskId tid); static TaskId toTaskID(String tid); static String toString(TaskAttemptId taid); static TaskAttemptId toTaskAttemptID(String taid); static String taskSymbol(TaskType type); static TaskType taskType(String symbol); static TaskAttemptStateUI taskAttemptState(String attemptStateStr); @SuppressWarnings("deprecation") static void setClasspath(Map<String, String> environment, Configuration conf); }### Answer: @Test public void testToTaskID() { TaskId tid = MRApps.toTaskID("task_1_2_r_3"); assertEquals(1, tid.getJobId().getAppId().getClusterTimestamp()); assertEquals(2, tid.getJobId().getAppId().getId()); assertEquals(2, tid.getJobId().getId()); assertEquals(TaskType.REDUCE, tid.getTaskType()); assertEquals(3, tid.getId()); tid = MRApps.toTaskID("task_1_2_m_3"); assertEquals(TaskType.MAP, tid.getTaskType()); } @Test(expected=IllegalArgumentException.class) public void testTaskIDShort() { MRApps.toTaskID("task_0_0000_m"); } @Test(expected=IllegalArgumentException.class) public void testTaskIDBadType() { MRApps.toTaskID("task_0_0000_x_000000"); }
### Question: MRApps extends Apps { public static TaskAttemptId toTaskAttemptID(String taid) { return TypeConverter.toYarn(TaskAttemptID.forName(taid)); } if(userClassesTakesPrecedence); static String toString(JobId jid); static JobId toJobID(String jid); static String toString(TaskId tid); static TaskId toTaskID(String tid); static String toString(TaskAttemptId taid); static TaskAttemptId toTaskAttemptID(String taid); static String taskSymbol(TaskType type); static TaskType taskType(String symbol); static TaskAttemptStateUI taskAttemptState(String attemptStateStr); @SuppressWarnings("deprecation") static void setClasspath(Map<String, String> environment, Configuration conf); }### Answer: @Test public void testToTaskAttemptID() { TaskAttemptId taid = MRApps.toTaskAttemptID("attempt_0_1_m_2_3"); assertEquals(0, taid.getTaskId().getJobId().getAppId().getClusterTimestamp()); assertEquals(1, taid.getTaskId().getJobId().getAppId().getId()); assertEquals(1, taid.getTaskId().getJobId().getId()); assertEquals(2, taid.getTaskId().getId()); assertEquals(3, taid.getId()); } @Test(expected=IllegalArgumentException.class) public void testTaskAttemptIDShort() { MRApps.toTaskAttemptID("attempt_0_0_0_m_0"); }
### Question: CompletedTask implements Task { @Override public synchronized TaskReport getReport() { if (report == null) { constructTaskReport(); } return report; } CompletedTask(TaskId taskId, TaskInfo taskInfo); @Override boolean canCommit(TaskAttemptId taskAttemptID); @Override TaskAttempt getAttempt(TaskAttemptId attemptID); @Override Map<TaskAttemptId, TaskAttempt> getAttempts(); @Override Counters getCounters(); @Override TaskId getID(); @Override float getProgress(); @Override synchronized TaskReport getReport(); @Override TaskType getType(); @Override boolean isFinished(); @Override TaskState getState(); }### Answer: @Test public void testTaskStartTimes() { TaskId taskId = Mockito.mock(TaskId.class); TaskInfo taskInfo = Mockito.mock(TaskInfo.class); Map<TaskAttemptID, TaskAttemptInfo> taskAttempts = new TreeMap<TaskAttemptID, TaskAttemptInfo>(); TaskAttemptID id = new TaskAttemptID("0", 0, TaskType.MAP, 0, 0); TaskAttemptInfo info = Mockito.mock(TaskAttemptInfo.class); Mockito.when(info.getAttemptId()).thenReturn(id); Mockito.when(info.getStartTime()).thenReturn(10l); taskAttempts.put(id, info); id = new TaskAttemptID("1", 0, TaskType.MAP, 1, 1); info = Mockito.mock(TaskAttemptInfo.class); Mockito.when(info.getAttemptId()).thenReturn(id); Mockito.when(info.getStartTime()).thenReturn(20l); taskAttempts.put(id, info); Mockito.when(taskInfo.getAllTaskAttempts()).thenReturn(taskAttempts); CompletedTask task = new CompletedTask(taskId, taskInfo); TaskReport report = task.getReport(); Assert.assertTrue(report.getStartTime() == 10); }
### Question: TokenCache { public static void cleanUpTokenReferral(Configuration conf) { conf.unset(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY); } static byte[] getSecretKey(Credentials credentials, Text alias); static void obtainTokensForNamenodes(Credentials credentials, Path[] ps, Configuration conf); static void cleanUpTokenReferral(Configuration conf); @InterfaceAudience.Private static Credentials loadTokens(String jobTokenFile, JobConf conf); @InterfaceAudience.Private static void setJobToken(Token<? extends TokenIdentifier> t, Credentials credentials); @SuppressWarnings("unchecked") @InterfaceAudience.Private static Token<JobTokenIdentifier> getJobToken(Credentials credentials); @InterfaceAudience.Private static final String JOB_TOKEN_HDFS_FILE; @InterfaceAudience.Private static final String JOB_TOKENS_FILENAME; }### Answer: @Test public void testCleanUpTokenReferral() throws Exception { Configuration conf = new Configuration(); conf.set(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY, "foo"); TokenCache.cleanUpTokenReferral(conf); assertNull(conf.get(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY)); }
### Question: Counters extends AbstractCounters<Counters.Counter, Counters.Group> { public Counters() { super(groupFactory); } Counters(); Counters(org.apache.hadoop.mapreduce.Counters newCounters); synchronized Group getGroup(String groupName); @SuppressWarnings("unchecked") synchronized Collection<String> getGroupNames(); synchronized String makeCompactString(); synchronized Counter findCounter(String group, String name); @Deprecated Counter findCounter(String group, int id, String name); void incrCounter(Enum<?> key, long amount); void incrCounter(String group, String counter, long amount); synchronized long getCounter(Enum<?> key); synchronized void incrAllCounters(Counters other); int size(); static Counters sum(Counters a, Counters b); void log(Log log); String makeEscapedCompactString(); static Counters fromEscapedCompactString(String compactString); static int MAX_COUNTER_LIMIT; }### Answer: @Test public void testCounters() throws IOException { Enum[] keysWithResource = {TaskCounter.MAP_INPUT_RECORDS, TaskCounter.MAP_OUTPUT_BYTES}; Enum[] keysWithoutResource = {myCounters.TEST1, myCounters.TEST2}; String[] groups = {"group1", "group2", "group{}()[]"}; String[] counters = {"counter1", "counter2", "counter{}()[]"}; try { testCounter(getEnumCounters(keysWithResource)); testCounter(getEnumCounters(keysWithoutResource)); testCounter(getEnumCounters(groups, counters)); } catch (ParseException pe) { throw new IOException(pe); } }
### Question: Counters extends AbstractCounters<Counters.Counter, Counters.Group> { public void incrCounter(Enum<?> key, long amount) { findCounter(key).increment(amount); } Counters(); Counters(org.apache.hadoop.mapreduce.Counters newCounters); synchronized Group getGroup(String groupName); @SuppressWarnings("unchecked") synchronized Collection<String> getGroupNames(); synchronized String makeCompactString(); synchronized Counter findCounter(String group, String name); @Deprecated Counter findCounter(String group, int id, String name); void incrCounter(Enum<?> key, long amount); void incrCounter(String group, String counter, long amount); synchronized long getCounter(Enum<?> key); synchronized void incrAllCounters(Counters other); int size(); static Counters sum(Counters a, Counters b); void log(Log log); String makeEscapedCompactString(); static Counters fromEscapedCompactString(String compactString); static int MAX_COUNTER_LIMIT; }### Answer: @SuppressWarnings("deprecation") @Test public void testCounterIteratorConcurrency() { Counters counters = new Counters(); counters.incrCounter("group1", "counter1", 1); Iterator<Group> iterator = counters.iterator(); counters.incrCounter("group2", "counter2", 1); iterator.next(); }
### Question: Counters extends AbstractCounters<Counters.Counter, Counters.Group> { public synchronized String makeCompactString() { StringBuilder builder = new StringBuilder(); boolean first = true; for(Group group: this){ for(Counter counter: group) { if (first) { first = false; } else { builder.append(','); } builder.append(group.getDisplayName()); builder.append('.'); builder.append(counter.getDisplayName()); builder.append(':'); builder.append(counter.getCounter()); } } return builder.toString(); } Counters(); Counters(org.apache.hadoop.mapreduce.Counters newCounters); synchronized Group getGroup(String groupName); @SuppressWarnings("unchecked") synchronized Collection<String> getGroupNames(); synchronized String makeCompactString(); synchronized Counter findCounter(String group, String name); @Deprecated Counter findCounter(String group, int id, String name); void incrCounter(Enum<?> key, long amount); void incrCounter(String group, String counter, long amount); synchronized long getCounter(Enum<?> key); synchronized void incrAllCounters(Counters other); int size(); static Counters sum(Counters a, Counters b); void log(Log log); String makeEscapedCompactString(); static Counters fromEscapedCompactString(String compactString); static int MAX_COUNTER_LIMIT; }### Answer: @Test public void testMakeCompactString() { final String GC1 = "group1.counter1:1"; final String GC2 = "group2.counter2:3"; Counters counters = new Counters(); counters.incrCounter("group1", "counter1", 1); assertEquals("group1.counter1:1", counters.makeCompactString()); counters.incrCounter("group2", "counter2", 3); String cs = counters.makeCompactString(); assertTrue("Bad compact string", cs.equals(GC1 + ',' + GC2) || cs.equals(GC2 + ',' + GC1)); }
### Question: ClientServiceDelegate { public org.apache.hadoop.mapreduce.Counters getJobCounters(JobID arg0) throws IOException, InterruptedException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobID = TypeConverter.toYarn(arg0); GetCountersRequest request = recordFactory.newRecordInstance(GetCountersRequest.class); request.setJobId(jobID); Counters cnt = ((GetCountersResponse) invoke("getCounters", GetCountersRequest.class, request)).getCounters(); return TypeConverter.fromYarn(cnt); } ClientServiceDelegate(Configuration conf, ResourceMgrDelegate rm, JobID jobId, MRClientProtocol historyServerProxy); org.apache.hadoop.mapreduce.Counters getJobCounters(JobID arg0); TaskCompletionEvent[] getTaskCompletionEvents(JobID arg0, int arg1, int arg2); String[] getTaskDiagnostics(org.apache.hadoop.mapreduce.TaskAttemptID arg0); JobStatus getJobStatus(JobID oldJobID); org.apache.hadoop.mapreduce.TaskReport[] getTaskReports(JobID oldJobID, TaskType taskType); boolean killTask(TaskAttemptID taskAttemptID, boolean fail); boolean killJob(JobID oldJobID); LogParams getLogFilePath(JobID oldJobID, TaskAttemptID oldTaskAttemptID); }### Answer: @Test public void testCountersFromHistoryServer() throws Exception { MRClientProtocol historyServerProxy = mock(MRClientProtocol.class); when(historyServerProxy.getCounters(getCountersRequest())).thenReturn( getCountersResponseFromHistoryServer()); ResourceMgrDelegate rm = mock(ResourceMgrDelegate.class); when(rm.getApplicationReport(TypeConverter.toYarn(oldJobId).getAppId())) .thenReturn(null); ClientServiceDelegate clientServiceDelegate = getClientServiceDelegate( historyServerProxy, rm); Counters counters = TypeConverter.toYarn(clientServiceDelegate.getJobCounters(oldJobId)); Assert.assertNotNull(counters); Assert.assertEquals(1001, counters.getCounterGroup("dummyCounters").getCounter("dummyCounter").getValue()); }
### Question: Constraints { public static void remove(HTableDescriptor desc) { disable(desc); List<ImmutableBytesWritable> keys = new ArrayList<ImmutableBytesWritable>(); for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e : desc .getValues().entrySet()) { String key = Bytes.toString((e.getKey().get())); String[] className = CONSTRAINT_HTD_ATTR_KEY_PATTERN.split(key); if (className.length == 2) { keys.add(e.getKey()); } } for (ImmutableBytesWritable key : keys) { desc.remove(key.get()); } } private Constraints(); static void enable(HTableDescriptor desc); static void disable(HTableDescriptor desc); static void remove(HTableDescriptor desc); static boolean has(HTableDescriptor desc, Class<? extends Constraint> clazz); static void add(HTableDescriptor desc, Class<? extends Constraint>... constraints); static void add(HTableDescriptor desc, Pair<Class<? extends Constraint>, Configuration>... constraints); static void add(HTableDescriptor desc, Class<? extends Constraint> constraint, Configuration conf); static void setConfiguration(HTableDescriptor desc, Class<? extends Constraint> clazz, Configuration configuration); static void remove(HTableDescriptor desc, Class<? extends Constraint> clazz); static void enableConstraint(HTableDescriptor desc, Class<? extends Constraint> clazz); static void disableConstraint(HTableDescriptor desc, Class<? extends Constraint> clazz); static boolean enabled(HTableDescriptor desc, Class<? extends Constraint> clazz); }### Answer: @Test public void testRemoveUnsetConstraint() throws Throwable { HTableDescriptor desc = new HTableDescriptor("table"); Constraints.remove(desc); Constraints.remove(desc, AlsoWorks.class); }
### Question: ThrottledInputStream extends InputStream { @Override public int read() throws IOException { throttle(); int data = rawStream.read(); if (data != -1) { bytesRead++; } return data; } ThrottledInputStream(InputStream rawStream); ThrottledInputStream(InputStream rawStream, long maxBytesPerSec); @Override int read(); @Override int read(byte[] b); @Override int read(byte[] b, int off, int len); long getTotalBytesRead(); long getBytesPerSec(); long getTotalSleepTime(); @Override String toString(); }### Answer: @Test public void testRead() { File tmpFile; File outFile; try { tmpFile = createFile(1024); outFile = createFile(); tmpFile.deleteOnExit(); outFile.deleteOnExit(); long maxBandwidth = copyAndAssert(tmpFile, outFile, 0, 1, -1, CB.BUFFER); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.BUFFER); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.BUFF_OFFSET); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.ONE_C); } catch (IOException e) { LOG.error("Exception encountered ", e); } }
### Question: ResourceCalculatorProcessTree extends Configured { public static ResourceCalculatorProcessTree getResourceCalculatorProcessTree( String pid, Class<? extends ResourceCalculatorProcessTree> clazz, Configuration conf) { if (clazz != null) { try { Constructor <? extends ResourceCalculatorProcessTree> c = clazz.getConstructor(String.class); ResourceCalculatorProcessTree rctree = c.newInstance(pid); rctree.setConf(conf); return rctree; } catch(Exception e) { throw new RuntimeException(e); } } try { String osName = System.getProperty("os.name"); if (osName.startsWith("Linux")) { return new ProcfsBasedProcessTree(pid); } } catch (SecurityException se) { return null; } return null; } ResourceCalculatorProcessTree(String root); abstract void updateProcessTree(); abstract String getProcessTreeDump(); long getCumulativeVmem(); long getCumulativeRssmem(); abstract long getCumulativeVmem(int olderThanAge); abstract long getCumulativeRssmem(int olderThanAge); abstract long getCumulativeCpuTime(); abstract boolean checkPidPgrpidForMatch(); static ResourceCalculatorProcessTree getResourceCalculatorProcessTree( String pid, Class<? extends ResourceCalculatorProcessTree> clazz, Configuration conf); }### Answer: @Test public void testCreateInstance() { ResourceCalculatorProcessTree tree; tree = ResourceCalculatorProcessTree.getResourceCalculatorProcessTree("1", EmptyProcessTree.class, new Configuration()); assertNotNull(tree); assertThat(tree, instanceOf(EmptyProcessTree.class)); } @Test public void testCreatedInstanceConfigured() { ResourceCalculatorProcessTree tree; Configuration conf = new Configuration(); tree = ResourceCalculatorProcessTree.getResourceCalculatorProcessTree("1", EmptyProcessTree.class, conf); assertNotNull(tree); assertThat(tree.getConf(), sameInstance(conf)); }
### Question: ProcfsBasedProcessTree extends ResourceCalculatorProcessTree { @Override public boolean checkPidPgrpidForMatch() { return checkPidPgrpidForMatch(pid, PROCFS); } ProcfsBasedProcessTree(String pid); ProcfsBasedProcessTree(String pid, String procfsDir); static boolean isAvailable(); @Override void updateProcessTree(); @Override boolean checkPidPgrpidForMatch(); static boolean checkPidPgrpidForMatch(String _pid, String procfs); List<String> getCurrentProcessIDs(); @Override String getProcessTreeDump(); @Override long getCumulativeVmem(int olderThanAge); @Override long getCumulativeRssmem(int olderThanAge); @Override long getCumulativeCpuTime(); @Override String toString(); static final String PROCFS_STAT_FILE; static final String PROCFS_CMDLINE_FILE; static final long PAGE_SIZE; static final long JIFFY_LENGTH_IN_MILLIS; }### Answer: @Test public void testDestroyProcessTree() throws IOException { String pid = "100"; File procfsRootDir = new File(TEST_ROOT_DIR, "proc"); try { setupProcfsRootDir(procfsRootDir); createProcessTree(pid, procfsRootDir.getAbsolutePath()); Assert.assertTrue(ProcfsBasedProcessTree.checkPidPgrpidForMatch( pid, procfsRootDir.getAbsolutePath())); } finally { FileUtil.fullyDelete(procfsRootDir); } }
### Question: ConverterUtils { public static String toString(ApplicationId appId) { return appId.toString(); } static Path getPathFromYarnURL(URL url); static Map<String, String> convertToString( Map<CharSequence, CharSequence> env); static URL getYarnUrlFromPath(Path path); static URL getYarnUrlFromURI(URI uri); static String toString(ApplicationId appId); static ApplicationId toApplicationId(RecordFactory recordFactory, String appIdStr); static String toString(ContainerId cId); static NodeId toNodeId(String nodeIdStr); static ContainerId toContainerId(String containerIdStr); static ApplicationAttemptId toApplicationAttemptId( String applicationAttmeptIdStr); static ApplicationId toApplicationId( String appIdStr); static final String APPLICATION_PREFIX; static final String CONTAINER_PREFIX; static final String APPLICATION_ATTEMPT_PREFIX; }### Answer: @Test public void testContainerIdNull() throws URISyntaxException { assertNull(ConverterUtils.toString((ContainerId)null)); }
### Question: ApplicationClassLoader extends URLClassLoader { @VisibleForTesting static boolean isSystemClass(String name, List<String> systemClasses) { if (systemClasses != null) { String canonicalName = name.replace('/', '.'); while (canonicalName.startsWith(".")) { canonicalName=canonicalName.substring(1); } for (String c : systemClasses) { boolean result = true; if (c.startsWith("-")) { c = c.substring(1); result = false; } if (c.endsWith(".") && canonicalName.startsWith(c)) { return result; } else if (canonicalName.equals(c)) { return result; } } } return false; } ApplicationClassLoader(URL[] urls, ClassLoader parent, List<String> systemClasses); ApplicationClassLoader(String classpath, ClassLoader parent, List<String> systemClasses); @Override URL getResource(String name); @Override Class<?> loadClass(String name); }### Answer: @Test public void testIsSystemClass() { assertFalse(isSystemClass("org.example.Foo", null)); assertTrue(isSystemClass("org.example.Foo", classes("org.example.Foo"))); assertTrue(isSystemClass("/org.example.Foo", classes("org.example.Foo"))); assertTrue(isSystemClass("org.example.Foo", classes("org.example."))); assertTrue(isSystemClass("net.example.Foo", classes("org.example.,net.example."))); assertFalse(isSystemClass("org.example.Foo", classes("-org.example.Foo,org.example."))); assertTrue(isSystemClass("org.example.Bar", classes("-org.example.Foo.,org.example."))); }
### Question: ApplicationClassLoader extends URLClassLoader { @Override public URL getResource(String name) { URL url = null; if (!isSystemClass(name, systemClasses)) { url= findResource(name); if (url == null && name.startsWith("/")) { if (LOG.isDebugEnabled()) { LOG.debug("Remove leading / off " + name); } url= findResource(name.substring(1)); } } if (url == null) { url= parent.getResource(name); } if (url != null) { if (LOG.isDebugEnabled()) { LOG.debug("getResource("+name+")=" + url); } } return url; } ApplicationClassLoader(URL[] urls, ClassLoader parent, List<String> systemClasses); ApplicationClassLoader(String classpath, ClassLoader parent, List<String> systemClasses); @Override URL getResource(String name); @Override Class<?> loadClass(String name); }### Answer: @Test public void testGetResource() throws IOException { URL testJar = makeTestJar().toURI().toURL(); ClassLoader currentClassLoader = getClass().getClassLoader(); ClassLoader appClassloader = new ApplicationClassLoader( new URL[] { testJar }, currentClassLoader, null); assertNull("Resource should be null for current classloader", currentClassLoader.getResourceAsStream("resource.txt")); InputStream in = appClassloader.getResourceAsStream("resource.txt"); assertNotNull("Resource should not be null for app classloader", in); assertEquals("hello", IOUtils.toString(in)); }
### Question: HFileArchiveUtil { public static Path getTableArchivePath(Path tabledir) { Path root = tabledir.getParent(); return getTableArchivePath(root, tabledir.getName()); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegion region, byte [] family); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir); static Path getRegionArchiveDir(Path rootdir, Path tabledir, Path regiondir); static Path getTableArchivePath(Path tabledir); static Path getTableArchivePath(final Path rootdir, final String tableName); static Path getTableArchivePath(final Configuration conf, final String tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetTableArchivePath() { assertNotNull(HFileArchiveUtil.getTableArchivePath(new Path("table"))); assertNotNull(HFileArchiveUtil.getTableArchivePath(new Path("root", new Path("table")))); }
### Question: WebApp extends ServletModule { public void stop() { try { checkNotNull(httpServer, "httpServer").stop(); checkNotNull(guiceFilter, "guiceFilter").destroy(); } catch (Exception e) { throw new WebAppException(e); } } @Provides HttpServer httpServer(); InetSocketAddress getListenerAddress(); int port(); void stop(); void joinThread(); @Provides Configuration conf(); String name(); String[] getServePathSpecs(); String getRedirectPath(); @Override void configureServlets(); void route(HTTP method, String pathSpec, Class<? extends Controller> cls, String action); void route(String pathSpec, Class<? extends Controller> cls, String action); void route(String pathSpec, Class<? extends Controller> cls); abstract void setup(); }### Answer: @Test public void testCreate() { WebApp app = WebApps.$for(this).start(); app.stop(); } @Test public void testDefaultRoutes() throws Exception { WebApp app = WebApps.$for("test", this).start(); String baseUrl = baseUrl(app); try { assertEquals("foo", getContent(baseUrl +"test/foo").trim()); assertEquals("foo", getContent(baseUrl +"test/foo/index").trim()); assertEquals("bar", getContent(baseUrl +"test/foo/bar").trim()); assertEquals("default", getContent(baseUrl +"test").trim()); assertEquals("default", getContent(baseUrl +"test/").trim()); assertEquals("default", getContent(baseUrl).trim()); } finally { app.stop(); } }
### Question: ServiceOperations { public static void init(Service service, Configuration configuration) { Service.STATE state = service.getServiceState(); ensureCurrentState(state, Service.STATE.NOTINITED); service.init(configuration); } private ServiceOperations(); static void ensureCurrentState(Service.STATE state, Service.STATE expectedState); static void init(Service service, Configuration configuration); static void start(Service service); static void deploy(Service service, Configuration configuration); static void stop(Service service); static Exception stopQuietly(Service service); }### Answer: @Test public void testInitTwice() throws Throwable { BreakableService svc = new BreakableService(); Configuration conf = new Configuration(); conf.set("test.init", "t"); ServiceOperations.init(svc, conf); try { ServiceOperations.init(svc, new Configuration()); fail("Expected a failure, got " + svc); } catch (IllegalStateException e) { } assertStateCount(svc, Service.STATE.INITED, 1); assertServiceConfigurationContains(svc, "test.init"); }
### Question: ServiceOperations { public static void deploy(Service service, Configuration configuration) { init(service, configuration); start(service); } private ServiceOperations(); static void ensureCurrentState(Service.STATE state, Service.STATE expectedState); static void init(Service service, Configuration configuration); static void start(Service service); static void deploy(Service service, Configuration configuration); static void stop(Service service); static Exception stopQuietly(Service service); }### Answer: @Test public void testDeploy() throws Throwable { BreakableService svc = new BreakableService(); assertServiceStateCreated(svc); ServiceOperations.deploy(svc, new Configuration()); assertServiceStateStarted(svc); assertStateCount(svc, Service.STATE.INITED, 1); assertStateCount(svc, Service.STATE.STARTED, 1); ServiceOperations.stop(svc); assertServiceStateStopped(svc); assertStateCount(svc, Service.STATE.STOPPED, 1); } @Test public void testDeployNotAtomic() throws Throwable { BreakableService svc = new BreakableService(false, true, false); try { ServiceOperations.deploy(svc, new Configuration()); fail("Expected a failure, got " + svc); } catch (BreakableService.BrokenLifecycleEvent expected) { } assertServiceStateInited(svc); assertStateCount(svc, Service.STATE.INITED, 1); assertStateCount(svc, Service.STATE.STARTED, 1); try { ServiceOperations.deploy(svc, new Configuration()); fail("Expected a failure, got " + svc); } catch (IllegalStateException e) { } }
### Question: ServiceOperations { public static void stop(Service service) { if (service != null) { Service.STATE state = service.getServiceState(); if (state == Service.STATE.STARTED) { service.stop(); } } } private ServiceOperations(); static void ensureCurrentState(Service.STATE state, Service.STATE expectedState); static void init(Service service, Configuration configuration); static void start(Service service); static void deploy(Service service, Configuration configuration); static void stop(Service service); static Exception stopQuietly(Service service); }### Answer: @Test public void testStopInit() throws Throwable { BreakableService svc = new BreakableService(); ServiceOperations.stop(svc); assertServiceStateCreated(svc); assertStateCount(svc, Service.STATE.STOPPED, 0); ServiceOperations.stop(svc); assertStateCount(svc, Service.STATE.STOPPED, 0); }
### Question: HFileArchiveUtil { public static Path getArchivePath(Configuration conf) throws IOException { return getArchivePath(FSUtils.getRootDir(conf)); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegion region, byte [] family); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir); static Path getRegionArchiveDir(Path rootdir, Path tabledir, Path regiondir); static Path getTableArchivePath(Path tabledir); static Path getTableArchivePath(final Path rootdir, final String tableName); static Path getTableArchivePath(final Configuration conf, final String tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetArchivePath() throws Exception { Configuration conf = new Configuration(); FSUtils.setRootDir(conf, new Path("root")); assertNotNull(HFileArchiveUtil.getArchivePath(conf)); }
### Question: HFileArchiveUtil { public static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir) { Path archiveDir = getTableArchivePath(tabledir); String encodedRegionName = regiondir.getName(); return HRegion.getRegionDir(archiveDir, encodedRegionName); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegion region, byte [] family); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir); static Path getRegionArchiveDir(Path rootdir, Path tabledir, Path regiondir); static Path getTableArchivePath(Path tabledir); static Path getTableArchivePath(final Path rootdir, final String tableName); static Path getTableArchivePath(final Configuration conf, final String tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testRegionArchiveDir() { Configuration conf = null; Path tableDir = new Path("table"); Path regionDir = new Path("region"); assertNotNull(HFileArchiveUtil.getRegionArchiveDir(conf, tableDir, regionDir)); }
### Question: DirectoryCollection { synchronized boolean createNonExistentDirs(FileContext localFs, FsPermission perm) { boolean failed = false; for (final String dir : localDirs) { try { createDir(localFs, new Path(dir), perm); } catch (IOException e) { LOG.warn("Unable to create directory " + dir + " error " + e.getMessage() + ", removing from the list of valid directories."); localDirs.remove(dir); failedDirs.add(dir); numFailures++; failed = true; } } return !failed; } DirectoryCollection(String[] dirs); }### Answer: @Test public void testCreateDirectories() throws IOException { Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077"); FileContext localFs = FileContext.getLocalFSFileContext(conf); String dirA = new File(testDir, "dirA").getPath(); String dirB = new File(dirA, "dirB").getPath(); String dirC = new File(testDir, "dirC").getPath(); Path pathC = new Path(dirC); FsPermission permDirC = new FsPermission((short)0710); localFs.mkdir(pathC, null, true); localFs.setPermission(pathC, permDirC); String[] dirs = { dirA, dirB, dirC }; DirectoryCollection dc = new DirectoryCollection(dirs); FsPermission defaultPerm = FsPermission.getDefault() .applyUMask(new FsPermission((short)FsPermission.DEFAULT_UMASK)); boolean createResult = dc.createNonExistentDirs(localFs, defaultPerm); Assert.assertTrue(createResult); FileStatus status = localFs.getFileStatus(new Path(dirA)); Assert.assertEquals("local dir parent not created with proper permissions", defaultPerm, status.getPermission()); status = localFs.getFileStatus(new Path(dirB)); Assert.assertEquals("local dir not created with proper permissions", defaultPerm, status.getPermission()); status = localFs.getFileStatus(pathC); Assert.assertEquals("existing local directory permissions modified", permDirC, status.getPermission()); }
### Question: NonAggregatingLogHandler extends AbstractService implements LogHandler { @Override public void stop() { if (sched != null) { sched.shutdown(); boolean isShutdown = false; try { isShutdown = sched.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { sched.shutdownNow(); isShutdown = true; } if (!isShutdown) { sched.shutdownNow(); } } super.stop(); } NonAggregatingLogHandler(Dispatcher dispatcher, DeletionService delService, LocalDirsHandlerService dirsHandler); @Override void init(Configuration conf); @Override void stop(); @SuppressWarnings("unchecked") @Override void handle(LogHandlerEvent event); }### Answer: @Test public void testStop() throws Exception { NonAggregatingLogHandler aggregatingLogHandler = new NonAggregatingLogHandler(null, null, null); aggregatingLogHandler.stop(); NonAggregatingLogHandlerWithMockExecutor logHandler = new NonAggregatingLogHandlerWithMockExecutor(null, null, null); logHandler.init(new Configuration()); logHandler.stop(); verify(logHandler.mockSched).shutdown(); verify(logHandler.mockSched) .awaitTermination(eq(10l), eq(TimeUnit.SECONDS)); verify(logHandler.mockSched).shutdownNow(); }
### Question: HFileArchiveUtil { public static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName) throws IOException { Path tableArchiveDir = getTableArchivePath(conf, tableName); return Store.getStoreHomedir(tableArchiveDir, regionName, familyName); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegion region, byte [] family); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir); static Path getRegionArchiveDir(Path rootdir, Path tabledir, Path regiondir); static Path getTableArchivePath(Path tabledir); static Path getTableArchivePath(final Path rootdir, final String tableName); static Path getTableArchivePath(final Configuration conf, final String tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetStoreArchivePath(){ byte[] family = Bytes.toBytes("Family"); Path tabledir = new Path("table"); HRegionInfo region = new HRegionInfo(Bytes.toBytes("table")); Configuration conf = null; assertNotNull(HFileArchiveUtil.getStoreArchivePath(conf, region, tabledir, family)); conf = new Configuration(); assertNotNull(HFileArchiveUtil.getStoreArchivePath(conf, region, tabledir, family)); HRegion mockRegion = Mockito.mock(HRegion.class); Mockito.when(mockRegion.getRegionInfo()).thenReturn(region); Mockito.when(mockRegion.getTableDir()).thenReturn(tabledir); assertNotNull(HFileArchiveUtil.getStoreArchivePath(null, mockRegion, family)); conf = new Configuration(); assertNotNull(HFileArchiveUtil.getStoreArchivePath(conf, mockRegion, family)); }
### Question: AuxServices extends AbstractService implements ServiceStateChangeListener, EventHandler<AuxServicesEvent> { public AuxServices() { super(AuxServices.class.getName()); serviceMap = Collections.synchronizedMap(new HashMap<String,AuxiliaryService>()); serviceMeta = Collections.synchronizedMap(new HashMap<String,ByteBuffer>()); } AuxServices(); Map<String, ByteBuffer> getMeta(); @Override void init(Configuration conf); @Override void start(); @Override void stop(); @Override void stateChanged(Service service); @Override void handle(AuxServicesEvent event); }### Answer: @Test public void testAuxServices() { Configuration conf = new Configuration(); conf.setStrings(YarnConfiguration.NM_AUX_SERVICES, new String[] { "Asrv", "Bsrv" }); conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT, "Asrv"), ServiceA.class, Service.class); conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT, "Bsrv"), ServiceB.class, Service.class); final AuxServices aux = new AuxServices(); aux.init(conf); int latch = 1; for (Service s : aux.getServices()) { assertEquals(INITED, s.getServiceState()); if (s instanceof ServiceA) { latch *= 2; } else if (s instanceof ServiceB) { latch *= 3; } else fail("Unexpected service type " + s.getClass()); } assertEquals("Invalid mix of services", 6, latch); aux.start(); for (Service s : aux.getServices()) { assertEquals(STARTED, s.getServiceState()); } aux.stop(); for (Service s : aux.getServices()) { assertEquals(STOPPED, s.getServiceState()); } }
### Question: ResourceManager extends CompositeService implements Recoverable { public RMContext getRMContext() { return this.rmContext; } ResourceManager(); RMContext getRMContext(); @Override synchronized void init(Configuration conf); @Override void start(); @Override void stop(); @Private ClientRMService getClientRMService(); @Private ResourceScheduler getResourceScheduler(); @Private ResourceTrackerService getResourceTrackerService(); @Private ApplicationMasterService getApplicationMasterService(); @Private ApplicationACLsManager getApplicationACLsManager(); @Private RMContainerTokenSecretManager getRMContainerTokenSecretManager(); @Private ApplicationTokenSecretManager getApplicationTokenSecretManager(); @Override void recover(RMState state); static void main(String argv[]); static final int SHUTDOWN_HOOK_PRIORITY; static final long clusterTimeStamp; }### Answer: @Test public void testNodeHealthReportIsNotNull() throws Exception{ String host1 = "host1"; final int memory = 4 * 1024; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm1 = registerNode(host1, 1234, 2345, NetworkTopology.DEFAULT_RACK, memory); nm1.heartbeat(); nm1.heartbeat(); Collection<RMNode> values = resourceManager.getRMContext().getRMNodes().values(); for (RMNode ni : values) { NodeHealthStatus nodeHealthStatus = ni.getNodeHealthStatus(); String healthReport = nodeHealthStatus.getHealthReport(); assertNotNull(healthReport); } }
### Question: RMAuditLogger { static void start(Keys key, String value, StringBuilder b) { b.append(key.name()).append(AuditConstants.KEY_VAL_SEPARATOR).append(value); } static void logSuccess(String user, String operation, String target, ApplicationId appId, ContainerId containerId); static void logSuccess(String user, String operation, String target, ApplicationId appId, ApplicationAttemptId attemptId); static void logSuccess(String user, String operation, String target, ApplicationId appId); static void logSuccess(String user, String operation, String target); static void logFailure(String user, String operation, String perm, String target, String description, ApplicationId appId, ContainerId containerId); static void logFailure(String user, String operation, String perm, String target, String description, ApplicationId appId, ApplicationAttemptId attemptId); static void logFailure(String user, String operation, String perm, String target, String description, ApplicationId appId); static void logFailure(String user, String operation, String perm, String target, String description); }### Answer: @Test public void testRMAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); Server server = RPC.getServer(TestProtocol.class, new MyTestRPCServer(), "0.0.0.0", 0, 5, true, conf, null); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); TestProtocol proxy = (TestProtocol)RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); server.stop(); } @Test public void testRMAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); Server server = RPC.getServer(new MyTestRPCServer(), "0.0.0.0", 0, conf); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); TestProtocol proxy = (TestProtocol)RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); server.stop(); }
### Question: FifoScheduler implements ResourceScheduler, Configurable { @Override public QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive) { return DEFAULT_QUEUE.getQueueInfo(false, false); } @Override synchronized void setConf(Configuration conf); @Override synchronized Configuration getConf(); @Override Resource getMinimumResourceCapability(); @Override int getNumClusterNodes(); @Override Resource getMaximumResourceCapability(); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @Override Allocation allocate( ApplicationAttemptId applicationAttemptId, List<ResourceRequest> ask, List<ContainerId> release); @Override SchedulerAppReport getSchedulerAppInfo( ApplicationAttemptId applicationAttemptId); @Override void handle(SchedulerEvent event); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override void recover(RMState state); @Override synchronized SchedulerNodeReport getNodeReport(NodeId nodeId); @Override QueueMetrics getRootQueueMetrics(); }### Answer: @Test public void testFifoSchedulerCapacityWhenNoNMs() { FifoScheduler scheduler = new FifoScheduler(); QueueInfo queueInfo = scheduler.getQueueInfo(null, false, false); Assert.assertEquals(0.0f, queueInfo.getCurrentCapacity()); }
### Question: SchedulerUtils { public static void normalizeRequest(ResourceRequest ask, int minMemory) { int memory = Math.max(ask.getCapability().getMemory(), minMemory); ask.getCapability().setMemory( minMemory * ((memory / minMemory) + (memory % minMemory > 0 ? 1 : 0))); } static ContainerStatus createAbnormalContainerStatus( ContainerId containerId, String diagnostics); static void normalizeRequests(List<ResourceRequest> asks, int minMemory); static void normalizeRequest(ResourceRequest ask, int minMemory); static final String RELEASED_CONTAINER; static final String LOST_CONTAINER; static final String PREEMPTED_CONTAINER; static final String COMPLETED_APPLICATION; static final String EXPIRED_CONTAINER; static final String UNRESERVED_CONTAINER; }### Answer: @Test public void testNormalizeRequest() { int minMemory = 1024; ResourceRequest ask = new ResourceRequestPBImpl(); ask.setCapability(Resource.createResource(-1024)); SchedulerUtils.normalizeRequest(ask, minMemory); assertEquals(minMemory, ask.getCapability().getMemory()); ask.setCapability(Resource.createResource(0)); SchedulerUtils.normalizeRequest(ask, minMemory); assertEquals(minMemory, ask.getCapability().getMemory()); ask.setCapability(Resource.createResource(2 * minMemory)); SchedulerUtils.normalizeRequest(ask, minMemory); assertEquals(2 * minMemory, ask.getCapability().getMemory()); ask.setCapability(Resource.createResource(minMemory + 10)); SchedulerUtils.normalizeRequest(ask, minMemory); assertEquals(2 * minMemory, ask.getCapability().getMemory()); }
### Question: ProxyUriUtils { public static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved) { StringBuilder newp = new StringBuilder(); newp.append(getPath(id, path)); boolean first = appendQuery(newp, query, true); if(approved) { appendQuery(newp, PROXY_APPROVAL_PARAM+"=true", first); } return newp.toString(); } static String getPath(ApplicationId id); static String getPath(ApplicationId id, String path); static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved); static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id); static URI getUriFromAMUrl(String noSchemeUrl); static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins); static final String PROXY_SERVLET_NAME; static final String PROXY_BASE; static final String PROXY_PATH_SPEC; static final String PROXY_APPROVAL_PARAM; }### Answer: @Test public void testGetPathAndQuery() { assertEquals("/proxy/application_6384623_0005/static/app?foo=bar", ProxyUriUtils.getPathAndQuery(BuilderUtils.newApplicationId(6384623l, 5), "/static/app", "?foo=bar", false)); assertEquals("/proxy/application_6384623_0005/static/app?foo=bar&bad=good&proxyapproved=true", ProxyUriUtils.getPathAndQuery(BuilderUtils.newApplicationId(6384623l, 5), "/static/app", "foo=bar&bad=good", true)); }
### Question: ProxyUriUtils { public static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id) { try { String path = getPath(id, originalUri == null ? "/" : originalUri.getPath()); return new URI(proxyUri.getScheme(), proxyUri.getAuthority(), path, originalUri == null ? null : originalUri.getQuery(), originalUri == null ? null : originalUri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException("Could not proxify "+originalUri,e); } } static String getPath(ApplicationId id); static String getPath(ApplicationId id, String path); static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved); static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id); static URI getUriFromAMUrl(String noSchemeUrl); static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins); static final String PROXY_SERVLET_NAME; static final String PROXY_BASE; static final String PROXY_PATH_SPEC; static final String PROXY_APPROVAL_PARAM; }### Answer: @Test public void testGetProxyUri() throws Exception { URI originalUri = new URI("http: URI proxyUri = new URI("http: ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); URI expected = new URI("http: URI result = ProxyUriUtils.getProxyUri(originalUri, proxyUri, id); assertEquals(expected, result); } @Test public void testGetProxyUriNull() throws Exception { URI originalUri = null; URI proxyUri = new URI("http: ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); URI expected = new URI("http: URI result = ProxyUriUtils.getProxyUri(originalUri, proxyUri, id); assertEquals(expected, result); }
### Question: ProxyUriUtils { public static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins) throws URISyntaxException { URI toRet = null; for(TrackingUriPlugin plugin : trackingUriPlugins) { toRet = plugin.getTrackingUri(id); if (toRet != null) { return toRet; } } return null; } static String getPath(ApplicationId id); static String getPath(ApplicationId id, String path); static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved); static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id); static URI getUriFromAMUrl(String noSchemeUrl); static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins); static final String PROXY_SERVLET_NAME; static final String PROXY_BASE; static final String PROXY_PATH_SPEC; static final String PROXY_APPROVAL_PARAM; }### Answer: @Test public void testGetProxyUriFromPluginsReturnsNullIfNoPlugins() throws URISyntaxException { ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); List<TrackingUriPlugin> list = Lists.newArrayListWithExpectedSize(0); assertNull(ProxyUriUtils.getUriFromTrackingPlugins(id, list)); } @Test public void testGetProxyUriFromPluginsReturnsValidUriWhenAble() throws URISyntaxException { ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); List<TrackingUriPlugin> list = Lists.newArrayListWithExpectedSize(2); list.add(new TrackingUriPlugin() { public URI getTrackingUri(ApplicationId id) throws URISyntaxException { return null; } }); list.add(new TrackingUriPlugin() { public URI getTrackingUri(ApplicationId id) throws URISyntaxException { return new URI("http: } }); URI result = ProxyUriUtils.getUriFromTrackingPlugins(id, list); assertNotNull(result); }
### Question: KerberosName { public String getRealm() { return realm; } KerberosName(String name); String getDefaultRealm(); @Override String toString(); String getServiceName(); String getHostName(); String getRealm(); String getShortName(); static void setRules(String ruleString); static boolean hasRulesBeenSet(); }### Answer: @Test public void testRules() throws Exception { checkTranslation("omalley@" + KerberosTestUtils.getRealm(), "omalley"); checkTranslation("hdfs/10.0.0.1@" + KerberosTestUtils.getRealm(), "hdfs"); checkTranslation("[email protected]", "oom"); checkTranslation("johndoe/[email protected]", "guest"); checkTranslation("joe/[email protected]", "joe"); checkTranslation("joe/[email protected]", "root"); }
### Question: DataChecksum implements Checksum { @Override public String toString() { String strType = getNameOfType(type); return "DataChecksum(type=" + strType + ", chunkSize=" + bytesPerChecksum + ")"; } private DataChecksum( int checksumType, Checksum checksum, int sumSize, int chunkSize ); static DataChecksum newDataChecksum( int type, int bytesPerChecksum ); static DataChecksum newDataChecksum( byte bytes[], int offset ); static DataChecksum newDataChecksum( DataInputStream in ); void writeHeader( DataOutputStream out ); byte[] getHeader(); int writeValue( DataOutputStream out, boolean reset ); int writeValue( byte[] buf, int offset, boolean reset ); boolean compare( byte buf[], int offset ); int getChecksumType(); int getChecksumSize(); int getBytesPerChecksum(); int getNumBytesInSum(); static int getChecksumHeaderSize(); long getValue(); void reset(); void update( byte[] b, int off, int len ); void update( int b ); void verifyChunkedSums(ByteBuffer data, ByteBuffer checksums, String fileName, long basePos); void calculateChunkedSums(ByteBuffer data, ByteBuffer checksums); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); static String getNameOfType(int checksumType); static int getTypeFromName(String checksumName); static final int HEADER_LEN; static final int CHECKSUM_NULL; static final int CHECKSUM_CRC32; static final int CHECKSUM_CRC32C; static final int CHECKSUM_DEFAULT; static final int CHECKSUM_MIXED; static final int SIZE_OF_INTEGER; }### Answer: @Test public void testToString() { assertEquals("DataChecksum(type=CRC32, chunkSize=512)", DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_CRC32, 512) .toString()); }
### Question: HostsFileReader { public synchronized void refresh() throws IOException { LOG.info("Refreshing hosts (include/exclude) list"); if (!includesFile.equals("")) { Set<String> newIncludes = new HashSet<String>(); readFileToSet(includesFile, newIncludes); includes = newIncludes; } if (!excludesFile.equals("")) { Set<String> newExcludes = new HashSet<String>(); readFileToSet(excludesFile, newExcludes); excludes = newExcludes; } } HostsFileReader(String inFile, String exFile); synchronized void refresh(); synchronized Set<String> getHosts(); synchronized Set<String> getExcludedHosts(); synchronized void setIncludesFile(String includesFile); synchronized void setExcludesFile(String excludesFile); synchronized void updateFileNames(String includesFile, String excludesFile); }### Answer: @Test public void testRefreshHostFileReaderWithNonexistentFile() throws Exception { FileWriter efw = new FileWriter(excludesFile); FileWriter ifw = new FileWriter(includesFile); efw.close(); ifw.close(); HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile); assertTrue(INCLUDES_FILE.delete()); try { hfp.refresh(); Assert.fail("Should throw FileNotFoundException"); } catch (FileNotFoundException ex) { } }
### Question: NativeLibraryChecker { public static void main(String[] args) { String usage = "NativeLibraryChecker [-a|-h]\n" + " -a use -a to check all libraries are available\n" + " by default just check hadoop library is available\n" + " exit with error code if check failed\n" + " -h print this message\n"; if (args.length > 1 || (args.length == 1 && !(args[0].equals("-a") || args[0].equals("-h")))) { System.err.println(usage); ExitUtil.terminate(1); } boolean checkAll = false; if (args.length == 1) { if (args[0].equals("-h")) { System.out.println(usage); return; } checkAll = true; } boolean nativeHadoopLoaded = NativeCodeLoader.isNativeCodeLoaded(); boolean zlibLoaded = false; boolean snappyLoaded = false; boolean lz4Loaded = nativeHadoopLoaded; if (nativeHadoopLoaded) { zlibLoaded = ZlibFactory.isNativeZlibLoaded(new Configuration()); snappyLoaded = NativeCodeLoader.buildSupportsSnappy() && SnappyCodec.isNativeCodeLoaded(); } System.out.println("Native library checking:"); System.out.printf("hadoop: %b\n", nativeHadoopLoaded); System.out.printf("zlib: %b\n", zlibLoaded); System.out.printf("snappy: %b\n", snappyLoaded); System.out.printf("lz4: %b\n", lz4Loaded); if ((!nativeHadoopLoaded) || (checkAll && !(zlibLoaded && snappyLoaded && lz4Loaded))) { ExitUtil.terminate(1); } } static void main(String[] args); }### Answer: @Test public void testNativeLibraryChecker() { ExitUtil.disableSystemExit(); NativeLibraryChecker.main(new String[] {"-h"}); expectExit(new String[] {"-a", "-h"}); expectExit(new String[] {"aaa"}); if (NativeCodeLoader.isNativeCodeLoaded()) { NativeLibraryChecker.main(new String[0]); } else { expectExit(new String[0]); } }
### Question: NativeCodeLoader { public static boolean isNativeCodeLoaded() { return nativeCodeLoaded; } static boolean isNativeCodeLoaded(); static native boolean buildSupportsSnappy(); boolean getLoadNativeLibraries(Configuration conf); void setLoadNativeLibraries(Configuration conf, boolean loadNativeLibraries); }### Answer: @Test public void testNativeCodeLoaded() { if (requireTestJni() == false) { LOG.info("TestNativeCodeLoader: libhadoop.so testing is not required."); return; } if (!NativeCodeLoader.isNativeCodeLoaded()) { fail("TestNativeCodeLoader: libhadoop.so testing was required, but " + "libhadoop.so was not loaded."); } LOG.info("TestNativeCodeLoader: libhadoop.so is loaded."); }
### Question: ClassUtil { public static String findContainingJar(Class clazz) { ClassLoader loader = clazz.getClassLoader(); String classFile = clazz.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(classFile); itr.hasMoreElements();) { URL url = (URL) itr.nextElement(); if ("jar".equals(url.getProtocol())) { String toReturn = url.getPath(); if (toReturn.startsWith("file:")) { toReturn = toReturn.substring("file:".length()); } toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; } static String findContainingJar(Class clazz); }### Answer: @Test(timeout=1000) public void testFindContainingJar() { String containingJar = ClassUtil.findContainingJar(Logger.class); Assert.assertNotNull("Containing jar not found for Logger", containingJar); File jarFile = new File(containingJar); Assert.assertTrue("Containing jar does not exist on file system", jarFile.exists()); Assert.assertTrue("Incorrect jar file" + containingJar, jarFile.getName().matches("log4j.+[.]jar")); }
### Question: NodeFencer { public boolean fence(HAServiceTarget fromSvc) { LOG.info("====== Beginning Service Fencing Process... ======"); int i = 0; for (FenceMethodWithArg method : methods) { LOG.info("Trying method " + (++i) + "/" + methods.size() +": " + method); try { if (method.method.tryFence(fromSvc, method.arg)) { LOG.info("====== Fencing successful by method " + method + " ======"); return true; } } catch (BadFencingConfigurationException e) { LOG.error("Fencing method " + method + " misconfigured", e); continue; } catch (Throwable t) { LOG.error("Fencing method " + method + " failed with an unexpected error.", t); continue; } LOG.warn("Fencing method " + method + " was unsuccessful."); } LOG.error("Unable to fence service by any configured method."); return false; } NodeFencer(Configuration conf, String spec); static NodeFencer create(Configuration conf, String confKey); boolean fence(HAServiceTarget fromSvc); }### Answer: @Test public void testShortNameShell() throws BadFencingConfigurationException { NodeFencer fencer = setupFencer("shell(true)"); assertTrue(fencer.fence(MOCK_TARGET)); }
### Question: HAZKUtil { public static List<ZKAuthInfo> parseAuth(String authString) { List<ZKAuthInfo> ret = Lists.newArrayList(); if (authString == null) { return ret; } List<String> authComps = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults() .split(authString)); for (String comp : authComps) { String parts[] = comp.split(":", 2); if (parts.length != 2) { throw new BadAuthFormatException( "Auth '" + comp + "' not of expected form scheme:auth"); } ret.add(new ZKAuthInfo(parts[0], parts[1].getBytes(Charsets.UTF_8))); } return ret; } static List<ACL> parseACLs(String aclString); static List<ZKAuthInfo> parseAuth(String authString); static String resolveConfIndirection(String valInConf); }### Answer: @Test public void testEmptyAuth() { List<ZKAuthInfo> result = HAZKUtil.parseAuth(""); assertTrue(result.isEmpty()); } @Test public void testNullAuth() { List<ZKAuthInfo> result = HAZKUtil.parseAuth(null); assertTrue(result.isEmpty()); } @Test public void testGoodAuths() { List<ZKAuthInfo> result = HAZKUtil.parseAuth( "scheme:data,\n scheme2:user:pass"); assertEquals(2, result.size()); ZKAuthInfo auth0 = result.get(0); assertEquals("scheme", auth0.getScheme()); assertEquals("data", new String(auth0.getAuth())); ZKAuthInfo auth1 = result.get(1); assertEquals("scheme2", auth1.getScheme()); assertEquals("user:pass", new String(auth1.getAuth())); }
### Question: HAZKUtil { public static String resolveConfIndirection(String valInConf) throws IOException { if (valInConf == null) return null; if (!valInConf.startsWith("@")) { return valInConf; } String path = valInConf.substring(1).trim(); return Files.toString(new File(path), Charsets.UTF_8).trim(); } static List<ACL> parseACLs(String aclString); static List<ZKAuthInfo> parseAuth(String authString); static String resolveConfIndirection(String valInConf); }### Answer: @Test public void testConfIndirection() throws IOException { assertNull(HAZKUtil.resolveConfIndirection(null)); assertEquals("x", HAZKUtil.resolveConfIndirection("x")); TEST_FILE.getParentFile().mkdirs(); Files.write("hello world", TEST_FILE, Charsets.UTF_8); assertEquals("hello world", HAZKUtil.resolveConfIndirection( "@" + TEST_FILE.getAbsolutePath())); try { HAZKUtil.resolveConfIndirection("@" + BOGUS_FILE); fail("Did not throw for non-existent file reference"); } catch (FileNotFoundException fnfe) { assertTrue(fnfe.getMessage().startsWith(BOGUS_FILE)); } }
### Question: ActiveStandbyElector implements StatCallback, StringCallback { public synchronized void joinElection(byte[] data) throws HadoopIllegalArgumentException { if (data == null) { throw new HadoopIllegalArgumentException("data cannot be null"); } if (wantToBeInElection) { LOG.info("Already in election. Not re-connecting."); return; } appData = new byte[data.length]; System.arraycopy(data, 0, appData, 0, data.length); LOG.debug("Attempting active election for " + this); joinElectionInternal(); } ActiveStandbyElector(String zookeeperHostPorts, int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl, List<ZKAuthInfo> authInfo, ActiveStandbyElectorCallback app); synchronized void joinElection(byte[] data); synchronized boolean parentZNodeExists(); synchronized void ensureParentZNode(); synchronized void clearParentZNode(); synchronized void quitElection(boolean needFence); synchronized byte[] getActiveData(); @Override synchronized void processResult(int rc, String path, Object ctx, String name); @Override synchronized void processResult(int rc, String path, Object ctx, Stat stat); @Override String toString(); static final Log LOG; }### Answer: @Test(expected = HadoopIllegalArgumentException.class) public void testJoinElectionException() { elector.joinElection(null); } @Test public void testJoinElection() { elector.joinElection(data); Mockito.verify(mockZK, Mockito.times(1)).create(ZK_LOCK_NAME, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK); }
### Question: ActiveStandbyElector implements StatCallback, StringCallback { public synchronized void quitElection(boolean needFence) { LOG.info("Yielding from election"); if (!needFence && state == State.ACTIVE) { tryDeleteOwnBreadCrumbNode(); } reset(); wantToBeInElection = false; } ActiveStandbyElector(String zookeeperHostPorts, int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl, List<ZKAuthInfo> authInfo, ActiveStandbyElectorCallback app); synchronized void joinElection(byte[] data); synchronized boolean parentZNodeExists(); synchronized void ensureParentZNode(); synchronized void clearParentZNode(); synchronized void quitElection(boolean needFence); synchronized byte[] getActiveData(); @Override synchronized void processResult(int rc, String path, Object ctx, String name); @Override synchronized void processResult(int rc, String path, Object ctx, Stat stat); @Override String toString(); static final Log LOG; }### Answer: @Test public void testQuitElection() throws Exception { elector.joinElection(data); Mockito.verify(mockZK, Mockito.times(0)).close(); elector.quitElection(true); Mockito.verify(mockZK, Mockito.times(1)).close(); verifyExistCall(0); byte[] data = new byte[8]; elector.joinElection(data); Assert.assertEquals(2, count); elector.processResult(Code.NODEEXISTS.intValue(), ZK_LOCK_NAME, mockZK, ZK_LOCK_NAME); Mockito.verify(mockApp, Mockito.times(1)).becomeStandby(); verifyExistCall(1); }
### Question: HAAdmin extends Configured implements Tool { private int help(String[] argv) { if (argv.length == 1) { printUsage(out); return 0; } else if (argv.length != 2) { printUsage(errOut, "-help"); return -1; } String cmd = argv[1]; if (!cmd.startsWith("-")) { cmd = "-" + cmd; } UsageInfo usageInfo = USAGE.get(cmd); if (usageInfo == null) { errOut.println(cmd + ": Unknown command"); printUsage(errOut); return -1; } out.println(cmd + " [" + usageInfo.args + "]: " + usageInfo.help); return 0; } @Override void setConf(Configuration conf); @Override int run(String[] argv); }### Answer: @Test public void testHelp() throws Exception { assertEquals(0, runTool("-help")); assertEquals(0, runTool("-help", "transitionToActive")); assertOutputContains("Transitions the service into Active"); }
### Question: HealthMonitor { public void addCallback(Callback cb) { this.callbacks.add(cb); } HealthMonitor(Configuration conf, HAServiceTarget target); void addCallback(Callback cb); void removeCallback(Callback cb); void shutdown(); synchronized HAServiceProtocol getProxy(); }### Answer: @Test(timeout=15000) public void testCallbackThrowsRTE() throws Exception { hm.addCallback(new Callback() { @Override public void enteredState(State newState) { throw new RuntimeException("Injected RTE"); } }); LOG.info("Mocking bad health check, waiting for UNHEALTHY"); svc.isHealthy = false; waitForState(hm, HealthMonitor.State.HEALTH_MONITOR_FAILED); }
### Question: ByteBufferUtils { public static void putInt(OutputStream out, final int value) throws IOException { for (int i = Bytes.SIZEOF_INT - 1; i >= 0; --i) { out.write((byte) (value >>> (i * 8))); } } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testPutInt() { testPutInt(0); testPutInt(Integer.MAX_VALUE); for (int i = 0; i < 3; i++) { testPutInt((128 << i) - 1); } for (int i = 0; i < 3; i++) { testPutInt((128 << i)); } }
### Question: IOUtils { public static int wrappedReadForCompressedData(InputStream is, byte[] buf, int off, int len) throws IOException { try { return is.read(buf, off, len); } catch (IOException ie) { throw ie; } catch (Throwable t) { throw new IOException("Error while reading compressed data", t); } } static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close); static void copyBytes(InputStream in, OutputStream out, int buffSize); static void copyBytes(InputStream in, OutputStream out, Configuration conf); static void copyBytes(InputStream in, OutputStream out, Configuration conf, boolean close); static void copyBytes(InputStream in, OutputStream out, long count, boolean close); static int wrappedReadForCompressedData(InputStream is, byte[] buf, int off, int len); static void readFully(InputStream in, byte buf[], int off, int len); static void skipFully(InputStream in, long len); static void cleanup(Log log, java.io.Closeable... closeables); static void closeStream(java.io.Closeable stream); static void closeSocket(Socket sock); static void writeFully(WritableByteChannel bc, ByteBuffer buf); static void writeFully(FileChannel fc, ByteBuffer buf, long offset); }### Answer: @Test public void testWrappedReadForCompressedData() throws IOException { byte[] buf = new byte[2]; InputStream mockStream = Mockito.mock(InputStream.class); Mockito.when(mockStream.read(buf, 0, 1)).thenReturn(1); Mockito.when(mockStream.read(buf, 0, 2)).thenThrow( new java.lang.InternalError()); try { assertEquals("Check expected value", 1, IOUtils.wrappedReadForCompressedData(mockStream, buf, 0, 1)); } catch (IOException ioe) { fail("Unexpected error while reading"); } try { IOUtils.wrappedReadForCompressedData(mockStream, buf, 0, 2); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains( "Error while reading compressed data", ioe); } }
### Question: SecureIOUtils { static FileInputStream forceSecureOpenForRead(File f, String expectedOwner, String expectedGroup) throws IOException { FileInputStream fis = new FileInputStream(f); boolean success = false; try { Stat stat = NativeIO.getFstat(fis.getFD()); checkStat(f, stat.getOwner(), stat.getGroup(), expectedOwner, expectedGroup); success = true; return fis; } finally { if (!success) { fis.close(); } } } static FileInputStream openForRead(File f, String expectedOwner, String expectedGroup); static FileOutputStream createForWrite(File f, int permissions); }### Answer: @Test public void testReadIncorrectlyRestrictedWithSecurity() throws IOException { assumeTrue(NativeIO.isAvailable()); System.out.println("Running test with native libs..."); try { SecureIOUtils .forceSecureOpenForRead(testFilePath, "invalidUser", null).close(); fail("Didn't throw expection for wrong ownership!"); } catch (IOException ioe) { } }
### 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) { LOG.info("No regions under directory:" + tableDir); return; } for (FileStatus region: regions) { visitRegionStoreFiles(fs, region.getPath(), visitor); } } private FSVisitor(); 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: NativeIO { private static native Stat fstat(FileDescriptor fd) throws IOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testFstat() throws Exception { FileOutputStream fos = new FileOutputStream( new File(TEST_DIR, "testfstat")); NativeIO.Stat stat = NativeIO.getFstat(fos.getFD()); fos.close(); LOG.info("Stat: " + String.valueOf(stat)); assertEquals(System.getProperty("user.name"), stat.getOwner()); assertNotNull(stat.getGroup()); assertTrue(!"".equals(stat.getGroup())); assertEquals("Stat mode field should indicate a regular file", NativeIO.Stat.S_IFREG, stat.getMode() & NativeIO.Stat.S_IFMT); }
### 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) { LOG.info("No regions under directory:" + tableDir); return; } for (FileStatus region: regions) { visitRegionRecoveredEdits(fs, region.getPath(), visitor); } } private FSVisitor(); 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: NativeIO { static native String getUserName(int uid) throws IOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testGetUserName() throws IOException { assertFalse(NativeIO.getUserName(0).isEmpty()); }
### Question: NativeIO { static native String getGroupName(int uid) throws IOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testGetGroupName() throws IOException { assertFalse(NativeIO.getGroupName(0).isEmpty()); }
### Question: SampleQuantiles { synchronized public void clear() { count = 0; bufferCount = 0; samples.clear(); } SampleQuantiles(Quantile[] quantiles); synchronized void insert(long v); synchronized Map<Quantile, Long> snapshot(); synchronized long getCount(); @VisibleForTesting synchronized int getSampleCount(); synchronized void clear(); }### Answer: @Test public void testClear() throws IOException { for (int i = 0; i < 1000; i++) { estimator.insert(i); } estimator.clear(); assertEquals(estimator.getCount(), 0); assertEquals(estimator.getSampleCount(), 0); try { estimator.snapshot(); fail("Expected IOException for an empty window."); } catch (IOException e) { GenericTestUtils.assertExceptionContains("No samples", e); } }
### Question: FSVisitor { public static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor) throws IOException { Path logsDir = new Path(rootDir, HConstants.HREGION_LOGDIR_NAME); FileStatus[] logServerDirs = FSUtils.listStatus(fs, logsDir); if (logServerDirs == null) { LOG.info("No logs under directory:" + logsDir); return; } for (FileStatus serverLogs: logServerDirs) { String serverName = serverLogs.getPath().getName(); FileStatus[] hlogs = FSUtils.listStatus(fs, serverLogs.getPath()); if (hlogs == null) { LOG.debug("No hfiles found for server: " + serverName + ", skipping."); continue; } for (FileStatus hlogRef: hlogs) { visitor.logFile(serverName, hlogRef.getPath().getName()); } } } private FSVisitor(); 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 testVisitLogFiles() throws IOException { final Set<String> servers = new HashSet<String>(); final Set<String> logs = new HashSet<String>(); FSVisitor.visitLogFiles(fs, rootDir, new FSVisitor.LogFileVisitor() { public void logFile (final String server, final String logfile) throws IOException { servers.add(server); logs.add(logfile); } }); assertEquals(regionServers, servers); assertEquals(serverLogs, logs); }
### Question: PathData implements Comparable<PathData> { public PathData[] getDirectoryContents() throws IOException { checkIfExists(FileTypeRequirement.SHOULD_BE_DIRECTORY); FileStatus[] stats = fs.listStatus(path); PathData[] items = new PathData[stats.length]; for (int i=0; i < stats.length; i++) { String child = getStringForChildPath(stats[i].getPath()); items[i] = new PathData(fs, child, stats[i]); } Arrays.sort(items); return items; } PathData(String pathString, Configuration conf); PathData(File localPath, Configuration conf); private PathData(FileSystem fs, String pathString); private PathData(FileSystem fs, String pathString, FileStatus stat); FileStatus refreshStatus(); PathData suffix(String extension); boolean parentExists(); boolean representsDirectory(); PathData[] getDirectoryContents(); PathData getPathDataForChild(PathData child); static PathData[] expandAsGlob(String pattern, Configuration conf); String toString(); File toFile(); @Override int compareTo(PathData o); @Override boolean equals(Object o); @Override int hashCode(); final FileSystem fs; final Path path; public FileStatus stat; public boolean exists; }### Answer: @Test public void testUnqualifiedUriContents() throws Exception { String dirString = "d1"; PathData item = new PathData(dirString, conf); PathData[] items = item.getDirectoryContents(); assertEquals( sortedString("d1/f1", "d1/f1.1", "d1/f2"), sortedString(items) ); } @Test public void testCwdContents() throws Exception { String dirString = Path.CUR_DIR; PathData item = new PathData(dirString, conf); PathData[] items = item.getDirectoryContents(); assertEquals( sortedString("d1", "d2"), sortedString(items) ); }
### Question: PathData implements Comparable<PathData> { public File toFile() { if (!(fs instanceof LocalFileSystem)) { throw new IllegalArgumentException("Not a local path: " + path); } return ((LocalFileSystem)fs).pathToFile(path); } PathData(String pathString, Configuration conf); PathData(File localPath, Configuration conf); private PathData(FileSystem fs, String pathString); private PathData(FileSystem fs, String pathString, FileStatus stat); FileStatus refreshStatus(); PathData suffix(String extension); boolean parentExists(); boolean representsDirectory(); PathData[] getDirectoryContents(); PathData getPathDataForChild(PathData child); static PathData[] expandAsGlob(String pattern, Configuration conf); String toString(); File toFile(); @Override int compareTo(PathData o); @Override boolean equals(Object o); @Override int hashCode(); final FileSystem fs; final Path path; public FileStatus stat; public boolean exists; }### Answer: @Test public void testToFile() throws Exception { PathData item = new PathData(".", conf); assertEquals(new File(testDir.toString()), item.toFile()); item = new PathData("d1/f1", conf); assertEquals(new File(testDir + "/d1/f1"), item.toFile()); item = new PathData(testDir + "/d1/f1", conf); assertEquals(new File(testDir + "/d1/f1"), item.toFile()); }
### Question: PathData implements Comparable<PathData> { public String toString() { String scheme = uri.getScheme(); String decodedRemainder = uri.getSchemeSpecificPart(); if (scheme == null) { return decodedRemainder; } else { StringBuilder buffer = new StringBuilder(); buffer.append(scheme); buffer.append(":"); buffer.append(decodedRemainder); return buffer.toString(); } } PathData(String pathString, Configuration conf); PathData(File localPath, Configuration conf); private PathData(FileSystem fs, String pathString); private PathData(FileSystem fs, String pathString, FileStatus stat); FileStatus refreshStatus(); PathData suffix(String extension); boolean parentExists(); boolean representsDirectory(); PathData[] getDirectoryContents(); PathData getPathDataForChild(PathData child); static PathData[] expandAsGlob(String pattern, Configuration conf); String toString(); File toFile(); @Override int compareTo(PathData o); @Override boolean equals(Object o); @Override int hashCode(); final FileSystem fs; final Path path; public FileStatus stat; public boolean exists; }### Answer: @Test public void testWithStringAndConfForBuggyPath() throws Exception { String dirString = "file: Path tmpDir = new Path(dirString); PathData item = new PathData(dirString, conf); assertEquals("file:/tmp", tmpDir.toString()); checkPathData(dirString, item); }
### Question: HarFileSystem extends FilterFileSystem { public FileChecksum getFileChecksum(Path f) { return null; } HarFileSystem(); HarFileSystem(FileSystem fs); @Override String getScheme(); void initialize(URI name, Configuration conf); int getHarVersion(); Path getWorkingDirectory(); @Override URI getUri(); @Override Path makeQualified(Path path); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); static int getHarHash(Path p); @Override FileStatus getFileStatus(Path f); FileChecksum getFileChecksum(Path f); @Override FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream create(Path f, int bufferSize); FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override void close(); @Override boolean setReplication(Path src, short replication); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); Path getHomeDirectory(); void setWorkingDirectory(Path newDir); boolean mkdirs(Path f, FsPermission permission); void copyFromLocalFile(boolean delSrc, Path src, Path dst); void copyToLocalFile(boolean delSrc, Path src, Path dst); Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); void setOwner(Path p, String username, String groupname); void setPermission(Path p, FsPermission permisssion); static final int VERSION; }### Answer: @Test public void testFileChecksum() { final Path p = new Path("har: final HarFileSystem harfs = new HarFileSystem(); Assert.assertEquals(null, harfs.getFileChecksum(p)); }
### Question: BlockCacheColumnFamilySummary implements Writable, Comparable<BlockCacheColumnFamilySummary> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BlockCacheColumnFamilySummary other = (BlockCacheColumnFamilySummary) obj; if (columnFamily == null) { if (other.columnFamily != null) return false; } else if (!columnFamily.equals(other.columnFamily)) return false; if (table == null) { if (other.table != null) return false; } else if (!table.equals(other.table)) return false; return true; } BlockCacheColumnFamilySummary(); BlockCacheColumnFamilySummary(String table, String columnFamily); String getTable(); void setTable(String table); String getColumnFamily(); void setColumnFamily(String columnFamily); int getBlocks(); void setBlocks(int blocks); long getHeapSize(); void incrementBlocks(); void incrementHeapSize(long heapSize); void setHeapSize(long heapSize); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static BlockCacheColumnFamilySummary createFromStoreFilePath(Path path); @Override int compareTo(BlockCacheColumnFamilySummary o); static BlockCacheColumnFamilySummary create(BlockCacheColumnFamilySummary e); }### Answer: @Test public void testEquals() { BlockCacheColumnFamilySummary e1 = new BlockCacheColumnFamilySummary(); e1.setTable("table1"); e1.setColumnFamily("cf1"); BlockCacheColumnFamilySummary e2 = new BlockCacheColumnFamilySummary(); e2.setTable("table1"); e2.setColumnFamily("cf1"); assertEquals("bcse", e1, e2); }
### Question: LocalFileSystem extends ChecksumFileSystem { @Override public String getScheme() { return "file"; } LocalFileSystem(); LocalFileSystem(FileSystem rawLocalFileSystem); @Override void initialize(URI name, Configuration conf); @Override String getScheme(); FileSystem getRaw(); File pathToFile(Path path); @Override void copyFromLocalFile(boolean delSrc, Path src, Path dst); @Override void copyToLocalFile(boolean delSrc, Path src, Path dst); boolean reportChecksumFailure(Path p, FSDataInputStream in, long inPos, FSDataInputStream sums, long sumsPos); }### Answer: @Test public void testStatistics() throws Exception { FileSystem.getLocal(new Configuration()); int fileSchemeCount = 0; for (Statistics stats : FileSystem.getAllStatistics()) { if (stats.getScheme().equals("file")) { fileSchemeCount++; } } assertEquals(1, fileSchemeCount); }
### Question: LocalDirAllocator { public File createTmpFileForWrite(String pathStr, long size, Configuration conf) throws IOException { AllocatorPerContext context = obtainContext(contextCfgItemName); return context.createTmpFileForWrite(pathStr, size, conf); } LocalDirAllocator(String contextCfgItemName); Path getLocalPathForWrite(String pathStr, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf, boolean checkWrite); Path getLocalPathToRead(String pathStr, Configuration conf); Iterable<Path> getAllLocalPathsToRead(String pathStr, Configuration conf ); File createTmpFileForWrite(String pathStr, long size, Configuration conf); static boolean isContextValid(String contextCfgItemName); @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) static void removeContext(String contextCfgItemName); boolean ifExists(String pathStr,Configuration conf); static final int SIZE_UNKNOWN; }### Answer: @Test public void testNoSideEffects() throws IOException { if (isWindows) return; String dir = buildBufferDir(ROOT, 0); try { conf.set(CONTEXT, dir); File result = dirAllocator.createTmpFileForWrite(FILENAME, -1, conf); assertTrue(result.delete()); assertTrue(result.getParentFile().delete()); assertFalse(new File(dir).exists()); } finally { Shell.execCommand(new String[]{"chmod", "u+w", BUFFER_DIR_ROOT}); rmBufferDirs(); } }
### Question: LocalDirAllocator { public Path getLocalPathToRead(String pathStr, Configuration conf) throws IOException { AllocatorPerContext context = obtainContext(contextCfgItemName); return context.getLocalPathToRead(pathStr, conf); } LocalDirAllocator(String contextCfgItemName); Path getLocalPathForWrite(String pathStr, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf, boolean checkWrite); Path getLocalPathToRead(String pathStr, Configuration conf); Iterable<Path> getAllLocalPathsToRead(String pathStr, Configuration conf ); File createTmpFileForWrite(String pathStr, long size, Configuration conf); static boolean isContextValid(String contextCfgItemName); @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) static void removeContext(String contextCfgItemName); boolean ifExists(String pathStr,Configuration conf); static final int SIZE_UNKNOWN; }### Answer: @Test public void testGetLocalPathToRead() throws IOException { if (isWindows) return; String dir = buildBufferDir(ROOT, 0); try { conf.set(CONTEXT, dir); assertTrue(localFs.mkdirs(new Path(dir))); File f1 = dirAllocator.createTmpFileForWrite(FILENAME, SMALL_FILE_SIZE, conf); Path p1 = dirAllocator.getLocalPathToRead(f1.getName(), conf); assertEquals(f1.getName(), p1.getName()); assertEquals("file", p1.getFileSystem(conf).getUri().getScheme()); } finally { Shell.execCommand(new String[] { "chmod", "u+w", BUFFER_DIR_ROOT }); rmBufferDirs(); } }
### Question: SlabCache implements SlabItemActionWatcher, BlockCache, HeapSize { Entry<Integer, SingleSizeCache> getHigherBlock(int size) { return sizer.higherEntry(size - 1); } SlabCache(long size, long avgBlockSize); void addSlabByConf(Configuration conf); void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem); void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory); CacheStats getStats(); Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat); boolean evictBlock(BlockCacheKey cacheKey); @Override void onEviction(BlockCacheKey key, SingleSizeCache notifier); @Override void onInsertion(BlockCacheKey key, SingleSizeCache notifier); void shutdown(); long heapSize(); long size(); long getFreeSize(); @Override long getBlockCount(); long getCurrentSize(); long getEvictedCount(); int evictBlocksByHfileName(String hfileName); @Override List<BlockCacheColumnFamilySummary> getBlockCacheColumnFamilySummaries( Configuration conf); }### Answer: @Test public void testElementPlacement() { assertEquals(cache.getHigherBlock(BLOCK_SIZE).getKey().intValue(), (BLOCK_SIZE * 11 / 10)); assertEquals(cache.getHigherBlock((BLOCK_SIZE * 2)).getKey() .intValue(), (BLOCK_SIZE * 21 / 10)); }
### Question: LocalDirAllocator { @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) public static void removeContext(String contextCfgItemName) { synchronized (contexts) { contexts.remove(contextCfgItemName); } } LocalDirAllocator(String contextCfgItemName); Path getLocalPathForWrite(String pathStr, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf, boolean checkWrite); Path getLocalPathToRead(String pathStr, Configuration conf); Iterable<Path> getAllLocalPathsToRead(String pathStr, Configuration conf ); File createTmpFileForWrite(String pathStr, long size, Configuration conf); static boolean isContextValid(String contextCfgItemName); @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) static void removeContext(String contextCfgItemName); boolean ifExists(String pathStr,Configuration conf); static final int SIZE_UNKNOWN; }### Answer: @Test public void testRemoveContext() throws IOException { String dir = buildBufferDir(ROOT, 0); try { String contextCfgItemName = "application_1340842292563_0004.app.cache.dirs"; conf.set(contextCfgItemName, dir); LocalDirAllocator localDirAllocator = new LocalDirAllocator( contextCfgItemName); localDirAllocator.getLocalPathForWrite("p1/x", SMALL_FILE_SIZE, conf); assertTrue(LocalDirAllocator.isContextValid(contextCfgItemName)); LocalDirAllocator.removeContext(contextCfgItemName); assertFalse(LocalDirAllocator.isContextValid(contextCfgItemName)); } finally { rmBufferDirs(); } }
### Question: HFileBlock extends SchemaConfigured implements Cacheable { public int getUncompressedSizeWithoutHeader() { return uncompressedSizeWithoutHeader; } HFileBlock(BlockType blockType, int onDiskSizeWithoutHeader, int uncompressedSizeWithoutHeader, long prevBlockOffset, ByteBuffer buf, boolean fillHeader, long offset, boolean includesMemstoreTS, int minorVersion, int bytesPerChecksum, byte checksumType, int onDiskDataSizeWithHeader); HFileBlock(ByteBuffer b, int minorVersion); BlockType getBlockType(); short getDataBlockEncodingId(); int getOnDiskSizeWithHeader(); int getUncompressedSizeWithoutHeader(); long getPrevBlockOffset(); ByteBuffer getBufferReadOnly(); @Override String toString(); void assumeUncompressed(); void expectType(BlockType expectedType); long getOffset(); DataInputStream getByteStream(); @Override long heapSize(); static boolean readWithExtra(InputStream in, byte buf[], int bufOffset, int necessaryLen, int extraLen); int getNextBlockOnDiskSizeWithHeader(); @Override int getSerializedLength(); @Override void serialize(ByteBuffer destination); @Override CacheableDeserializer<Cacheable> getDeserializer(); @Override boolean equals(Object comparison); boolean doesIncludeMemstoreTS(); DataBlockEncoding getDataBlockEncoding(); int headerSize(); byte[] getDummyHeaderForVersion(); static final boolean FILL_HEADER; static final boolean DONT_FILL_HEADER; static final int ENCODED_HEADER_SIZE; static final int BYTE_BUFFER_HEAP_SIZE; }### Answer: @Test public void testNoCompression() throws IOException { assertEquals(4000, createTestV2Block(NONE, includesMemstoreTS). getBlockForCaching().getUncompressedSizeWithoutHeader()); }
### Question: SecurityUtil { public static String getHostFromPrincipal(String principalName) { return new HadoopKerberosName(principalName).getHostName(); } @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, String hostname); @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, InetAddress addr); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey, String hostname); static String buildDTServiceName(URI uri, int defPort); static String getHostFromPrincipal(String principalName); @InterfaceAudience.Private static void setSecurityInfoProviders(SecurityInfo... providers); static KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf); static TokenInfo getTokenInfo(Class<?> protocol, Configuration conf); static InetSocketAddress getTokenServiceAddr(Token<?> token); static void setTokenService(Token<?> token, InetSocketAddress addr); static Text buildTokenService(InetSocketAddress addr); static Text buildTokenService(URI uri); static T doAsLoginUserOrFatal(PrivilegedAction<T> action); static T doAsLoginUser(PrivilegedExceptionAction<T> action); static T doAsCurrentUser(PrivilegedExceptionAction<T> action); static URLConnection openSecureHttpConnection(URL url); @InterfaceAudience.Private static InetAddress getByName(String hostname); static final Log LOG; static final String HOSTNAME_PATTERN; }### Answer: @Test public void testGetHostFromPrincipal() { assertEquals("host", SecurityUtil.getHostFromPrincipal("service/host@realm")); assertEquals(null, SecurityUtil.getHostFromPrincipal("service@realm")); }
### Question: DomainSocket implements Closeable { public static String getEffectivePath(String path, int port) { return path.replace("_PORT", String.valueOf(port)); } private DomainSocket(String path, int fd); static String getLoadingFailureReason(); @VisibleForTesting static void disableBindPathValidation(); static String getEffectivePath(String path, int port); static DomainSocket bindAndListen(String path); DomainSocket accept(); static DomainSocket connect(String path); boolean isOpen(); String getPath(); DomainInputStream getInputStream(); DomainOutputStream getOutputStream(); DomainChannel getChannel(); void setAttribute(int type, int size); int getAttribute(int type); @Override void close(); void sendFileDescriptors(FileDescriptor jfds[], byte jbuf[], int offset, int length); int receiveFileDescriptors(FileDescriptor[] jfds, byte jbuf[], int offset, int length); int recvFileInputStreams(FileInputStream[] fis, byte buf[], int offset, int length); @Override String toString(); static final int SND_BUF_SIZE; static final int RCV_BUF_SIZE; static final int SND_TIMEO; static final int RCV_TIMEO; }### Answer: @Test(timeout=180000) public void testSocketPathSetGet() throws IOException { Assert.assertEquals("/var/run/hdfs/sock.100", DomainSocket.getEffectivePath("/var/run/hdfs/sock._PORT", 100)); }
### Question: DomainSocket implements Closeable { public static DomainSocket connect(String path) throws IOException { if (loadingFailureReason != null) { throw new UnsupportedOperationException(loadingFailureReason); } int fd = connect0(path); return new DomainSocket(path, fd); } private DomainSocket(String path, int fd); static String getLoadingFailureReason(); @VisibleForTesting static void disableBindPathValidation(); static String getEffectivePath(String path, int port); static DomainSocket bindAndListen(String path); DomainSocket accept(); static DomainSocket connect(String path); boolean isOpen(); String getPath(); DomainInputStream getInputStream(); DomainOutputStream getOutputStream(); DomainChannel getChannel(); void setAttribute(int type, int size); int getAttribute(int type); @Override void close(); void sendFileDescriptors(FileDescriptor jfds[], byte jbuf[], int offset, int length); int receiveFileDescriptors(FileDescriptor[] jfds, byte jbuf[], int offset, int length); int recvFileInputStreams(FileInputStream[] fis, byte buf[], int offset, int length); @Override String toString(); static final int SND_BUF_SIZE; static final int RCV_BUF_SIZE; static final int SND_TIMEO; static final int RCV_TIMEO; }### Answer: @Test(timeout=180000) public void testInvalidOperations() throws IOException { try { DomainSocket.connect( new File(sockDir.getDir(), "test_sock_invalid_operation"). getAbsolutePath()); } catch (IOException e) { GenericTestUtils.assertExceptionContains("connect(2) error: ", e); } }
### Question: ScriptBasedMapping extends CachedDNSToSwitchMapping { @Override public void setConf(Configuration conf) { super.setConf(conf); getRawMapping().setConf(conf); } ScriptBasedMapping(); ScriptBasedMapping(Configuration conf); @Override Configuration getConf(); @Override String toString(); @Override void setConf(Configuration conf); static final String NO_SCRIPT; }### Answer: @Test public void testFilenameMeansMultiSwitch() throws Throwable { Configuration conf = new Configuration(); conf.set(ScriptBasedMapping.SCRIPT_FILENAME_KEY, "any-filename"); ScriptBasedMapping mapping = createMapping(conf); assertFalse("Expected to be multi switch", mapping.isSingleSwitch()); mapping.setConf(new Configuration()); assertTrue("Expected to be single switch", mapping.isSingleSwitch()); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { @Override public int hashCode() { int result = address == null? 0: address.hashCode(); result ^= toString().hashCode(); return result; } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testHashCode() { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerAddress hsa2 = new HServerAddress("localhost", 1234); assertEquals(hsa1.hashCode(), hsa2.hashCode()); HServerAddress hsa3 = new HServerAddress("localhost", 1235); assertNotSame(hsa1.hashCode(), hsa3.hashCode()); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { public HServerAddress() { super(); } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testHServerAddress() { new HServerAddress(); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { @Override public String toString() { return this.cachedToString; } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testHServerAddressInetSocketAddress() { HServerAddress hsa1 = new HServerAddress(new InetSocketAddress("localhost", 1234)); System.out.println(hsa1.toString()); }
### Question: FileInputStreamCache { public synchronized void close() { if (closed) return; closed = true; IOUtils.cleanup(LOG, cacheCleaner); for (Iterator<Entry<Key, Value>> iter = map.entries().iterator(); iter.hasNext();) { Entry<Key, Value> entry = iter.next(); entry.getValue().close(); iter.remove(); } } FileInputStreamCache(int maxCacheSize, long expiryTimeMs); void put(DatanodeID datanodeID, ExtendedBlock block, FileInputStream fis[]); synchronized FileInputStream[] get(DatanodeID datanodeID, ExtendedBlock block); synchronized void close(); synchronized String toString(); long getExpiryTimeMs(); int getMaxCacheSize(); }### Answer: @Test public void testCreateAndDestroy() throws Exception { FileInputStreamCache cache = new FileInputStreamCache(10, 1000); cache.close(); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; return compareTo((HServerAddress)o) == 0; } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testHServerAddressString() { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerAddress hsa2 = new HServerAddress(new InetSocketAddress("localhost", 1234)); assertTrue(hsa1.equals(hsa2)); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { public void readFields(DataInput in) throws IOException { String hostname = in.readUTF(); int port = in.readInt(); if (hostname != null && hostname.length() > 0) { this.address = getResolvedAddress(new InetSocketAddress(hostname, port)); checkBindAddressCanBeResolved(); createCachedToString(); } } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testReadFields() throws IOException { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerAddress hsa2 = new HServerAddress("localhost", 1235); byte [] bytes = Writables.getBytes(hsa1); HServerAddress deserialized = (HServerAddress)Writables.getWritable(bytes, new HServerAddress()); assertEquals(hsa1, deserialized); bytes = Writables.getBytes(hsa2); deserialized = (HServerAddress)Writables.getWritable(bytes, new HServerAddress()); assertNotSame(hsa1, deserialized); }
### Question: LayoutVersion { public static boolean supports(final Feature f, final int lv) { final EnumSet<Feature> set = map.get(lv); return set != null && set.contains(f); } static String getString(); static boolean supports(final Feature f, final int lv); static int getCurrentLayoutVersion(); static final int BUGFIX_HDFS_2991_VERSION; }### Answer: @Test public void testRelease203() { assertTrue(LayoutVersion.supports(Feature.DELEGATION_TOKEN, Feature.RESERVED_REL20_203.lv)); } @Test public void testRelease204() { assertTrue(LayoutVersion.supports(Feature.DELEGATION_TOKEN, Feature.RESERVED_REL20_204.lv)); }
### Question: MD5FileUtils { public static MD5Hash computeMd5ForFile(File dataFile) throws IOException { InputStream in = new FileInputStream(dataFile); try { MessageDigest digester = MD5Hash.getDigester(); DigestInputStream dis = new DigestInputStream(in, digester); IOUtils.copyBytes(dis, new IOUtils.NullOutputStream(), 128*1024); return new MD5Hash(digester.digest()); } finally { IOUtils.closeStream(in); } } static void verifySavedMD5(File dataFile, MD5Hash expectedMD5); static MD5Hash readStoredMd5ForFile(File dataFile); static MD5Hash computeMd5ForFile(File dataFile); static void saveMD5File(File dataFile, MD5Hash digest); static File getDigestFileForFile(File file); static final String MD5_SUFFIX; }### Answer: @Test public void testComputeMd5ForFile() throws Exception { MD5Hash computedDigest = MD5FileUtils.computeMd5ForFile(TEST_FILE); assertEquals(TEST_MD5, computedDigest); }
### Question: MD5FileUtils { public static void verifySavedMD5(File dataFile, MD5Hash expectedMD5) throws IOException { MD5Hash storedHash = readStoredMd5ForFile(dataFile); if (!expectedMD5.equals(storedHash)) { throw new IOException( "File " + dataFile + " did not match stored MD5 checksum " + " (stored: " + storedHash + ", computed: " + expectedMD5); } } static void verifySavedMD5(File dataFile, MD5Hash expectedMD5); static MD5Hash readStoredMd5ForFile(File dataFile); static MD5Hash computeMd5ForFile(File dataFile); static void saveMD5File(File dataFile, MD5Hash digest); static File getDigestFileForFile(File file); static final String MD5_SUFFIX; }### Answer: @Test(expected=IOException.class) public void testVerifyMD5FileMissing() throws Exception { MD5FileUtils.verifySavedMD5(TEST_FILE, TEST_MD5); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { public T pollFirst() { if (head == null) { return null; } T first = head.element; this.remove(first); return first; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testPollOneElement() { LOG.info("Test poll one element"); set.add(list.get(0)); assertEquals(list.get(0), set.pollFirst()); assertNull(set.pollFirst()); LOG.info("Test poll one element - DONE"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { @Override public List<T> pollAll() { List<T> retList = new ArrayList<T>(size); while (head != null) { retList.add(head.element); head = head.after; } this.clear(); return retList; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testPollAll() { LOG.info("Test poll all"); for (Integer i : list) { assertTrue(set.add(i)); } while (set.pollFirst() != null); assertEquals(0, set.size()); assertTrue(set.isEmpty()); for (int i = 0; i < NUM; i++) { assertFalse(set.contains(list.get(i))); } Iterator<Integer> iter = set.iterator(); assertFalse(iter.hasNext()); LOG.info("Test poll all - DONE"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { @Override public List<T> pollN(int n) { if (n >= size) { return pollAll(); } List<T> retList = new ArrayList<T>(n); while (n-- > 0 && head != null) { T curr = head.element; this.removeElem(curr); retList.add(curr); } shrinkIfNecessary(); return retList; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testPollNOne() { LOG.info("Test pollN one"); set.add(list.get(0)); List<Integer> l = set.pollN(10); assertEquals(1, l.size()); assertEquals(list.get(0), l.get(0)); LOG.info("Test pollN one - DONE"); } @Test public void testPollNMulti() { LOG.info("Test pollN multi"); set.addAll(list); List<Integer> l = set.pollN(10); assertEquals(10, l.size()); for (int i = 0; i < 10; i++) { assertEquals(list.get(i), l.get(i)); } l = set.pollN(1000); assertEquals(NUM - 10, l.size()); for (int i = 10; i < NUM; i++) { assertEquals(list.get(i), l.get(i - 10)); } assertTrue(set.isEmpty()); assertEquals(0, set.size()); LOG.info("Test pollN multi - DONE"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { @Override public void clear() { super.clear(); this.head = null; this.tail = null; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testClear() { LOG.info("Test clear"); set.addAll(list); assertEquals(NUM, set.size()); assertFalse(set.isEmpty()); set.clear(); assertEquals(0, set.size()); assertTrue(set.isEmpty()); assertEquals(0, set.pollAll().size()); assertEquals(0, set.pollN(10).size()); assertNull(set.pollFirst()); Iterator<Integer> iter = set.iterator(); assertFalse(iter.hasNext()); LOG.info("Test clear - DONE"); }
### Question: ServerName implements Comparable<ServerName> { public static long getServerStartcodeFromServerName(final String serverName) { int index = serverName.lastIndexOf(SERVERNAME_SEPARATOR); return Long.parseLong(serverName.substring(index + 1)); } ServerName(final String hostname, final int port, final long startcode); ServerName(final String serverName); ServerName(final String hostAndPort, final long startCode); static String parseHostname(final String serverName); static int parsePort(final String serverName); static long parseStartcode(final String serverName); @Override String toString(); synchronized byte [] getVersionedBytes(); String getServerName(); String getHostname(); int getPort(); long getStartcode(); static String getServerName(String hostName, int port, long startcode); static String getServerName(final String hostAndPort, final long startcode); String getHostAndPort(); static long getServerStartcodeFromServerName(final String serverName); static String getServerNameLessStartCode(String inServerName); @Override int compareTo(ServerName other); @Override int hashCode(); @Override boolean equals(Object o); static ServerName findServerWithSameHostnamePort(final Collection<ServerName> names, final ServerName serverName); static boolean isSameHostnameAndPort(final ServerName left, final ServerName right); static ServerName parseVersionedServerName(final byte [] versionedBytes); static ServerName parseServerName(final String str); static final int NON_STARTCODE; static final String SERVERNAME_SEPARATOR; static Pattern SERVERNAME_PATTERN; static final String UNKNOWN_SERVERNAME; }### Answer: @Test public void getServerStartcodeFromServerName() { ServerName sn = new ServerName("www.example.org", 1234, 5678); assertEquals(5678, ServerName.getServerStartcodeFromServerName(sn.toString())); assertNotSame(5677, ServerName.getServerStartcodeFromServerName(sn.toString())); }
### Question: HDFSBlocksDistribution { public void addHostsAndBlockWeight(String[] hosts, long weight) { if (hosts == null || hosts.length == 0) { return; } addUniqueWeight(weight); for (String hostname : hosts) { addHostAndBlockWeight(hostname, weight); } } HDFSBlocksDistribution(); @Override synchronized String toString(); void addHostsAndBlockWeight(String[] hosts, long weight); Map<String,HostAndWeight> getHostAndWeights(); long getWeight(String host); long getUniqueBlocksTotalWeight(); float getBlockLocalityIndex(String host); void add(HDFSBlocksDistribution otherBlocksDistribution); List<String> getTopHosts(); }### Answer: @Test public void testAddHostsAndBlockWeight() throws Exception { HDFSBlocksDistribution distribution = new HDFSBlocksDistribution(); distribution.addHostsAndBlockWeight(null, 100); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[0], 100); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[] {"test"}, 101); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[] {"test"}, 202); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); assertEquals("test host should have weight 303", 303, distribution.getHostAndWeights().get("test").getWeight()); distribution.addHostsAndBlockWeight(new String[] {"testTwo"}, 222); assertEquals("Should be two hosts", 2, distribution.getHostAndWeights().size()); assertEquals("Total weight should be 525", 525, distribution.getUniqueBlocksTotalWeight()); }