method2testcases
stringlengths
118
3.08k
### Question: HDFSBlocksDistribution { public void add(HDFSBlocksDistribution otherBlocksDistribution) { Map<String,HostAndWeight> otherHostAndWeights = otherBlocksDistribution.getHostAndWeights(); for (Map.Entry<String, HostAndWeight> otherHostAndWeight: otherHostAndWeights.entrySet()) { addHostAndBlockWeight(otherHostAndWeight.getValue().host, otherHostAndWeight.getValue().weight); } addUniqueWeight(otherBlocksDistribution.getUniqueBlocksTotalWeight()); } 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 testAdd() throws Exception { HDFSBlocksDistribution distribution = new HDFSBlocksDistribution(); distribution.add(new MockHDFSBlocksDistribution()); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[]{"test"}, 10); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); distribution.add(new MockHDFSBlocksDistribution()); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); assertEquals("Total weight should be 10", 10, distribution.getUniqueBlocksTotalWeight()); }
### Question: QuorumJournalManager implements JournalManager { @Override public void format(NamespaceInfo nsInfo) throws IOException { QuorumCall<AsyncLogger,Void> call = loggers.format(nsInfo); try { call.waitFor(loggers.size(), loggers.size(), 0, FORMAT_TIMEOUT_MS, "format"); } catch (InterruptedException e) { throw new IOException("Interrupted waiting for format() response"); } catch (TimeoutException e) { throw new IOException("Timed out waiting for format() response"); } if (call.countExceptions() > 0) { call.rethrowException("Could not format one or more JournalNodes"); } } QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo); QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo, AsyncLogger.Factory loggerFactory); static void checkJournalId(String jid); @Override void format(NamespaceInfo nsInfo); @Override boolean hasSomeData(); @Override EditLogOutputStream startLogSegment(long txId); @Override void finalizeLogSegment(long firstTxId, long lastTxId); @Override void setOutputBufferCapacity(int size); @Override void purgeLogsOlderThan(long minTxIdToKeep); @Override void recoverUnfinalizedSegments(); @Override void close(); @Override void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk); @Override String toString(); }### Answer: @Test public void testFormat() throws Exception { QuorumJournalManager qjm = closeLater(new QuorumJournalManager( conf, cluster.getQuorumJournalURI("testFormat-jid"), FAKE_NSINFO)); assertFalse(qjm.hasSomeData()); qjm.format(FAKE_NSINFO); assertTrue(qjm.hasSomeData()); }
### Question: QuorumJournalManager implements JournalManager { @Override public String toString() { return "QJM to " + loggers; } QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo); QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo, AsyncLogger.Factory loggerFactory); static void checkJournalId(String jid); @Override void format(NamespaceInfo nsInfo); @Override boolean hasSomeData(); @Override EditLogOutputStream startLogSegment(long txId); @Override void finalizeLogSegment(long firstTxId, long lastTxId); @Override void setOutputBufferCapacity(int size); @Override void purgeLogsOlderThan(long minTxIdToKeep); @Override void recoverUnfinalizedSegments(); @Override void close(); @Override void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk); @Override String toString(); }### Answer: @Test public void testToString() throws Exception { GenericTestUtils.assertMatches( qjm.toString(), "QJM to \\[127.0.0.1:\\d+, 127.0.0.1:\\d+, 127.0.0.1:\\d+\\]"); }
### Question: Journal implements Closeable { synchronized NewEpochResponseProto newEpoch( NamespaceInfo nsInfo, long epoch) throws IOException { checkFormatted(); storage.checkConsistentNamespace(nsInfo); if (epoch <= getLastPromisedEpoch()) { throw new IOException("Proposed epoch " + epoch + " <= last promise " + getLastPromisedEpoch()); } updateLastPromisedEpoch(epoch); abortCurSegment(); NewEpochResponseProto.Builder builder = NewEpochResponseProto.newBuilder(); EditLogFile latestFile = scanStorageForLatestEdits(); if (latestFile != null) { builder.setLastSegmentTxId(latestFile.getFirstTxId()); } return builder.build(); } Journal(File logDir, String journalId, StorageErrorReporter errorReporter); @Override // Closeable void close(); synchronized long getLastWriterEpoch(); void heartbeat(RequestInfo reqInfo); synchronized boolean isFormatted(); synchronized void startLogSegment(RequestInfo reqInfo, long txid); synchronized void finalizeLogSegment(RequestInfo reqInfo, long startTxId, long endTxId); synchronized void purgeLogsOlderThan(RequestInfo reqInfo, long minTxIdToKeep); RemoteEditLogManifest getEditLogManifest(long sinceTxId); synchronized PrepareRecoveryResponseProto prepareRecovery( RequestInfo reqInfo, long segmentTxId); synchronized void acceptRecovery(RequestInfo reqInfo, SegmentStateProto segment, URL fromUrl); }### Answer: @Test public void testNamespaceVerification() throws Exception { journal.newEpoch(FAKE_NSINFO, 1); try { journal.newEpoch(FAKE_NSINFO_2, 2); fail("Did not fail newEpoch() when namespaces mismatched"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains( "Incompatible namespaceID", ioe); } }
### Question: NamenodeJspHelper { static String getDelegationToken(final NamenodeProtocols nn, HttpServletRequest request, Configuration conf, final UserGroupInformation ugi) throws IOException, InterruptedException { Token<DelegationTokenIdentifier> token = ugi .doAs(new PrivilegedExceptionAction<Token<DelegationTokenIdentifier>>() { @Override public Token<DelegationTokenIdentifier> run() throws IOException { return nn.getDelegationToken(new Text(ugi.getUserName())); } }); return token == null ? null : token.encodeToUrlString(); } }### Answer: @Test public void testDelegationToken() throws IOException, InterruptedException { NamenodeProtocols nn = cluster.getNameNodeRpc(); HttpServletRequest request = mock(HttpServletRequest.class); UserGroupInformation ugi = UserGroupInformation.createRemoteUser("auser"); String tokenString = NamenodeJspHelper.getDelegationToken(nn, request, conf, ugi); Assert.assertEquals(null, tokenString); }
### Question: NamenodeJspHelper { static String getSecurityModeText() { if(UserGroupInformation.isSecurityEnabled()) { return "<div class=\"security\">Security is <em>ON</em></div>"; } else { return "<div class=\"security\">Security is <em>OFF</em></div>"; } } }### Answer: @Test public void tesSecurityModeText() { conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); String securityOnOff = NamenodeJspHelper.getSecurityModeText(); Assert.assertTrue("security mode doesn't match. Should be ON", securityOnOff.contains("ON")); conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "simple"); UserGroupInformation.setConfiguration(conf); securityOnOff = NamenodeJspHelper.getSecurityModeText(); Assert.assertTrue("security mode doesn't match. Should be OFF", securityOnOff.contains("OFF")); } @Test public void testSecurityModeText() { conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); String securityOnOff = NamenodeJspHelper.getSecurityModeText(); Assert.assertTrue("security mode doesn't match. Should be ON", securityOnOff.contains("ON")); conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "simple"); UserGroupInformation.setConfiguration(conf); securityOnOff = NamenodeJspHelper.getSecurityModeText(); Assert.assertTrue("security mode doesn't match. Should be OFF", securityOnOff.contains("OFF")); }
### Question: INodeFile extends INode implements BlockCollection { @Override public short getBlockReplication() { return (short) ((header & HEADERMASK) >> BLOCKBITS); } INodeFile(PermissionStatus permissions, BlockInfo[] blklist, short replication, long modificationTime, long atime, long preferredBlockSize); static INodeFile valueOf(INode inode, String path); @Override short getBlockReplication(); @Override long getPreferredBlockSize(); @Override BlockInfo[] getBlocks(); void setBlock(int idx, BlockInfo blk); @Override String getName(); @Override BlockInfo getLastBlock(); @Override int numBlocks(); }### Answer: @Test public void testReplication () { replication = 3; preferredBlockSize = 128*1024*1024; INodeFile inf = new INodeFile(new PermissionStatus(userName, null, FsPermission.getDefault()), null, replication, 0L, 0L, preferredBlockSize); assertEquals("True has to be returned in this case", replication, inf.getBlockReplication()); }
### Question: INodeFile extends INode implements BlockCollection { @Override public long getPreferredBlockSize() { return header & ~HEADERMASK; } INodeFile(PermissionStatus permissions, BlockInfo[] blklist, short replication, long modificationTime, long atime, long preferredBlockSize); static INodeFile valueOf(INode inode, String path); @Override short getBlockReplication(); @Override long getPreferredBlockSize(); @Override BlockInfo[] getBlocks(); void setBlock(int idx, BlockInfo blk); @Override String getName(); @Override BlockInfo getLastBlock(); @Override int numBlocks(); }### Answer: @Test public void testPreferredBlockSize () { replication = 3; preferredBlockSize = 128*1024*1024; INodeFile inf = new INodeFile(new PermissionStatus(userName, null, FsPermission.getDefault()), null, replication, 0L, 0L, preferredBlockSize); assertEquals("True has to be returned in this case", preferredBlockSize, inf.getPreferredBlockSize()); } @Test public void testPreferredBlockSizeUpperBound () { replication = 3; preferredBlockSize = BLKSIZE_MAXVALUE; INodeFile inf = new INodeFile(new PermissionStatus(userName, null, FsPermission.getDefault()), null, replication, 0L, 0L, preferredBlockSize); assertEquals("True has to be returned in this case", BLKSIZE_MAXVALUE, inf.getPreferredBlockSize()); }
### Question: INodeFile extends INode implements BlockCollection { void appendBlocks(INodeFile [] inodes, int totalAddedBlocks) { int size = this.blocks.length; BlockInfo[] newlist = new BlockInfo[size + totalAddedBlocks]; System.arraycopy(this.blocks, 0, newlist, 0, size); for(INodeFile in: inodes) { System.arraycopy(in.blocks, 0, newlist, size, in.blocks.length); size += in.blocks.length; } for(BlockInfo bi: newlist) { bi.setBlockCollection(this); } this.blocks = newlist; } INodeFile(PermissionStatus permissions, BlockInfo[] blklist, short replication, long modificationTime, long atime, long preferredBlockSize); static INodeFile valueOf(INode inode, String path); @Override short getBlockReplication(); @Override long getPreferredBlockSize(); @Override BlockInfo[] getBlocks(); void setBlock(int idx, BlockInfo blk); @Override String getName(); @Override BlockInfo getLastBlock(); @Override int numBlocks(); }### Answer: @Test public void testAppendBlocks() { INodeFile origFile = createINodeFiles(1, "origfile")[0]; assertEquals("Number of blocks didn't match", origFile.numBlocks(), 1L); INodeFile[] appendFiles = createINodeFiles(4, "appendfile"); origFile.appendBlocks(appendFiles, getTotalBlocks(appendFiles)); assertEquals("Number of blocks didn't match", origFile.numBlocks(), 5L); }
### Question: EditLogFileOutputStream extends EditLogOutputStream { @Override public void close() throws IOException { if (fp == null) { throw new IOException("Trying to use aborted output stream"); } try { if (doubleBuf != null) { doubleBuf.close(); doubleBuf = null; } if (fc != null && fc.isOpen()) { fc.truncate(fc.position()); fc.close(); fc = null; } if (fp != null) { fp.close(); fp = null; } } finally { IOUtils.cleanup(FSNamesystem.LOG, fc, fp); doubleBuf = null; fc = null; fp = null; } fp = null; } EditLogFileOutputStream(File name, int size); @Override void write(FSEditLogOp op); @Override void writeRaw(byte[] bytes, int offset, int length); @Override void create(); @VisibleForTesting static void writeHeader(DataOutputStream out); @Override void close(); @Override void abort(); @Override void setReadyToFlush(); @Override void flushAndSync(boolean durable); @Override boolean shouldForceSync(); @Override String toString(); boolean isOpen(); @VisibleForTesting void setFileChannelForTesting(FileChannel fc); @VisibleForTesting FileChannel getFileChannelForTesting(); @VisibleForTesting static void setShouldSkipFsyncForTesting(boolean skip); static final int MIN_PREALLOCATION_LENGTH; }### Answer: @Test public void testEditLogFileOutputStreamCloseClose() throws IOException { EditLogFileOutputStream editLogStream = new EditLogFileOutputStream(TEST_EDITS, 0); editLogStream.close(); try { editLogStream.close(); } catch (IOException ioe) { String msg = StringUtils.stringifyException(ioe); assertTrue(msg, msg.contains("Trying to use aborted output stream")); } }
### Question: EditLogFileOutputStream extends EditLogOutputStream { @Override public void abort() throws IOException { if (fp == null) { return; } IOUtils.cleanup(LOG, fp); fp = null; } EditLogFileOutputStream(File name, int size); @Override void write(FSEditLogOp op); @Override void writeRaw(byte[] bytes, int offset, int length); @Override void create(); @VisibleForTesting static void writeHeader(DataOutputStream out); @Override void close(); @Override void abort(); @Override void setReadyToFlush(); @Override void flushAndSync(boolean durable); @Override boolean shouldForceSync(); @Override String toString(); boolean isOpen(); @VisibleForTesting void setFileChannelForTesting(FileChannel fc); @VisibleForTesting FileChannel getFileChannelForTesting(); @VisibleForTesting static void setShouldSkipFsyncForTesting(boolean skip); static final int MIN_PREALLOCATION_LENGTH; }### Answer: @Test public void testEditLogFileOutputStreamAbortAbort() throws IOException { EditLogFileOutputStream editLogStream = new EditLogFileOutputStream(TEST_EDITS, 0); editLogStream.abort(); editLogStream.abort(); }
### Question: FSEditLogLoader { static EditLogValidation validateEditLog(EditLogInputStream in) { long lastPos = 0; long lastTxId = HdfsConstants.INVALID_TXID; long numValid = 0; FSEditLogOp op = null; while (true) { lastPos = in.getPosition(); try { if ((op = in.readOp()) == null) { break; } } catch (Throwable t) { FSImage.LOG.warn("Caught exception after reading " + numValid + " ops from " + in + " while determining its valid length." + "Position was " + lastPos, t); in.resync(); FSImage.LOG.warn("After resync, position is " + in.getPosition()); continue; } if (lastTxId == HdfsConstants.INVALID_TXID || op.getTransactionId() > lastTxId) { lastTxId = op.getTransactionId(); } numValid++; } return new EditLogValidation(lastPos, lastTxId, false); } FSEditLogLoader(FSNamesystem fsNamesys, long lastAppliedTxId); long getLastAppliedTxId(); }### Answer: @Test public void testValidateEmptyEditLog() throws IOException { File testDir = new File(TEST_DIR, "testValidateEmptyEditLog"); SortedMap<Long, Long> offsetToTxId = Maps.newTreeMap(); File logFile = prepareUnfinalizedTestEditLog(testDir, 0, offsetToTxId); truncateFile(logFile, 4); EditLogValidation validation = EditLogFileInputStream.validateEditLog(logFile); assertTrue(!validation.hasCorruptHeader()); assertEquals(HdfsConstants.INVALID_TXID, validation.getEndTxId()); }
### Question: StreamFile extends DfsServlet { static void copyFromOffset(FSInputStream in, OutputStream out, long offset, long count) throws IOException { in.seek(offset); IOUtils.copyBytes(in, out, count, false); } @Override @SuppressWarnings("unchecked") void doGet(HttpServletRequest request, HttpServletResponse response); static final String CONTENT_LENGTH; }### Answer: @Test public void testWriteTo() throws IOException { FSInputStream fsin = new MockFSInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); int[] pairs = new int[]{ 0, 10000, 50, 100, 50, 6000, 1000, 2000, 0, 1, 0, 0, 5000, 0, }; assertTrue("Pairs array must be even", pairs.length % 2 == 0); for (int i = 0; i < pairs.length; i+=2) { StreamFile.copyFromOffset(fsin, os, pairs[i], pairs[i+1]); assertArrayEquals("Reading " + pairs[i+1] + " bytes from offset " + pairs[i], getOutputArray(pairs[i], pairs[i+1]), os.toByteArray()); os.reset(); } }
### Question: FileJournalManager implements JournalManager { public static List<EditLogFile> matchEditLogs(File logDir) throws IOException { return matchEditLogs(FileUtil.listFiles(logDir)); } FileJournalManager(StorageDirectory sd, StorageErrorReporter errorReporter); @Override void close(); @Override void format(NamespaceInfo ns); @Override boolean hasSomeData(); @Override synchronized EditLogOutputStream startLogSegment(long txid); @Override synchronized void finalizeLogSegment(long firstTxId, long lastTxId); @VisibleForTesting StorageDirectory getStorageDirectory(); @Override synchronized void setOutputBufferCapacity(int size); @Override void purgeLogsOlderThan(long minTxIdToKeep); List<RemoteEditLog> getRemoteEditLogs(long firstTxId); static List<EditLogFile> matchEditLogs(File logDir); @Override synchronized void selectInputStreams( Collection<EditLogInputStream> streams, long fromTxId, boolean inProgressOk); @Override synchronized void recoverUnfinalizedSegments(); List<EditLogFile> getLogFiles(long fromTxId); EditLogFile getLogFile(long startTxId); static EditLogFile getLogFile(File dir, long startTxId); @Override String toString(); }### Answer: @Test(expected = IOException.class) public void testMatchEditLogInvalidDirThrowsIOException() throws IOException { File badDir = new File("does not exist"); FileJournalManager.matchEditLogs(badDir); }
### Question: DirectoryScanner implements Runnable { DirectoryScanner(DataNode dn, FsDatasetSpi<?> dataset, Configuration conf) { this.datanode = dn; this.dataset = dataset; int interval = conf.getInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_DEFAULT); scanPeriodMsecs = interval * 1000L; int threads = conf.getInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_THREADS_KEY, DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_THREADS_DEFAULT); reportCompileThreadPool = Executors.newFixedThreadPool(threads, new Daemon.DaemonFactory()); masterThread = new ScheduledThreadPoolExecutor(1, new Daemon.DaemonFactory()); } DirectoryScanner(DataNode dn, FsDatasetSpi<?> dataset, Configuration conf); @Override void run(); }### Answer: @Test public void testDirectoryScanner() throws Exception { for (int parallelism = 1; parallelism < 3; parallelism++) { runTest(parallelism); } }
### Question: BlockPoolManager { void refreshNamenodes(Configuration conf) throws IOException { LOG.info("Refresh request received for nameservices: " + conf.get(DFSConfigKeys.DFS_NAMESERVICES)); Map<String, Map<String, InetSocketAddress>> newAddressMap = DFSUtil.getNNServiceRpcAddresses(conf); synchronized (refreshNamenodesLock) { doRefreshNamenodes(newAddressMap); } } BlockPoolManager(DataNode dn); }### Answer: @Test public void testFederationRefresh() throws Exception { Configuration conf = new Configuration(); conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1,ns2"); addNN(conf, "ns1", "mock1:8020"); addNN(conf, "ns2", "mock1:8020"); bpm.refreshNamenodes(conf); assertEquals( "create #1\n" + "create #2\n", log.toString()); log.setLength(0); conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1"); bpm.refreshNamenodes(conf); assertEquals( "stop #1\n" + "refresh #2\n", log.toString()); log.setLength(0); conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1,ns2"); bpm.refreshNamenodes(conf); assertEquals( "create #3\n" + "refresh #2\n", log.toString()); }
### Question: ColumnCountGetFilter extends FilterBase { public ColumnCountGetFilter() { super(); } ColumnCountGetFilter(); ColumnCountGetFilter(final int n); int getLimit(); @Override boolean filterAllRemaining(); @Override ReturnCode filterKeyValue(KeyValue v); @Override void reset(); static Filter createFilterFromArguments(ArrayList<byte []> filterArguments); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override String toString(); }### Answer: @Test public void testColumnCountGetFilter() throws IOException { String family = "Family"; HTableDescriptor htd = new HTableDescriptor("testColumnCountGetFilter"); htd.addFamily(new HColumnDescriptor(family)); HRegionInfo info = new HRegionInfo(htd.getName(), null, null, false); HRegion region = HRegion.createHRegion(info, TEST_UTIL. getDataTestDir(), TEST_UTIL.getConfiguration(), htd); try { String valueString = "ValueString"; String row = "row-1"; List<String> columns = generateRandomWords(10000, "column"); Put p = new Put(Bytes.toBytes(row)); p.setWriteToWAL(false); for (String column : columns) { KeyValue kv = KeyValueTestUtil.create(row, family, column, 0, valueString); p.add(kv); } region.put(p); Get get = new Get(row.getBytes()); Filter filter = new ColumnCountGetFilter(100); get.setFilter(filter); Scan scan = new Scan(get); InternalScanner scanner = region.getScanner(scan); List<KeyValue> results = new ArrayList<KeyValue>(); scanner.next(results); assertEquals(100, results.size()); } finally { region.close(); region.getLog().closeAndDelete(); } region.close(); region.getLog().closeAndDelete(); }
### Question: AuthFilter extends AuthenticationFilter { @Override protected Properties getConfiguration(String prefix, FilterConfig config) throws ServletException { final Properties p = super.getConfiguration(CONF_PREFIX, config); p.setProperty(AUTH_TYPE, UserGroupInformation.isSecurityEnabled()? KerberosAuthenticationHandler.TYPE: PseudoAuthenticationHandler.TYPE); p.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "true"); p.setProperty(COOKIE_PATH, "/"); return p; } @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain); }### Answer: @Test public void testGetConfiguration() throws ServletException { AuthFilter filter = new AuthFilter(); Map<String, String> m = new HashMap<String,String>(); m.put(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, "xyz/thehost@REALM"); m.put(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY, "thekeytab"); FilterConfig config = new DummyFilterConfig(m); Properties p = filter.getConfiguration("random", config); Assert.assertEquals("xyz/thehost@REALM", p.getProperty("kerberos.principal")); Assert.assertEquals("thekeytab", p.getProperty("kerberos.keytab")); Assert.assertEquals("true", p.getProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED)); }
### Question: RunnableCallable implements Callable<Void>, Runnable { @Override public void run() { if (runnable != null) { runnable.run(); } else { try { callable.call(); } catch (Exception ex) { throw new RuntimeException(ex); } } } RunnableCallable(Runnable runnable); RunnableCallable(Callable<?> callable); @Override Void call(); @Override void run(); String toString(); }### Answer: @Test(expected = RuntimeException.class) public void callableExRun() throws Exception { CEx c = new CEx(); RunnableCallable rc = new RunnableCallable(c); rc.run(); }
### Question: User { public abstract <T> T runAs(PrivilegedAction<T> action); UserGroupInformation getUGI(); String getName(); String[] getGroupNames(); abstract String getShortName(); abstract T runAs(PrivilegedAction<T> action); abstract T runAs(PrivilegedExceptionAction<T> action); abstract void obtainAuthTokenForJob(Configuration conf, Job job); abstract void obtainAuthTokenForJob(JobConf job); String toString(); static User getCurrent(); static User create(UserGroupInformation ugi); static User createUserForTesting(Configuration conf, String name, String[] groups); static void login(Configuration conf, String fileConfKey, String principalConfKey, String localhost); static boolean isSecurityEnabled(); static boolean isHBaseSecurityEnabled(Configuration conf); static final String HBASE_SECURITY_CONF_KEY; }### Answer: @Test public void testRunAs() throws Exception { Configuration conf = HBaseConfiguration.create(); final User user = User.createUserForTesting(conf, "testuser", new String[]{"foo"}); final PrivilegedExceptionAction<String> action = new PrivilegedExceptionAction<String>(){ public String run() throws IOException { User u = User.getCurrent(); return u.getName(); } }; String username = user.runAs(action); assertEquals("Current user within runAs() should match", "testuser", username); User user2 = User.createUserForTesting(conf, "testuser2", new String[]{"foo"}); String username2 = user2.runAs(action); assertEquals("Second username should match second user", "testuser2", username2); username = user.runAs(new PrivilegedExceptionAction<String>(){ public String run() throws Exception { return User.getCurrent().getName(); } }); assertEquals("User name in runAs() should match", "testuser", username); user2.runAs(new PrivilegedExceptionAction(){ public Object run() throws IOException, InterruptedException{ String nestedName = user.runAs(action); assertEquals("Nest name should match nested user", "testuser", nestedName); assertEquals("Current name should match current user", "testuser2", User.getCurrent().getName()); return null; } }); }
### Question: User { public static User getCurrent() throws IOException { User user; if (IS_SECURE_HADOOP) { user = new SecureHadoopUser(); } else { user = new HadoopUser(); } if (user.getUGI() == null) { return null; } return user; } UserGroupInformation getUGI(); String getName(); String[] getGroupNames(); abstract String getShortName(); abstract T runAs(PrivilegedAction<T> action); abstract T runAs(PrivilegedExceptionAction<T> action); abstract void obtainAuthTokenForJob(Configuration conf, Job job); abstract void obtainAuthTokenForJob(JobConf job); String toString(); static User getCurrent(); static User create(UserGroupInformation ugi); static User createUserForTesting(Configuration conf, String name, String[] groups); static void login(Configuration conf, String fileConfKey, String principalConfKey, String localhost); static boolean isSecurityEnabled(); static boolean isHBaseSecurityEnabled(Configuration conf); static final String HBASE_SECURITY_CONF_KEY; }### Answer: @Test public void testGetCurrent() throws Exception { User user1 = User.getCurrent(); assertNotNull(user1.ugi); LOG.debug("User1 is "+user1.getName()); for (int i =0 ; i< 100; i++) { User u = User.getCurrent(); assertNotNull(u); assertEquals(user1.getName(), u.getName()); } }
### Question: ServerWebApp extends Server implements ServletContextListener { static String getHomeDir(String name) { String homeDir = HOME_DIR_TL.get(); if (homeDir == null) { String sysProp = name + HOME_DIR; homeDir = System.getProperty(sysProp); if (homeDir == null) { throw new IllegalArgumentException(MessageFormat.format("System property [{0}] not defined", sysProp)); } } return homeDir; } protected ServerWebApp(String name, String homeDir, String configDir, String logDir, String tempDir, Configuration config); protected ServerWebApp(String name, String homeDir, Configuration config); ServerWebApp(String name); static void setHomeDirForCurrentThread(String homeDir); void contextInitialized(ServletContextEvent event); void contextDestroyed(ServletContextEvent event); InetSocketAddress getAuthority(); @VisibleForTesting void setAuthority(InetSocketAddress authority); }### Answer: @Test(expected = IllegalArgumentException.class) public void getHomeDirNotDef() { ServerWebApp.getHomeDir("TestServerWebApp00"); } @Test public void getHomeDir() { System.setProperty("TestServerWebApp0.home.dir", "/tmp"); assertEquals(ServerWebApp.getHomeDir("TestServerWebApp0"), "/tmp"); assertEquals(ServerWebApp.getDir("TestServerWebApp0", ".log.dir", "/tmp/log"), "/tmp/log"); System.setProperty("TestServerWebApp0.log.dir", "/tmplog"); assertEquals(ServerWebApp.getDir("TestServerWebApp0", ".log.dir", "/tmp/log"), "/tmplog"); }
### Question: ServerWebApp extends Server implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { try { init(); } catch (ServerException ex) { event.getServletContext().log("ERROR: " + ex.getMessage()); throw new RuntimeException(ex); } } protected ServerWebApp(String name, String homeDir, String configDir, String logDir, String tempDir, Configuration config); protected ServerWebApp(String name, String homeDir, Configuration config); ServerWebApp(String name); static void setHomeDirForCurrentThread(String homeDir); void contextInitialized(ServletContextEvent event); void contextDestroyed(ServletContextEvent event); InetSocketAddress getAuthority(); @VisibleForTesting void setAuthority(InetSocketAddress authority); }### Answer: @Test(expected = RuntimeException.class) @TestDir public void failedInit() throws Exception { String dir = TestDirHelper.getTestDir().getAbsolutePath(); System.setProperty("TestServerWebApp2.home.dir", dir); System.setProperty("TestServerWebApp2.config.dir", dir); System.setProperty("TestServerWebApp2.log.dir", dir); System.setProperty("TestServerWebApp2.temp.dir", dir); System.setProperty("testserverwebapp2.services", "FOO"); ServerWebApp server = new ServerWebApp("TestServerWebApp2") { }; server.contextInitialized(null); }
### Question: ServerWebApp extends Server implements ServletContextListener { protected InetSocketAddress resolveAuthority() throws ServerException { String hostnameKey = getName() + HTTP_HOSTNAME; String portKey = getName() + HTTP_PORT; String host = System.getProperty(hostnameKey); String port = System.getProperty(portKey); if (host == null) { throw new ServerException(ServerException.ERROR.S13, hostnameKey); } if (port == null) { throw new ServerException(ServerException.ERROR.S13, portKey); } try { InetAddress add = InetAddress.getByName(host); int portNum = Integer.parseInt(port); return new InetSocketAddress(add, portNum); } catch (UnknownHostException ex) { throw new ServerException(ServerException.ERROR.S14, ex.toString(), ex); } } protected ServerWebApp(String name, String homeDir, String configDir, String logDir, String tempDir, Configuration config); protected ServerWebApp(String name, String homeDir, Configuration config); ServerWebApp(String name); static void setHomeDirForCurrentThread(String homeDir); void contextInitialized(ServletContextEvent event); void contextDestroyed(ServletContextEvent event); InetSocketAddress getAuthority(); @VisibleForTesting void setAuthority(InetSocketAddress authority); }### Answer: @Test @TestDir public void testResolveAuthority() throws Exception { String dir = TestDirHelper.getTestDir().getAbsolutePath(); System.setProperty("TestServerWebApp3.home.dir", dir); System.setProperty("TestServerWebApp3.config.dir", dir); System.setProperty("TestServerWebApp3.log.dir", dir); System.setProperty("TestServerWebApp3.temp.dir", dir); System.setProperty("testserverwebapp3.http.hostname", "localhost"); System.setProperty("testserverwebapp3.http.port", "14000"); ServerWebApp server = new ServerWebApp("TestServerWebApp3") { }; InetSocketAddress address = server.resolveAuthority(); Assert.assertEquals("localhost", address.getHostName()); Assert.assertEquals(14000, address.getPort()); }
### Question: HServerInfo extends VersionedWritable implements WritableComparable<HServerInfo> { public synchronized HServerAddress getServerAddress() { return new HServerAddress(serverAddress); } HServerInfo(); HServerInfo(final HServerAddress serverAddress, final int webuiport); HServerInfo(HServerAddress serverAddress, long startCode, final int webuiport); HServerInfo(HServerInfo other); byte getVersion(); synchronized HServerAddress getServerAddress(); synchronized long getStartCode(); int getInfoPort(); int getWebuiPort(); String getHostname(); @Override synchronized String toString(); @Override boolean equals(Object obj); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerInfo o); }### Answer: @Test public void testGetServerAddress() { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerInfo hsi1 = new HServerInfo(hsa1, 1L, 5678); assertEquals(hsi1.getServerAddress(), hsa1); }
### Question: Param { protected abstract T parse(String str) throws Exception; Param(String name, T defaultValue); String getName(); T parseParam(String str); T value(); String toString(); }### Answer: @Test public void testShort() throws Exception { Param<Short> param = new ShortParam("S", (short) 1) { }; test(param, "S", "a short", (short) 1, (short) 2, "x", "" + ((int)Short.MAX_VALUE + 1)); param = new ShortParam("S", (short) 1, 8) { }; assertEquals(new Short((short)01777), param.parse("01777")); }
### Question: HServerInfo extends VersionedWritable implements WritableComparable<HServerInfo> { @Override public synchronized String toString() { return ServerName.getServerName(this.serverAddress.getHostnameAndPort(), this.startCode); } HServerInfo(); HServerInfo(final HServerAddress serverAddress, final int webuiport); HServerInfo(HServerAddress serverAddress, long startCode, final int webuiport); HServerInfo(HServerInfo other); byte getVersion(); synchronized HServerAddress getServerAddress(); synchronized long getStartCode(); int getInfoPort(); int getWebuiPort(); String getHostname(); @Override synchronized String toString(); @Override boolean equals(Object obj); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerInfo o); }### Answer: @Test public void testToString() { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerInfo hsi1 = new HServerInfo(hsa1, 1L, 5678); System.out.println(hsi1.toString()); }
### Question: HServerInfo extends VersionedWritable implements WritableComparable<HServerInfo> { public void readFields(DataInput in) throws IOException { super.readFields(in); this.serverAddress.readFields(in); this.startCode = in.readLong(); this.webuiport = in.readInt(); } HServerInfo(); HServerInfo(final HServerAddress serverAddress, final int webuiport); HServerInfo(HServerAddress serverAddress, long startCode, final int webuiport); HServerInfo(HServerInfo other); byte getVersion(); synchronized HServerAddress getServerAddress(); synchronized long getStartCode(); int getInfoPort(); int getWebuiPort(); String getHostname(); @Override synchronized String toString(); @Override boolean equals(Object obj); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerInfo o); }### Answer: @Test public void testReadFields() throws IOException { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerInfo hsi1 = new HServerInfo(hsa1, 1L, 5678); HServerAddress hsa2 = new HServerAddress("localhost", 1235); HServerInfo hsi2 = new HServerInfo(hsa2, 1L, 5678); byte [] bytes = Writables.getBytes(hsi1); HServerInfo deserialized = (HServerInfo)Writables.getWritable(bytes, new HServerInfo()); assertEquals(hsi1, deserialized); bytes = Writables.getBytes(hsi2); deserialized = (HServerInfo)Writables.getWritable(bytes, new HServerInfo()); assertNotSame(hsa1, deserialized); }
### Question: HServerInfo extends VersionedWritable implements WritableComparable<HServerInfo> { public int compareTo(HServerInfo o) { int compare = this.serverAddress.compareTo(o.getServerAddress()); if (compare != 0) return compare; if (this.webuiport != o.getInfoPort()) return this.webuiport - o.getInfoPort(); if (this.startCode != o.getStartCode()) return (int)(this.startCode - o.getStartCode()); return 0; } HServerInfo(); HServerInfo(final HServerAddress serverAddress, final int webuiport); HServerInfo(HServerAddress serverAddress, long startCode, final int webuiport); HServerInfo(HServerInfo other); byte getVersion(); synchronized HServerAddress getServerAddress(); synchronized long getStartCode(); int getInfoPort(); int getWebuiPort(); String getHostname(); @Override synchronized String toString(); @Override boolean equals(Object obj); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerInfo o); }### Answer: @Test public void testCompareTo() { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerInfo hsi1 = new HServerInfo(hsa1, 1L, 5678); HServerAddress hsa2 = new HServerAddress("localhost", 1235); HServerInfo hsi2 = new HServerInfo(hsa2, 1L, 5678); assertTrue(hsi1.compareTo(hsi1) == 0); assertTrue(hsi2.compareTo(hsi2) == 0); int compare1 = hsi1.compareTo(hsi2); int compare2 = hsi2.compareTo(hsi1); assertTrue((compare1 > 0)? compare2 < 0: compare2 > 0); }
### Question: TableSplit extends InputSplit implements Writable, Comparable<TableSplit> { @Override public int hashCode() { int result = tableName != null ? Arrays.hashCode(tableName) : 0; result = 31 * result + (scan != null ? scan.hashCode() : 0); result = 31 * result + (startRow != null ? Arrays.hashCode(startRow) : 0); result = 31 * result + (endRow != null ? Arrays.hashCode(endRow) : 0); result = 31 * result + (regionLocation != null ? regionLocation.hashCode() : 0); return result; } TableSplit(); TableSplit(byte [] tableName, Scan scan, byte [] startRow, byte [] endRow, final String location); TableSplit(byte[] tableName, byte[] startRow, byte[] endRow, final String location); Scan getScan(); byte [] getTableName(); byte [] getStartRow(); byte [] getEndRow(); String getRegionLocation(); @Override String[] getLocations(); @Override long getLength(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override String toString(); @Override int compareTo(TableSplit split); @Override boolean equals(Object o); @Override int hashCode(); static final Log LOG; }### Answer: @Test public void testHashCode() { TableSplit split1 = new TableSplit("table".getBytes(), "row-start".getBytes(), "row-end".getBytes(), "location"); TableSplit split2 = new TableSplit("table".getBytes(), "row-start".getBytes(), "row-end".getBytes(), "location"); assertEquals (split1, split2); assertTrue (split1.hashCode() == split2.hashCode()); HashSet<TableSplit> set = new HashSet<TableSplit>(2); set.add(split1); set.add(split2); assertTrue(set.size() == 1); }
### Question: Reader { public static <T> String[] columnsOf(Class<T> clazz) { return ColumnInfo.columnsOf(clazz); } static String[] columnsOf(Class<T> clazz); static ReaderBuilder<T> of(Class<T> clazz); }### Answer: @Test public void testShouldExtractColumns() { String[] columnNames = new String[] { "ID", "FIRST_NAME", "MIDDLE_NAME", "LAST_NAME", "DATE_OF_BIRTH", "FAV_NUMBER", "DATE_REGISTERED" }; assertArrayEquals(columnNames, Reader.columnsOf(Person.class)); }
### Question: GlideFutures { public static <T> ListenableFuture<T> submit(final RequestBuilder<T> requestBuilder) { return transformFromTargetAndResult(submitInternal(requestBuilder)); } private GlideFutures(); static ListenableFuture<Void> submitAndExecute( final RequestManager requestManager, RequestBuilder<T> requestBuilder, final ResourceConsumer<T> action, Executor executor); static ListenableFuture<T> submit(final RequestBuilder<T> requestBuilder); }### Answer: @Test public void testBaseLoad() throws Exception { ColorDrawable expected = new ColorDrawable(Color.RED); ListenableFuture<Drawable> future = GlideFutures.submit(Glide.with(app).load(expected)); assertThat(((ColorDrawable) Futures.getDone(future)).getColor()).isEqualTo(expected.getColor()); } @Test public void testErrorLoad() { final ListenableFuture<Bitmap> future = GlideFutures.submit(Glide.with(app).asBitmap().load(app)); assertThrows( ExecutionException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { Futures.getDone(future); } }); }
### Question: ReEncodingGifResourceEncoder implements ResourceEncoder<GifDrawable> { @NonNull @Override public EncodeStrategy getEncodeStrategy(@NonNull Options options) { Boolean encodeTransformation = options.get(ENCODE_TRANSFORMATION); return encodeTransformation != null && encodeTransformation ? EncodeStrategy.TRANSFORMED : EncodeStrategy.SOURCE; } @SuppressWarnings("unused") ReEncodingGifResourceEncoder(@NonNull Context context, @NonNull BitmapPool bitmapPool); @VisibleForTesting ReEncodingGifResourceEncoder(Context context, BitmapPool bitmapPool, Factory factory); @NonNull @Override EncodeStrategy getEncodeStrategy(@NonNull Options options); @Override boolean encode( @NonNull Resource<GifDrawable> resource, @NonNull File file, @NonNull Options options); @SuppressWarnings("WeakerAccess") static final Option<Boolean> ENCODE_TRANSFORMATION; }### Answer: @Test public void testEncodeStrategy_withEncodeTransformationTrue_returnsTransformed() { assertThat(encoder.getEncodeStrategy(options)).isEqualTo(EncodeStrategy.TRANSFORMED); } @Test public void testEncodeStrategy_withEncodeTransformationUnSet_returnsSource() { options.set(ReEncodingGifResourceEncoder.ENCODE_TRANSFORMATION, null); assertThat(encoder.getEncodeStrategy(options)).isEqualTo(EncodeStrategy.SOURCE); } @Test public void testEncodeStrategy_withEncodeTransformationFalse_returnsSource() { options.set(ReEncodingGifResourceEncoder.ENCODE_TRANSFORMATION, false); assertThat(encoder.getEncodeStrategy(options)).isEqualTo(EncodeStrategy.SOURCE); }
### Question: GifHeaderParser { @NonNull public GifHeader parseHeader() { if (rawData == null) { throw new IllegalStateException("You must call setData() before parseHeader()"); } if (err()) { return header; } readHeader(); if (!err()) { readContents(); if (header.frameCount < 0) { header.status = STATUS_FORMAT_ERROR; } } return header; } GifHeaderParser setData(@NonNull ByteBuffer data); GifHeaderParser setData(@Nullable byte[] data); void clear(); @NonNull GifHeader parseHeader(); boolean isAnimated(); }### Answer: @Test(expected = IllegalStateException.class) public void testThrowsIfParseHeaderCalledBeforeSetData() { GifHeaderParser parser = new GifHeaderParser(); parser.parseHeader(); }
### Question: DiskLruCache implements Closeable { public synchronized void close() throws IOException { if (journalWriter == null) { return; } for (Entry entry : new ArrayList<Entry>(lruEntries.values())) { if (entry.currentEditor != null) { entry.currentEditor.abort(); } } trimToSize(); closeWriter(journalWriter); journalWriter = null; } private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize); static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize); synchronized Value get(String key); Editor edit(String key); File getDirectory(); synchronized long getMaxSize(); synchronized void setMaxSize(long maxSize); synchronized long size(); synchronized boolean remove(String key); synchronized boolean isClosed(); synchronized void flush(); synchronized void close(); void delete(); }### Answer: @Test public void emptyCache() throws Exception { cache.close(); assertJournalEquals(); }
### Question: DiskLruCache implements Closeable { public Editor edit(String key) throws IOException { return edit(key, ANY_SEQUENCE_NUMBER); } private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize); static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize); synchronized Value get(String key); Editor edit(String key); File getDirectory(); synchronized long getMaxSize(); synchronized void setMaxSize(long maxSize); synchronized long size(); synchronized boolean remove(String key); synchronized boolean isClosed(); synchronized void flush(); synchronized void close(); void delete(); }### Answer: @Test public void cannotOperateOnEditAfterPublish() throws Exception { DiskLruCache.Editor editor = cache.edit("k1"); editor.set(0, "A"); editor.set(1, "B"); editor.commit(); assertInoperable(editor); } @Test public void cannotOperateOnEditAfterRevert() throws Exception { DiskLruCache.Editor editor = cache.edit("k1"); editor.set(0, "A"); editor.set(1, "B"); editor.abort(); assertInoperable(editor); } @Test public void nullKeyThrows() throws Exception { try { cache.edit(null); Assert.fail(); } catch (NullPointerException expected) { } }
### Question: DiskLruCache implements Closeable { public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize) throws IOException { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } if (valueCount <= 0) { throw new IllegalArgumentException("valueCount <= 0"); } File backupFile = new File(directory, JOURNAL_FILE_BACKUP); if (backupFile.exists()) { File journalFile = new File(directory, JOURNAL_FILE); if (journalFile.exists()) { backupFile.delete(); } else { renameTo(backupFile, journalFile, false); } } DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize); if (cache.journalFile.exists()) { try { cache.readJournal(); cache.processJournal(); return cache; } catch (IOException journalIsCorrupt) { System.out .println("DiskLruCache " + directory + " is corrupt: " + journalIsCorrupt.getMessage() + ", removing"); cache.delete(); } } directory.mkdirs(); cache = new DiskLruCache(directory, appVersion, valueCount, maxSize); cache.rebuildJournal(); return cache; } private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize); static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize); synchronized Value get(String key); Editor edit(String key); File getDirectory(); synchronized long getMaxSize(); synchronized void setMaxSize(long maxSize); synchronized long size(); synchronized boolean remove(String key); synchronized boolean isClosed(); synchronized void flush(); synchronized void close(); void delete(); }### Answer: @Test public void constructorDoesNotAllowZeroCacheSize() throws Exception { try { DiskLruCache.open(cacheDir, appVersion, 2, 0); Assert.fail(); } catch (IllegalArgumentException expected) { } } @Test public void constructorDoesNotAllowZeroValuesPerEntry() throws Exception { try { DiskLruCache.open(cacheDir, appVersion, 0, 10); Assert.fail(); } catch (IllegalArgumentException expected) { } }
### Question: DiskLruCache implements Closeable { public synchronized boolean remove(String key) throws IOException { checkNotClosed(); Entry entry = lruEntries.get(key); if (entry == null || entry.currentEditor != null) { return false; } for (int i = 0; i < valueCount; i++) { File file = entry.getCleanFile(i); if (file.exists() && !file.delete()) { throw new IOException("failed to delete " + file); } size -= entry.lengths[i]; entry.lengths[i] = 0; } redundantOpCount++; journalWriter.append(REMOVE); journalWriter.append(' '); journalWriter.append(key); journalWriter.append('\n'); lruEntries.remove(key); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return true; } private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize); static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize); synchronized Value get(String key); Editor edit(String key); File getDirectory(); synchronized long getMaxSize(); synchronized void setMaxSize(long maxSize); synchronized long size(); synchronized boolean remove(String key); synchronized boolean isClosed(); synchronized void flush(); synchronized void close(); void delete(); }### Answer: @Test public void removeAbsentElement() throws Exception { cache.remove("a"); }
### Question: DiskLruCache implements Closeable { public synchronized Value get(String key) throws IOException { checkNotClosed(); Entry entry = lruEntries.get(key); if (entry == null) { return null; } if (!entry.readable) { return null; } for (File file : entry.cleanFiles) { if (!file.exists()) { return null; } } redundantOpCount++; journalWriter.append(READ); journalWriter.append(' '); journalWriter.append(key); journalWriter.append('\n'); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return new Value(key, entry.sequenceNumber, entry.cleanFiles, entry.lengths); } private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize); static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize); synchronized Value get(String key); Editor edit(String key); File getDirectory(); synchronized long getMaxSize(); synchronized void setMaxSize(long maxSize); synchronized long size(); synchronized boolean remove(String key); synchronized boolean isClosed(); synchronized void flush(); synchronized void close(); void delete(); }### Answer: @Test public void readingTheSameFileMultipleTimes() throws Exception { set("a", "a", "b"); DiskLruCache.Value value = cache.get("a"); assertThat(value.getFile(0)).isSameInstanceAs(value.getFile(0)); } @Test public void aggressiveClearingHandlesRead() throws Exception { deleteDirectory(cacheDir); assertThat(cache.get("a")).isNull(); } @Test public void readingTheSameFileMultipleTimes() throws Exception { set("a", "a", "b"); DiskLruCache.Value value = cache.get("a"); assertThat(value.getFile(0)).isSameAs(value.getFile(0)); } @Test public void aggressiveClearingHandlesRead() throws Exception { FileUtils.deleteDirectory(cacheDir); assertThat(cache.get("a")).isNull(); }
### Question: CustomViewTarget implements Target<Z> { @NonNull public final T getView() { return view; } CustomViewTarget(@NonNull T view); @Override void onStart(); @Override void onStop(); @Override void onDestroy(); @SuppressWarnings("WeakerAccess") // Public API @NonNull final CustomViewTarget<T, Z> waitForLayout(); @NonNull @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) final CustomViewTarget<T, Z> clearOnDetach(); @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) @Deprecated final CustomViewTarget<T, Z> useTagId(@IdRes int tagId); @NonNull final T getView(); @Override final void getSize(@NonNull SizeReadyCallback cb); @Override final void removeCallback(@NonNull SizeReadyCallback cb); @Override final void onLoadStarted(@Nullable Drawable placeholder); @Override final void onLoadCleared(@Nullable Drawable placeholder); @Override final void setRequest(@Nullable Request request); @Override @Nullable final Request getRequest(); @Override String toString(); }### Answer: @Test public void testReturnsWrappedView() { assertEquals(view, target.getView()); }
### Question: CustomViewTarget implements Target<Z> { @Override @Nullable public final Request getRequest() { Object tag = getTag(); if (tag != null) { if (tag instanceof Request) { return (Request) tag; } else { throw new IllegalArgumentException("You must not pass non-R.id ids to setTag(id)"); } } return null; } CustomViewTarget(@NonNull T view); @Override void onStart(); @Override void onStop(); @Override void onDestroy(); @SuppressWarnings("WeakerAccess") // Public API @NonNull final CustomViewTarget<T, Z> waitForLayout(); @NonNull @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) final CustomViewTarget<T, Z> clearOnDetach(); @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) @Deprecated final CustomViewTarget<T, Z> useTagId(@IdRes int tagId); @NonNull final T getView(); @Override final void getSize(@NonNull SizeReadyCallback cb); @Override final void removeCallback(@NonNull SizeReadyCallback cb); @Override final void onLoadStarted(@Nullable Drawable placeholder); @Override final void onLoadCleared(@Nullable Drawable placeholder); @Override final void setRequest(@Nullable Request request); @Override @Nullable final Request getRequest(); @Override String toString(); }### Answer: @Test public void testReturnsNullFromGetRequestIfNoRequestSet() { assertNull(target.getRequest()); }
### Question: CustomViewTarget implements Target<Z> { @Override public final void onLoadCleared(@Nullable Drawable placeholder) { sizeDeterminer.clearCallbacksAndListener(); onResourceCleared(placeholder); if (!isClearedByUs) { maybeRemoveAttachStateListener(); } } CustomViewTarget(@NonNull T view); @Override void onStart(); @Override void onStop(); @Override void onDestroy(); @SuppressWarnings("WeakerAccess") // Public API @NonNull final CustomViewTarget<T, Z> waitForLayout(); @NonNull @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) final CustomViewTarget<T, Z> clearOnDetach(); @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) @Deprecated final CustomViewTarget<T, Z> useTagId(@IdRes int tagId); @NonNull final T getView(); @Override final void getSize(@NonNull SizeReadyCallback cb); @Override final void removeCallback(@NonNull SizeReadyCallback cb); @Override final void onLoadStarted(@Nullable Drawable placeholder); @Override final void onLoadCleared(@Nullable Drawable placeholder); @Override final void setRequest(@Nullable Request request); @Override @Nullable final Request getRequest(); @Override String toString(); }### Answer: @Test public void onLoadCleared_withoutClearOnDetach_doesNotRemoveListeners() { final AtomicInteger count = new AtomicInteger(); OnAttachStateChangeListener expected = new OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(View v) { count.incrementAndGet(); } @Override public void onViewDetachedFromWindow(View v) { } }; view.addOnAttachStateChangeListener(expected); attachStateTarget.onLoadCleared( null); activity.visible(); Truth.assertThat(count.get()).isEqualTo(1); }
### Question: ChromiumUrlFetcher implements DataFetcher<T>, ChromiumRequestSerializer.Listener { @Override public void cancel() { serializer.cancelRequest(url, this); } ChromiumUrlFetcher( ChromiumRequestSerializer serializer, ByteBufferParser<T> parser, GlideUrl url); @Override void loadData(Priority priority, DataCallback<? super T> callback); @Override void cleanup(); @Override void cancel(); @Override Class<T> getDataClass(); @Override DataSource getDataSource(); @Override void onRequestComplete(ByteBuffer byteBuffer); @Override void onRequestFailed(@Nullable Exception e); }### Answer: @Test public void testCancel_withNoStartedRequest_doesNothing() { fetcher.cancel(); }
### Question: PluginXmlHandler extends DefaultHandler { List<String> getSerializables() { return serializables; } @Override void startElement(String uri, String localName, String qName, Attributes attributes); @Override void endElement(String uri, String localName, String qName); }### Answer: @Test public void test() throws Exception { PluginXmlHandler handler = new PluginXmlHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.newSAXParser().parse(PluginXmlHandlerTest.class.getResource("plugin.xml").toString(), handler); assertThat(handler.getSerializables()).containsExactly("class1", "class2").inOrder(); }
### Question: Utils { public static long computeArraySUID(String name) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); try { dout.writeUTF(name); dout.writeInt(Modifier.PUBLIC | Modifier.FINAL | Modifier.ABSTRACT); dout.flush(); } catch (IOException ex) { throw new Error(ex); } MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException ex) { throw new Error(ex); } byte[] hashBytes = md.digest(bout.toByteArray()); long hash = 0; for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) { hash = (hash << 8) | (hashBytes[i] & 0xFF); } return hash; } private Utils(); static long computeArraySUID(String name); }### Answer: @Test public void testComputeArraySUID() { Class<?> clazz = String[][].class; assertEquals(ObjectStreamClass.lookup(clazz).getSerialVersionUID(), Utils.computeArraySUID(clazz.getName())); }
### Question: ConfigDataId implements Serializable { @Override public String toString() { return contextUri + "|" + href; } ConfigDataId(String contextUri, String href); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void testToString() { assertEquals("cells/phobosNode03Cell/nodes/phobosNode03/servers/server1|server.xml#ThreadPool_1183121908657", new ConfigDataId("cells/phobosNode03Cell/nodes/phobosNode03/servers/server1", "server.xml#ThreadPool_1183121908657").toString()); }
### Question: ConfigDataId implements Serializable { @Override public int hashCode() { return toString().hashCode(); } ConfigDataId(String contextUri, String href); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void testHashCode() { assertEquals(-1121788133, new ConfigDataId("cells/phobosNode03Cell/nodes/phobosNode03/servers/server1", "server.xml#ThreadPool_1183121908657").hashCode()); }
### Question: ConfigDataId implements Serializable { @Override public boolean equals(Object obj) { if (obj instanceof ConfigDataId) { ConfigDataId other = (ConfigDataId)obj; return other.contextUri.equals(contextUri) && other.href.equals(href); } else { return false; } } ConfigDataId(String contextUri, String href); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void testEquals() { ConfigDataId id1 = new ConfigDataId("cells/phobosNode03Cell/nodes/phobosNode03/servers/server1", "server.xml#ThreadPool_1183121908657"); ConfigDataId id2 = new ConfigDataId("cells/phobosNode03Cell/nodes/phobosNode03/servers/server1", "server.xml#ThreadPool_1183121908657"); ConfigDataId id3 = new ConfigDataId("cells/phobosNode03Cell/nodes/phobosNode03/servers/server1", "server.xml#someOtherId"); assertTrue(id1.equals(id2)); assertFalse(id1.equals(id3)); }
### Question: AbstractHttpRequestMatcher implements HttpRequestMatcher { protected abstract String getToStringInfix(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test public abstract void testGetToStringInfix();
### Question: ParamExpression extends AbstractNameValueExpression<String> { @Override protected boolean isCaseSensitiveName() { return true; } ParamExpression(String expression); }### Answer: @Test public void testIsCaseSensitiveName() { Assert.assertTrue(createExpression("a=1").isCaseSensitiveName()); Assert.assertTrue(createExpression("a=!1").isCaseSensitiveName()); Assert.assertTrue(createExpression("b=1").isCaseSensitiveName()); }
### Question: DubboTransportedMethodMetadataResolver { public Map<DubboTransportedMethodMetadata, RestMethodMetadata> resolve( Class<?> targetType) { Set<DubboTransportedMethodMetadata> dubboTransportedMethodMetadataSet = resolveDubboTransportedMethodMetadataSet( targetType); Map<String, RestMethodMetadata> restMethodMetadataMap = resolveRestRequestMetadataMap( targetType); return dubboTransportedMethodMetadataSet.stream().collect( Collectors.toMap(methodMetadata -> methodMetadata, methodMetadata -> { RestMethodMetadata restMethodMetadata = restMethodMetadataMap .get(configKey(targetType, methodMetadata.getMethod())); restMethodMetadata.setMethod(methodMetadata.getMethodMetadata()); return restMethodMetadata; })); } DubboTransportedMethodMetadataResolver(PropertyResolver propertyResolver, Contract contract); Map<DubboTransportedMethodMetadata, RestMethodMetadata> resolve( Class<?> targetType); }### Answer: @Test public void testResolve() { Set<DubboTransportedMethodMetadata> metadataSet = resolver .resolveDubboTransportedMethodMetadataSet(TestDefaultService.class); Assert.assertEquals(1, metadataSet.size()); }
### Question: NacosServiceDiscovery { public List<String> getServices() throws NacosException { String group = discoveryProperties.getGroup(); ListView<String> services = namingService().getServicesOfServer(1, Integer.MAX_VALUE, group); return services.getData(); } NacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties, NacosServiceManager nacosServiceManager); List<ServiceInstance> getInstances(String serviceId); List<String> getServices(); static List<ServiceInstance> hostToServiceInstanceList( List<Instance> instances, String serviceId); static ServiceInstance hostToServiceInstance(Instance instance, String serviceId); }### Answer: @Test public void testGetServices() throws NacosException { ListView<String> nacosServices = new ListView<>(); nacosServices.setData(new LinkedList<>()); nacosServices.getData().add(serviceName + "1"); nacosServices.getData().add(serviceName + "2"); nacosServices.getData().add(serviceName + "3"); NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties.class); NacosServiceManager nacosServiceManager = mock(NacosServiceManager.class); NamingService namingService = mock(NamingService.class); when(nacosServiceManager .getNamingService(nacosDiscoveryProperties.getNacosProperties())) .thenReturn(namingService); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE), eq("DEFAULT"))).thenReturn(nacosServices); NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery( nacosDiscoveryProperties, nacosServiceManager); List<String> services = serviceDiscovery.getServices(); assertThat(services.size()).isEqualTo(3); assertThat(services.contains(serviceName + "1")); assertThat(services.contains(serviceName + "2")); assertThat(services.contains(serviceName + "3")); }
### Question: ProduceMediaTypeExpression extends AbstractMediaTypeExpression { public final boolean match(List<MediaType> acceptedMediaTypes) { boolean match = matchMediaType(acceptedMediaTypes); return (!isNegated() ? match : !match); } ProduceMediaTypeExpression(String expression); ProduceMediaTypeExpression(MediaType mediaType, boolean negated); final boolean match(List<MediaType> acceptedMediaTypes); }### Answer: @Test public void testMatch() { ProduceMediaTypeExpression expression = createExpression( MediaType.APPLICATION_JSON_VALUE); Assert.assertTrue(expression.match( Arrays.asList(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON))); expression = createExpression(MediaType.APPLICATION_JSON_VALUE); Assert.assertFalse(expression.match(Arrays.asList(MediaType.APPLICATION_XML))); } @Test public void testMatch() { ProduceMediaTypeExpression expression = createExpression(MediaType.APPLICATION_JSON_VALUE); Assert.assertTrue(expression.match(Arrays.asList(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON))); expression = createExpression(MediaType.APPLICATION_JSON_VALUE); Assert.assertFalse(expression.match(Arrays.asList(MediaType.APPLICATION_XML))); }
### Question: AbstractNameValueExpression implements NameValueExpression<T> { @Override public int hashCode() { int result = (isCaseSensitiveName() ? this.name.hashCode() : this.name.toLowerCase().hashCode()); result = 31 * result + (this.value != null ? this.value.hashCode() : 0); result = 31 * result + (this.negated ? 1 : 0); return result; } AbstractNameValueExpression(String expression); @Override String getName(); @Override T getValue(); @Override boolean isNegated(); final boolean match(HttpRequest request); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testEqualsAndHashCode() { Assert.assertEquals(createExpression("a"), createExpression("a")); Assert.assertEquals(createExpression("a").hashCode(), createExpression("a").hashCode()); Assert.assertEquals(createExpression("a=1"), createExpression("a = 1 ")); Assert.assertEquals(createExpression("a=1").hashCode(), createExpression("a = 1 ").hashCode()); Assert.assertNotEquals(createExpression("a"), createExpression("b")); Assert.assertNotEquals(createExpression("a").hashCode(), createExpression("b").hashCode()); }
### Question: AbstractMediaTypeExpression implements MediaTypeExpression, Comparable<AbstractMediaTypeExpression> { @Override public int hashCode() { return this.mediaType.hashCode(); } AbstractMediaTypeExpression(String expression); AbstractMediaTypeExpression(MediaType mediaType, boolean negated); @Override MediaType getMediaType(); @Override boolean isNegated(); @Override int compareTo(AbstractMediaTypeExpression other); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testEqualsAndHashCode() { Assert.assertEquals(createExpression(MediaType.APPLICATION_JSON_VALUE), createExpression(MediaType.APPLICATION_JSON_VALUE)); Assert.assertEquals(createExpression(MediaType.APPLICATION_JSON_VALUE).hashCode(), createExpression(MediaType.APPLICATION_JSON_VALUE).hashCode()); }
### Question: AbstractMediaTypeExpression implements MediaTypeExpression, Comparable<AbstractMediaTypeExpression> { @Override public int compareTo(AbstractMediaTypeExpression other) { return MediaType.SPECIFICITY_COMPARATOR.compare(this.getMediaType(), other.getMediaType()); } AbstractMediaTypeExpression(String expression); AbstractMediaTypeExpression(MediaType mediaType, boolean negated); @Override MediaType getMediaType(); @Override boolean isNegated(); @Override int compareTo(AbstractMediaTypeExpression other); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testCompareTo() { Assert.assertEquals(0, createExpression(MediaType.APPLICATION_JSON_VALUE) .compareTo(createExpression(MediaType.APPLICATION_JSON_VALUE))); } @Test public void testCompareTo() { Assert.assertEquals(0, createExpression(MediaType.APPLICATION_JSON_VALUE).compareTo(createExpression(MediaType.APPLICATION_JSON_VALUE))); }
### Question: HeaderExpression extends AbstractNameValueExpression<String> { @Override protected boolean isCaseSensitiveName() { return false; } HeaderExpression(String expression); }### Answer: @Test public void testIsCaseSensitiveName() { Assert.assertFalse(createExpression("a=1").isCaseSensitiveName()); Assert.assertFalse(createExpression("a=!1").isCaseSensitiveName()); Assert.assertFalse(createExpression("b=1").isCaseSensitiveName()); }
### Question: HttpRequestParamsMatcher extends AbstractHttpRequestMatcher { @Override public boolean match(HttpRequest request) { if (CollectionUtils.isEmpty(expressions)) { return true; } for (ParamExpression paramExpression : expressions) { if (paramExpression.match(request)) { return true; } } return false; } HttpRequestParamsMatcher(String... params); @Override boolean match(HttpRequest request); }### Answer: @Test public void testEquals() { HttpRequestParamsMatcher matcher = new HttpRequestParamsMatcher("a ", "a = 1"); MockClientHttpRequest request = new MockClientHttpRequest(); request.setURI(URI.create("http: Assert.assertTrue(matcher.match(request)); request.setURI(URI.create("http: Assert.assertTrue(matcher.match(request)); matcher = new HttpRequestParamsMatcher("a ", "a =1", "b", "b=2"); request.setURI(URI.create("http: Assert.assertTrue(matcher.match(request)); request.setURI(URI.create("http: Assert.assertTrue(matcher.match(request)); matcher = new HttpRequestParamsMatcher("a ", "a =1", "b", "b=2", "b = 3 "); request.setURI(URI.create("http: Assert.assertTrue(matcher.match(request)); request.setURI(URI.create("http: Assert.assertFalse(matcher.match(request)); }
### Question: ConsumeMediaTypeExpression extends AbstractMediaTypeExpression { public final boolean match(MediaType contentType) { boolean match = getMediaType().includes(contentType); return (!isNegated() ? match : !match); } ConsumeMediaTypeExpression(String expression); ConsumeMediaTypeExpression(MediaType mediaType, boolean negated); final boolean match(MediaType contentType); }### Answer: @Test public void testMatch() { ConsumeMediaTypeExpression expression = createExpression(MediaType.ALL_VALUE); Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON)); expression = createExpression(MediaType.APPLICATION_JSON_VALUE); Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON)); expression = createExpression(MediaType.APPLICATION_JSON_VALUE + ";q=0.7"); Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON)); expression = createExpression(MediaType.TEXT_HTML_VALUE); Assert.assertFalse(expression.match(MediaType.APPLICATION_JSON)); } @Test public void testMatch() { ConsumeMediaTypeExpression expression = createExpression(MediaType.ALL_VALUE); Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); expression = createExpression(MediaType.APPLICATION_JSON_VALUE); Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); expression = createExpression(MediaType.APPLICATION_JSON_VALUE + ";q=0.7"); Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); expression = createExpression(MediaType.TEXT_HTML_VALUE); Assert.assertFalse(expression.match(MediaType.APPLICATION_JSON_UTF8)); }
### Question: AbstractHttpRequestMatcher implements HttpRequestMatcher { protected abstract Collection<?> getContent(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test public abstract void testGetContent();
### Question: TyrusExtension implements Extension, Serializable { @Override public String toString() { final StringBuilder sb = new StringBuilder("TyrusExtension{"); sb.append("name='").append(name).append('\''); sb.append(", parameters=").append(parameters); sb.append('}'); return sb.toString(); } TyrusExtension(String name); TyrusExtension(String name, List<Parameter> parameters); @Override String getName(); @Override List<Parameter> getParameters(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static List<Extension> fromString(List<String> s); static List<Extension> fromHeaders(List<String> extensionHeaders); }### Answer: @Test public void testToString() { TyrusExtension.toString(new Extension() { @Override public String getName() { return "name"; } @Override public List<Parameter> getParameters() { return null; } }); }
### Question: Credentials { public String getUsername() { return username; } Credentials(String username, byte[] password); Credentials(String username, String password); String getUsername(); byte[] getPassword(); String toString(); }### Answer: @Test public void testGetUsername() throws Exception { Credentials credentials = new Credentials(USERNAME, PASSWORD_STRING); assertEquals(USERNAME, credentials.getUsername()); }
### Question: Credentials { public byte[] getPassword() { return password; } Credentials(String username, byte[] password); Credentials(String username, String password); String getUsername(); byte[] getPassword(); String toString(); }### Answer: @Test public void testGetPasswordString() throws Exception { Credentials credentials = new Credentials(USERNAME, PASSWORD_STRING); assertArrayEquals(PASSWORD_STRING.getBytes(AuthConfig.CHARACTER_SET), credentials.getPassword()); } @Test public void testGetPasswordByteArray() throws Exception { Credentials credentials = new Credentials(USERNAME, PASSWORD_BYTE_ARRAY); assertEquals(PASSWORD_BYTE_ARRAY, credentials.getPassword()); }
### Question: SslFilter extends Filter { @Override synchronized void write(final ByteBuffer applicationData, final CompletionHandler<ByteBuffer> completionHandler) { switch (state) { case NOT_STARTED: { writeQueue.write(applicationData, completionHandler); return; } case HANDSHAKING: { completionHandler.failed(new IllegalStateException("Cannot write until SSL handshake has been completed")); break; } case REHANDSHAKING: { storePendingApplicationWrite(applicationData, completionHandler); break; } case DATA: { handleWrite(applicationData, completionHandler); break; } case CLOSED: { completionHandler.failed(new IllegalStateException("SSL session has been closed")); break; } } } SslFilter(Filter downstreamFilter, SslEngineConfigurator sslEngineConfigurator, String serverHost); SslFilter(Filter downstreamFilter, org.glassfish.tyrus.container.jdk.client.SslEngineConfigurator sslEngineConfigurator); }### Answer: @Test public void testCloseServer() throws Throwable { CountDownLatch latch = new CountDownLatch(1); SslEchoServer server = new SslEchoServer(); try { server.start(); String message = "Hello world\n"; ByteBuffer readBuffer = ByteBuffer.allocate(message.length()); Filter clientSocket = openClientSocket("localhost", readBuffer, latch, null); clientSocket.write(stringToBuffer(message), new CompletionHandler<ByteBuffer>() { @Override public void failed(Throwable t) { t.printStackTrace(); } }); assertTrue(latch.await(5, TimeUnit.SECONDS)); server.stop(); readBuffer.flip(); String received = bufferToString(readBuffer); assertEquals(message, received); } finally { server.stop(); } }
### Question: TyrusFuture implements Future<T> { @Override public T get() throws InterruptedException, ExecutionException { latch.await(); if (throwable != null) { throw new ExecutionException(throwable); } return result; } @Override boolean cancel(boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override T get(); @Override T get(long timeout, TimeUnit unit); void setResult(T result); void setFailure(Throwable throwable); }### Answer: @Test public void testGet() throws ExecutionException, InterruptedException { TyrusFuture<String> voidTyrusFuture = new TyrusFuture<String>(); voidTyrusFuture.setResult(RESULT); assertEquals(RESULT, voidTyrusFuture.get()); } @Test(expected = InterruptedException.class) public void testInterrupted() throws ExecutionException, InterruptedException { TyrusFuture<String> voidTyrusFuture = new TyrusFuture<String>(); Thread.currentThread().interrupt(); voidTyrusFuture.get(); } @Test(expected = TimeoutException.class) public void testTimeout() throws InterruptedException, ExecutionException, TimeoutException { TyrusFuture<Void> voidTyrusFuture = new TyrusFuture<Void>(); voidTyrusFuture.get(1, TimeUnit.MILLISECONDS); }
### Question: TyrusFuture implements Future<T> { @Override public boolean isDone() { return (latch.getCount() == 0); } @Override boolean cancel(boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override T get(); @Override T get(long timeout, TimeUnit unit); void setResult(T result); void setFailure(Throwable throwable); }### Answer: @Test public void testIsDone() { TyrusFuture<Void> voidTyrusFuture = new TyrusFuture<Void>(); assertFalse(voidTyrusFuture.isDone()); voidTyrusFuture.setResult(null); assertTrue(voidTyrusFuture.isDone()); }
### Question: TyrusExtension implements Extension, Serializable { @Override public String getName() { return name; } TyrusExtension(String name); TyrusExtension(String name, List<Parameter> parameters); @Override String getName(); @Override List<Parameter> getParameters(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static List<Extension> fromString(List<String> s); static List<Extension> fromHeaders(List<String> extensionHeaders); }### Answer: @Test public void simple() { final TyrusExtension test = new TyrusExtension("test"); assertEquals("test", test.getName()); }
### Question: AbstractDAO implements DAO<TInterface> { @Override @SuppressWarnings("unchecked") public TInterface get(UID uid) throws NoResultException { return (TInterface) this.getEntity(uid); } @Override void beginTransaction(); @Override void rollback(); @Override void setForRollback(); @Override boolean isSetForRollback(); @Override void commit(); @Override void lock(TInterface entity, LockModeType type); @Override boolean isTransactionActive(); @Override @SuppressWarnings("unchecked") TInterface get(UID uid); @Override @SuppressWarnings("unchecked") TInterface create(final TInterface entity); @Override @SuppressWarnings("unchecked") final synchronized TInterface update(final TInterface entity); @Override boolean exists(UID uid); }### Answer: @Test public void get() { BaseEntity entity = AbstractDAOTest.abstractDAO.get(AbstractDAOTest.existingObjUid); Assert.assertEquals(entity.getClass(), JPABusinessEntity.class); JPABusinessEntity business = (JPABusinessEntity) entity; Assert.assertEquals(business.getUID(), AbstractDAOTest.existingObjUid); Assert.assertEquals(business.getName(), "Test Business"); } @Test public void get_noSuchUid() { this.expectedException.expect(NoResultException.class); AbstractDAOTest.abstractDAO.get(AbstractDAOTest.nonExistingObjUid); } @Test public void get_inactive() { this.expectedException.expect(NoResultException.class); AbstractDAOTest.abstractDAO.get(AbstractDAOTest.inactiveObjUid); }
### Question: AbstractDAO implements DAO<TInterface> { @Override public boolean exists(UID uid) { Class<? extends TEntity> entityClass = this.getEntityClass(); TEntity entity = Ebean.find(entityClass).where().eq("uid", uid.toString()).findOne(); return entity != null; } @Override void beginTransaction(); @Override void rollback(); @Override void setForRollback(); @Override boolean isSetForRollback(); @Override void commit(); @Override void lock(TInterface entity, LockModeType type); @Override boolean isTransactionActive(); @Override @SuppressWarnings("unchecked") TInterface get(UID uid); @Override @SuppressWarnings("unchecked") TInterface create(final TInterface entity); @Override @SuppressWarnings("unchecked") final synchronized TInterface update(final TInterface entity); @Override boolean exists(UID uid); }### Answer: @Test public void exists() { boolean exists = AbstractDAOTest.abstractDAO.exists(AbstractDAOTest.existingObjUid); Assert.assertEquals(exists, true); } @Test public void exists_noSuchUid() { boolean exists = AbstractDAOTest.abstractDAO.exists(AbstractDAOTest.nonExistingObjUid); Assert.assertEquals(exists, false); } @Test public void exists_inactive() { boolean exists = AbstractDAOTest.abstractDAO.exists(AbstractDAOTest.inactiveObjUid); Assert.assertEquals(exists, false); }
### Question: DAOSupplierImpl extends AbstractDAO<SupplierEntity, JPASupplierEntity> implements DAOSupplier { @Override public List<SupplierEntity> getAllActiveSuppliers() { return this.checkEntityList(this.querySupplier().active.eq(true).findList(), SupplierEntity.class); } @Override SupplierEntity getEntityInstance(); @Override List<SupplierEntity> getAllActiveSuppliers(); }### Answer: @Test public void getAllActiveSuppliers_noSuppliers() { List<SupplierEntity> suppliers = DAOSupplierImplTest.daoSupplierImpl.getAllActiveSuppliers(); Assert.assertEquals(suppliers.size(), 0); } @Test public void getAllActiveSuppliers_noActiveSuppliers() { Ebean.beginTransaction(); JPASupplierEntity supplier = new JPASupplierEntity(); supplier.setUID(DAOSupplierImplTest.inactiveObjUid); supplier.setName("Test Supplier 0"); Ebean.commitTransaction(); List<SupplierEntity> suppliers = DAOSupplierImplTest.daoSupplierImpl.getAllActiveSuppliers(); Assert.assertEquals(suppliers.size(), 0); } @Test public void getAllActiveSuppliers() { Ebean.beginTransaction(); JPASupplierEntity supplier = new JPASupplierEntity(); supplier.setUID(DAOSupplierImplTest.existingObjUid1); supplier.setName("Test Supplier 1"); DAOSupplierImplTest.daoSupplierImpl.create(supplier); supplier = new JPASupplierEntity(); supplier.setUID(DAOSupplierImplTest.existingObjUid2); supplier.setName("Test Supplier 2"); DAOSupplierImplTest.daoSupplierImpl.create(supplier); Ebean.commitTransaction(); List<SupplierEntity> suppliers = DAOSupplierImplTest.daoSupplierImpl.getAllActiveSuppliers(); Assert.assertEquals(suppliers.size(), 2); }
### Question: DAOCustomerImpl extends AbstractDAO<CustomerEntity, JPACustomerEntity> implements DAOCustomer { @Override public List<CustomerEntity> getAllActiveCustomers() { return this.checkEntityList(this.queryCustomer().active.eq(true).findList(), CustomerEntity.class); } @Override List<CustomerEntity> getAllActiveCustomers(); @Override CustomerEntity getEntityInstance(); }### Answer: @Test public void getAllActiveCustomers_noCustomers() { List<CustomerEntity> customers = DAOCustomerImplTest.daoCustomerImpl.getAllActiveCustomers(); Assert.assertEquals(customers.size(), 0); } @Test public void getAllActiveCustomers_noActiveCustomers() { Ebean.beginTransaction(); JPACustomerEntity customer = new JPACustomerEntity(); customer.setUID(DAOCustomerImplTest.inactiveObjUid); customer.setName("Test Customer 0"); Ebean.commitTransaction(); List<CustomerEntity> customers = DAOCustomerImplTest.daoCustomerImpl.getAllActiveCustomers(); Assert.assertEquals(customers.size(), 0); } @Test public void getAllActiveCustomers() { Ebean.beginTransaction(); JPACustomerEntity customer = new JPACustomerEntity(); customer.setUID(DAOCustomerImplTest.existingObjUid1); customer.setName("Test Customer 1"); DAOCustomerImplTest.daoCustomerImpl.create(customer); customer = new JPACustomerEntity(); customer.setUID(DAOCustomerImplTest.existingObjUid2); customer.setName("Test Customer 2"); DAOCustomerImplTest.daoCustomerImpl.create(customer); Ebean.commitTransaction(); List<CustomerEntity> customers = DAOCustomerImplTest.daoCustomerImpl.getAllActiveCustomers(); Assert.assertEquals(customers.size(), 2); }
### Question: DAOProductImpl extends AbstractDAO<ProductEntity, JPAProductEntity> implements DAOProduct { @Override public List<ProductEntity> getAllActiveProducts() { return this.checkEntityList(this.queryProduct().active.eq(true).findList(), ProductEntity.class); } @Override List<ProductEntity> getAllActiveProducts(); @Override ProductEntity getEntityInstance(); }### Answer: @Test public void getAllActiveProducts_noProducts() { List<ProductEntity> products = DAOProductImplTest.daoProductImpl.getAllActiveProducts(); Assert.assertEquals(products.size(), 0); } @Test public void getAllActiveProducts_noActiveProducts() { Ebean.beginTransaction(); JPAProductEntity product = new JPAProductEntity(); product.setUID(DAOProductImplTest.inactiveObjUid); product.setDescription("Test Product 0"); Ebean.commitTransaction(); List<ProductEntity> products = DAOProductImplTest.daoProductImpl.getAllActiveProducts(); Assert.assertEquals(products.size(), 0); } @Test public void getAllActiveProducts() { Ebean.beginTransaction(); JPAProductEntity product = new JPAProductEntity(); product.setUID(DAOProductImplTest.existingObjUid1); product.setDescription("Test Product 1"); DAOProductImplTest.daoProductImpl.create(product); product = new JPAProductEntity(); product.setUID(DAOProductImplTest.existingObjUid2); product.setDescription("Test Product 2"); DAOProductImplTest.daoProductImpl.create(product); Ebean.commitTransaction(); List<ProductEntity> products = DAOProductImplTest.daoProductImpl.getAllActiveProducts(); Assert.assertEquals(products.size(), 2); }
### Question: DAOTicketImpl extends AbstractDAO<TicketEntity, JPATicketEntity> implements DAOTicket { @Override public UID getObjectEntityUID(String ticketUID) throws NoResultException { JPATicketEntity ticket = this.queryTicket().uid.eq(ticketUID).findOne(); if (ticket == null) { throw new NoResultException(); } return ticket.getObjectUID(); } @Override TicketEntity getEntityInstance(); @Override UID getObjectEntityUID(String ticketUID); }### Answer: @Test public void getObjectEntityUID_noTickets() { this.expectedException.expect(NoResultException.class); DAOTicketImplTest.daoTicketImpl.getObjectEntityUID(DAOTicketImplTest.rightTicketUid.toString()); } @Test public void getObjectEntityUID_noSuchUID() { Ebean.beginTransaction(); JPATicketEntity ticket = new JPATicketEntity(); ticket.setUID(DAOTicketImplTest.rightTicketUid); ticket.setObjectUID(DAOTicketImplTest.referencedObjUid); DAOTicketImplTest.daoTicketImpl.create(ticket); Ebean.commitTransaction(); this.expectedException.expect(NoResultException.class); DAOTicketImplTest.daoTicketImpl.getObjectEntityUID(DAOTicketImplTest.wrongTicketUid.toString()); } @Test public void getObjectEntityUID() { Ebean.beginTransaction(); JPATicketEntity ticket = new JPATicketEntity(); ticket.setUID(DAOTicketImplTest.rightTicketUid); ticket.setObjectUID(DAOTicketImplTest.referencedObjUid); DAOTicketImplTest.daoTicketImpl.create(ticket); Ebean.commitTransaction(); UID objUid = DAOTicketImplTest.daoTicketImpl.getObjectEntityUID(DAOTicketImplTest.rightTicketUid.toString()); Assert.assertEquals(objUid, DAOTicketImplTest.referencedObjUid); }
### Question: TempfileBufferedInputStream extends InputStream { @Override public int read() throws IOException { byte[] bytes = new byte[1]; int read = read(bytes); return (read > 0) ? bytes[0] & 0xff : -1; } TempfileBufferedInputStream(InputStream source); TempfileBufferedInputStream(InputStream source, int threshold); @Override int read(); @Override int read(byte[] bytes); @Override int read(byte[] bytes, int offset, int length); @Override synchronized void reset(); @Override synchronized void mark(int i); @Override boolean markSupported(); @Override void close(); }### Answer: @Test public void shouldNotLeaveTempFilesLingering() throws Exception { String originalTmpdir = System.getProperty("java.io.tmpdir"); System.setProperty("java.io.tmpdir", tempDir.getRoot().toString()); try { InputStream subject = new TempfileBufferedInputStream(containing("123456789"), 3); read(subject); assertThat(tempDir.getRoot().listFiles()).isEmpty(); } finally { System.setProperty("java.io.tmpdir", originalTmpdir); } }
### Question: JRubyRackApplication implements RackApplication { @Override public RackResponse call(RackEnvironment environment) { RubyHash environmentHash = convertToRubyHash(environment.entrySet()); RubyArray response = callRackApplication(environmentHash); return convertToJavaRackResponse(response); } JRubyRackApplication(IRubyObject application); @Override RackResponse call(RackEnvironment environment); }### Answer: @Test public void callSetsTheResponseHeaders() { RackResponse response = app.call(env); assertThat(response.getHeaders()).contains(entry("Content-Type", "text/plain")); } @Test public void callSetsTheResponseBody() { RackResponse response = app.call(env); ImmutableList.Builder<String> strings = ImmutableList.builder(); Iterator<byte[]> bytes = response.getBody(); while (bytes.hasNext()) { strings.add(new String(bytes.next())); } assertThat(SPACE.join(strings.build())).isEqualTo(SPACE.join(env.keySet())); } @Test public void callParsesTheResponseStatusFromAString() { IRubyObject callable = Ruby.getGlobalRuntime() .evalScriptlet("proc { |env| ['201', {'Content-Type' => 'text/plain'}, env.keys] }"); app = new JRubyRackApplication(callable); RackResponse response = app.call(env); assertThat(response.getStatus()).isEqualTo(201); } @Test public void callSetsTheResponseStatus() { RackResponse response = app.call(env); assertThat(response.getStatus()).isEqualTo(200); }
### Question: JRubyRackInput extends RubyObject { @JRubyMethod(optional = 1) public IRubyObject read(ThreadContext context, IRubyObject[] args) { Integer length = null; if (args.length > 0) { long arg = args[0].convertToInteger("to_i").getLongValue(); length = (int) Math.min(arg, Integer.MAX_VALUE); } try { return toRubyString(rackInput.read(length)); } catch (IOException e) { throw getRuntime().newIOErrorFromException(e); } } JRubyRackInput(Ruby runtime, RubyClass klass); JRubyRackInput(Ruby runtime, RackInput rackInput); @JRubyMethod IRubyObject gets(); @JRubyMethod IRubyObject each(ThreadContext context, Block block); @JRubyMethod(optional = 1) IRubyObject read(ThreadContext context, IRubyObject[] args); @JRubyMethod IRubyObject rewind(); }### Answer: @Test public void shouldWrapJavaIOExceptions() throws Exception { Ruby ruby = Ruby.newInstance(); RackInput rackInput = mock(RackInput.class); when(rackInput.read(null)).thenThrow(new IOException("fake")); JRubyRackInput subject = new JRubyRackInput(ruby, rackInput); GlobalVariables globalVariables = ruby.getGlobalVariables(); globalVariables.set("$rack_input", subject); IRubyObject result = ruby.evalScriptlet( "begin; $rack_input.read; rescue IOError => e; \"rescued #{e.message}\"; end"); assertThat(result.asJavaString()).isEqualTo("rescued fake"); }
### Question: RackResponsePropagator { public void propagate(RackResponse rackResponse, HttpServletResponse response) { propagateStatus(rackResponse, response); propagateHeaders(rackResponse, response); propagateBody(rackResponse, response); } void propagate(RackResponse rackResponse, HttpServletResponse response); }### Answer: @Test public void propagateStatus() { rackResponse.status(404); subject.propagate(rackResponse.build(), response); verify(response).setStatus(404); } @Test public void propagateHeadersSkipsHeadsRackHeaders() { rackResponse.header("rack.internal", "42"); subject.propagate(rackResponse.build(), response); verify(response, never()).addHeader(eq("rack.internal"), anyString()); } @Test public void propagateHeadersMultipleValues() { rackResponse.header("Set-Cookie", "foo=bar\nbar=foo"); subject.propagate(rackResponse.build(), response); verify(response).addHeader("Set-Cookie", "foo=bar"); verify(response).addHeader("Set-Cookie", "bar=foo"); }
### Question: RackResponsePropagator { private void propagateHeaders(RackResponse rackResponse, HttpServletResponse response) { for (Map.Entry<String, String> header : rackResponse.getHeaders().entrySet()) { if (shouldPropagateHeaderToClient(header)) { for (String val : header.getValue().split("\n")) { response.addHeader(header.getKey(), val); } } } try { response.flushBuffer(); } catch (IOException e) { Throwables.propagate(e); } } void propagate(RackResponse rackResponse, HttpServletResponse response); }### Answer: @Test public void propagateHeaders() { rackResponse.header("Content-Type", "text/plain"); subject.propagate(rackResponse.build(), response); verify(response).addHeader("Content-Type", "text/plain"); }
### Question: RackResponsePropagator { private void propagateBody(RackResponse rackResponse, HttpServletResponse response) { ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); } catch (IOException e) { Throwables.propagate(e); } Iterator<byte[]> body = rackResponse.getBody(); while (body.hasNext()) { try { outputStream.write(body.next()); } catch (IOException e) { Throwables.propagate(e); } } try { outputStream.flush(); } catch (IOException e) { Throwables.propagate(e); } } void propagate(RackResponse rackResponse, HttpServletResponse response); }### Answer: @Test public void propagateBody() throws IOException { rackResponse.body("Here ".getBytes(), "are ".getBytes(), "the ".getBytes(), "parts.".getBytes()); subject.propagate(rackResponse.build(), response); InOrder inOrder = inOrder(outputStream); inOrder.verify(outputStream).write("Here ".getBytes()); inOrder.verify(outputStream).write("are ".getBytes()); inOrder.verify(outputStream).write("the ".getBytes()); inOrder.verify(outputStream).write("parts.".getBytes()); inOrder.verify(outputStream).flush(); }
### Question: RackEnvironmentBuilder { private RackInput rackInput(HttpServletRequest request) { try { return new RackInput(new TempfileBufferedInputStream(request.getInputStream())); } catch (IOException e) { throw propagate(e); } } RackEnvironment build(HttpServletRequest request); }### Answer: @Test public void rackInput() throws IOException { request.method("POST").body("foo=42&bar=0"); assertThat(environment()).containsKey("rack.input"); assertThat(environment().get("rack.input")).isInstanceOf(RackInput.class); }
### Question: RackLogger { public void info(String message) { logger.info(message); } RackLogger(Logger logger); void info(String message); void debug(String message); void warn(String message); void error(String message); void fatal(String message); static final Marker FATAL; }### Answer: @Test public void info() { subject.info(MESSAGE); verify(delegate).info(MESSAGE); }
### Question: RackServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RackEnvironment rackEnvironment = rackEnvironmentBuilder.build(request); try { RackResponse rackResponse = rackApplication.call(rackEnvironment); rackResponsePropagator.propagate(rackResponse, response); } finally { rackEnvironment.closeRackInput(); } } RackServlet(RackApplication rackApplication); RackServlet(RackEnvironmentBuilder rackEnvironmentBuilder, RackApplication rackApplication, RackResponsePropagator rackResponsePropagator); }### Answer: @Test public void service() throws ServletException, IOException { when(rackApplication.call(rackEnvironment)).thenReturn(rackResponse); subject.service(request, response); InOrder inOrder = inOrder(rackResponsePropagator, rackEnvironment); inOrder.verify(rackResponsePropagator).propagate(rackResponse, response); inOrder.verify(rackEnvironment).closeRackInput(); }
### Question: RackInput implements Closeable { public byte[] gets() throws IOException { return readToLinefeed(); } RackInput(InputStream inputStream); byte[] gets(); byte[] read(Integer length); void rewind(); @Override void close(); }### Answer: @Test public void getsAtEof() throws Exception { assertThat(empty.gets()).isNull(); } @Test public void gets() throws Exception { assertThat(full.gets()).isEqualTo("Hello,\n".getBytes()); } @Test public void getsWithCrLf() throws Exception { assertThat(rackInputFor("Hello,\r\nWorld!").gets()).isEqualTo("Hello,\r\n".getBytes()); } @Test public void getsAgain() throws Exception { full.gets(); assertThat(full.gets()).isEqualTo("World!".getBytes()); }
### Question: RackLogger { public void debug(String message) { logger.debug(message); } RackLogger(Logger logger); void info(String message); void debug(String message); void warn(String message); void error(String message); void fatal(String message); static final Marker FATAL; }### Answer: @Test public void debug() { subject.debug(MESSAGE); verify(delegate).debug(MESSAGE); }
### Question: RackInput implements Closeable { public void rewind() throws IOException { stream.reset(); buffer.reset(); bufferReadHead = 0; } RackInput(InputStream inputStream); byte[] gets(); byte[] read(Integer length); void rewind(); @Override void close(); }### Answer: @Test public void rewind() throws Exception { full.read(4); full.rewind(); assertThat(full.read(4)).isEqualTo(copyOfRange(BYTES, 0, 4)); }
### Question: RackLogger { public void warn(String message) { logger.warn(message); } RackLogger(Logger logger); void info(String message); void debug(String message); void warn(String message); void error(String message); void fatal(String message); static final Marker FATAL; }### Answer: @Test public void warn() { subject.warn(MESSAGE); verify(delegate).warn(MESSAGE); }
### Question: RackLogger { public void error(String message) { logger.error(message); } RackLogger(Logger logger); void info(String message); void debug(String message); void warn(String message); void error(String message); void fatal(String message); static final Marker FATAL; }### Answer: @Test public void error() { subject.error(MESSAGE); verify(delegate).error(MESSAGE); }
### Question: RackLogger { public void fatal(String message) { logger.error(FATAL, message); } RackLogger(Logger logger); void info(String message); void debug(String message); void warn(String message); void error(String message); void fatal(String message); static final Marker FATAL; }### Answer: @Test public void fatal() { subject.fatal(MESSAGE); verify(delegate).error(FATAL, MESSAGE); }
### Question: RackErrors { public void puts(String message) { logger.error(message); } RackErrors(Logger logger); void puts(String message); void write(String message); void flush(); }### Answer: @Test public void puts() { rackErrors.puts("Boom!"); verify(logger).error("Boom!"); }
### Question: RackErrors { public void write(String message) { buffer.append(message); } RackErrors(Logger logger); void puts(String message); void write(String message); void flush(); }### Answer: @Test public void write() { rackErrors.write("Boom?"); verify(logger, never()).error(anyString()); }
### Question: RackErrors { public void flush() { if (buffer.length() > 0) { logger.error(buffer.toString()); buffer.setLength(0); } } RackErrors(Logger logger); void puts(String message); void write(String message); void flush(); }### Answer: @Test public void flushOnEmpty() { rackErrors.flush(); verify(logger, never()).error(anyString()); }
### Question: CleanExpiredCQSubCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { boolean result = false; defaultMQAdminExt.start(); if (commandLine.hasOption('b')) { String addr = commandLine.getOptionValue('b').trim(); result = defaultMQAdminExt.cleanExpiredConsumerQueueByAddr(addr); } else { String cluster = commandLine.getOptionValue('c'); if (null != cluster) cluster = cluster.trim(); result = defaultMQAdminExt.cleanExpiredConsumerQueue(cluster); } System.out.printf(result ? "success" : "false"); } catch (Exception e) { e.printStackTrace(); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer: @Test public void testExecute() { CleanExpiredCQSubCommand cmd = new CleanExpiredCQSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); }
### Question: CleanUnusedTopicCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { boolean result = false; defaultMQAdminExt.start(); if (commandLine.hasOption('b')) { String addr = commandLine.getOptionValue('b').trim(); result = defaultMQAdminExt.cleanUnusedTopicByAddr(addr); } else { String cluster = commandLine.getOptionValue('c'); if (null != cluster) cluster = cluster.trim(); result = defaultMQAdminExt.cleanUnusedTopicByAddr(cluster); } System.out.printf(result ? "success" : "false"); } catch (Exception e) { e.printStackTrace(); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer: @Test public void testExecute() { CleanUnusedTopicCommand cmd = new CleanUnusedTopicCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); }
### Question: BrokerStatusSubCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); String brokerAddr = commandLine.hasOption('b') ? commandLine.getOptionValue('b').trim() : null; String clusterName = commandLine.hasOption('c') ? commandLine.getOptionValue('c').trim() : null; if (brokerAddr != null) { printBrokerRuntimeStats(defaultMQAdminExt, brokerAddr, false); } else if (clusterName != null) { Set<String> masterSet = CommandUtil.fetchMasterAndSlaveAddrByClusterName(defaultMQAdminExt, clusterName); for (String ba : masterSet) { try { printBrokerRuntimeStats(defaultMQAdminExt, ba, true); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); void printBrokerRuntimeStats(final DefaultMQAdminExt defaultMQAdminExt, final String brokerAddr, final boolean printBroker); }### Answer: @Test public void testExecute() { BrokerStatusSubCommand cmd = new BrokerStatusSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); }
### Question: SendMsgStatusCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) { final DefaultMQProducer producer = new DefaultMQProducer("PID_SMSC", rpcHook); producer.setInstanceName("PID_SMSC_" + System.currentTimeMillis()); try { producer.start(); String brokerName = commandLine.getOptionValue('b').trim(); int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128; int count = commandLine.hasOption('c') ? Integer.parseInt(commandLine.getOptionValue('c')) : 50; producer.send(buildMessage(brokerName, 16)); for (int i = 0; i < count; i++) { long begin = System.currentTimeMillis(); SendResult result = producer.send(buildMessage(brokerName, messageSize)); System.out.printf("rt:" + (System.currentTimeMillis() - begin) + "ms, SendResult=" + result); } } catch (Exception e) { e.printStackTrace(); } finally { producer.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer: @Test public void testExecute() { SendMsgStatusCommand cmd = new SendMsgStatusCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-s 1024 -c 10"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); }
### Question: GetNamesrvConfigCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, final RPCHook rpcHook) { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { String servers = commandLine.getOptionValue('n'); List<String> serverList = null; if (servers != null && servers.length() > 0) { String[] serverArray = servers.trim().split(";"); if (serverArray.length > 0) { serverList = Arrays.asList(serverArray); } } defaultMQAdminExt.start(); Map<String, Properties> nameServerConfigs = defaultMQAdminExt.getNameServerConfig(serverList); for (String server : nameServerConfigs.keySet()) { System.out.printf("============%s============\n", server); for (Object key : nameServerConfigs.get(server).keySet()) { System.out.printf("%-50s= %s\n", key, nameServerConfigs.get(server).get(key)); } } } catch (Exception e) { e.printStackTrace(); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(final Options options); @Override void execute(final CommandLine commandLine, final Options options, final RPCHook rpcHook); }### Answer: @Test public void testExecute() { GetNamesrvConfigCommand cmd = new GetNamesrvConfigCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); }
### Question: WipeWritePermSubCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); String brokerName = commandLine.getOptionValue('b').trim(); List<String> namesrvList = defaultMQAdminExt.getNameServerAddressList(); if (namesrvList != null) { for (String namesrvAddr : namesrvList) { try { int wipeTopicCount = defaultMQAdminExt.wipeWritePermOfBroker(namesrvAddr, brokerName); System.out.printf("wipe write perm of broker[%s] in name server[%s] OK, %d%n", brokerName, namesrvAddr, wipeTopicCount ); } catch (Exception e) { System.out.printf("wipe write perm of broker[%s] in name server[%s] Failed%n", brokerName, namesrvAddr ); e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer: @Test public void testExecute() { WipeWritePermSubCommand cmd = new WipeWritePermSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b default-broker"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); }
### Question: TopicRouteSubCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); String topic = commandLine.getOptionValue('t').trim(); TopicRouteData topicRouteData = defaultMQAdminExt.examineTopicRouteInfo(topic); String json = topicRouteData.toJson(true); System.out.printf("%s%n", json); } catch (Exception e) { e.printStackTrace(); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook); }### Answer: @Test public void testExecute() { TopicRouteSubCommand cmd = new TopicRouteSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-t unit-test"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test"); }
### Question: DeleteTopicSubCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) { DefaultMQAdminExt adminExt = new DefaultMQAdminExt(rpcHook); adminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { String topic = commandLine.getOptionValue('t').trim(); if (commandLine.hasOption('c')) { String clusterName = commandLine.getOptionValue('c').trim(); adminExt.start(); deleteTopic(adminExt, clusterName, topic); return; } ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options); } catch (Exception e) { e.printStackTrace(); } finally { adminExt.shutdown(); } } static void deleteTopic(final DefaultMQAdminExt adminExt, final String clusterName, final String topic ); @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer: @Test public void testExecute() { DeleteTopicSubCommand cmd = new DeleteTopicSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-t unit-test", "-c default-cluster"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test"); assertThat(commandLine.getOptionValue("c").trim()).isEqualTo("default-cluster"); }
### Question: TopicClusterSubCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); String topic = commandLine.getOptionValue('t').trim(); try { defaultMQAdminExt.start(); Set<String> clusters = defaultMQAdminExt.getTopicClusterList(topic); for (String value : clusters) { System.out.printf("%s%n", value); } } catch (Exception e) { e.printStackTrace(); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook); }### Answer: @Test public void testExecute() { TopicClusterSubCommand cmd = new TopicClusterSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-t unit-test"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test"); }