method2testcases
stringlengths
118
6.63k
### 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: INodeFile extends INode implements BlockCollection { public static INodeFile valueOf(INode inode, String path) throws IOException { if (inode == null) { throw new FileNotFoundException("File does not exist: " + path); } if (!(inode instanceof INodeFile)) { throw new FileNotFoundException("Path is not a file: " + path); } return (INodeFile)inode; } 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 testValueOf () throws IOException { final String path = "/testValueOf"; final PermissionStatus perm = new PermissionStatus( userName, null, FsPermission.getDefault()); final short replication = 3; { final INode from = null; try { INodeFile.valueOf(from, path); fail(); } catch(FileNotFoundException fnfe) { assertTrue(fnfe.getMessage().contains("File does not exist")); } try { INodeFileUnderConstruction.valueOf(from, path); fail(); } catch(FileNotFoundException fnfe) { assertTrue(fnfe.getMessage().contains("File does not exist")); } } { final INode from = new INodeFile( perm, null, replication, 0L, 0L, preferredBlockSize); final INodeFile f = INodeFile.valueOf(from, path); assertTrue(f == from); try { INodeFileUnderConstruction.valueOf(from, path); fail(); } catch(IOException ioe) { assertTrue(ioe.getMessage().contains("File is not under construction")); } } { final INode from = new INodeFileUnderConstruction( perm, replication, 0L, 0L, "client", "machine", null); final INodeFile f = INodeFile.valueOf(from, path); assertTrue(f == from); final INodeFileUnderConstruction u = INodeFileUnderConstruction.valueOf( from, path); assertTrue(u == from); } { final INode from = new INodeDirectory(perm, 0L); try { INodeFile.valueOf(from, path); fail(); } catch(FileNotFoundException fnfe) { assertTrue(fnfe.getMessage().contains("Path is not a file")); } try { INodeFileUnderConstruction.valueOf(from, path); fail(); } catch(FileNotFoundException fnfe) { assertTrue(fnfe.getMessage().contains("Path is not a file")); } } }
### 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: NameNodeResourceChecker { @VisibleForTesting Collection<String> getVolumesLowOnSpace() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Going to check the following volumes disk space: " + volumes); } Collection<String> lowVolumes = new ArrayList<String>(); for (CheckedVolume volume : volumes.values()) { lowVolumes.add(volume.getVolume()); } return lowVolumes; } NameNodeResourceChecker(Configuration conf); boolean hasAvailableDiskSpace(); }### Answer: @Test public void testChecking2NameDirsOnOneVolume() throws IOException { Configuration conf = new Configuration(); File nameDir1 = new File(System.getProperty("test.build.data"), "name-dir1"); File nameDir2 = new File(System.getProperty("test.build.data"), "name-dir2"); nameDir1.mkdirs(); nameDir2.mkdirs(); conf.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY, nameDir1.getAbsolutePath() + "," + nameDir2.getAbsolutePath()); conf.setLong(DFSConfigKeys.DFS_NAMENODE_DU_RESERVED_KEY, Long.MAX_VALUE); NameNodeResourceChecker nb = new NameNodeResourceChecker(conf); assertEquals("Should not check the same volume more than once.", 1, nb.getVolumesLowOnSpace().size()); } @Test public void testCheckingExtraVolumes() throws IOException { Configuration conf = new Configuration(); File nameDir = new File(System.getProperty("test.build.data"), "name-dir"); nameDir.mkdirs(); conf.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY, nameDir.getAbsolutePath()); conf.set(DFSConfigKeys.DFS_NAMENODE_CHECKED_VOLUMES_KEY, nameDir.getAbsolutePath()); conf.setLong(DFSConfigKeys.DFS_NAMENODE_DU_RESERVED_KEY, Long.MAX_VALUE); NameNodeResourceChecker nb = new NameNodeResourceChecker(conf); assertEquals("Should not check the same volume more than once.", 1, nb.getVolumesLowOnSpace().size()); }
### 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: StreamFile extends DfsServlet { static void sendPartialData(FSInputStream in, OutputStream out, HttpServletResponse response, long contentLength, List<InclusiveByteRange> ranges) throws IOException { if (ranges == null || ranges.size() != 1) { response.setContentLength(0); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); response.setHeader("Content-Range", InclusiveByteRange.to416HeaderRangeString(contentLength)); } else { InclusiveByteRange singleSatisfiableRange = ranges.get(0); long singleLength = singleSatisfiableRange.getSize(contentLength); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); response.setHeader("Content-Range", singleSatisfiableRange.toHeaderRangeString(contentLength)); copyFromOffset(in, out, singleSatisfiableRange.getFirst(contentLength), singleLength); } } @Override @SuppressWarnings("unchecked") void doGet(HttpServletRequest request, HttpServletResponse response); static final String CONTENT_LENGTH; }### Answer: @Test public void testSendPartialData() throws IOException { FSInputStream in = new MockFSInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); { List<InclusiveByteRange> ranges = strToRanges("0-,10-300", 500); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); StreamFile.sendPartialData(in, os, response, 500, ranges); Mockito.verify(response).setStatus(416); } { os.reset(); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); StreamFile.sendPartialData(in, os, response, 500, null); Mockito.verify(response).setStatus(416); } { List<InclusiveByteRange> ranges = strToRanges("600-800", 500); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); StreamFile.sendPartialData(in, os, response, 500, ranges); Mockito.verify(response).setStatus(416); } { List<InclusiveByteRange> ranges = strToRanges("100-300", 500); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); StreamFile.sendPartialData(in, os, response, 500, ranges); Mockito.verify(response).setStatus(206); assertArrayEquals("Byte range from 100-300", getOutputArray(100, 201), os.toByteArray()); } }
### Question: StreamFile extends DfsServlet { @Override @SuppressWarnings("unchecked") public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String path = ServletUtil.getDecodedPath(request, "/streamFile"); final String rawPath = ServletUtil.getRawPath(request, "/streamFile"); final String filename = JspHelper.validatePath(path); final String rawFilename = JspHelper.validatePath(rawPath); if (filename == null) { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.print("Invalid input"); return; } Enumeration<String> reqRanges = request.getHeaders("Range"); if (reqRanges != null && !reqRanges.hasMoreElements()) { reqRanges = null; } DFSClient dfs; try { dfs = getDFSClient(request); } catch (InterruptedException e) { response.sendError(400, e.getMessage()); return; } DFSInputStream in = null; OutputStream out = null; try { in = dfs.open(filename); out = response.getOutputStream(); final long fileLen = in.getFileLength(); if (reqRanges != null) { List<InclusiveByteRange> ranges = InclusiveByteRange.satisfiableRanges(reqRanges, fileLen); StreamFile.sendPartialData(in, out, response, fileLen, ranges); } else { response.setHeader("Content-Disposition", "attachment; filename=\"" + rawFilename + "\""); response.setContentType("application/octet-stream"); response.setHeader(CONTENT_LENGTH, "" + fileLen); StreamFile.copyFromOffset(in, out, 0L, fileLen); } in.close(); in = null; out.close(); out = null; dfs.close(); dfs = null; } catch (IOException ioe) { if (LOG.isDebugEnabled()) { LOG.debug("response.isCommitted()=" + response.isCommitted(), ioe); } throw ioe; } finally { IOUtils.cleanup(LOG, in); IOUtils.cleanup(LOG, out); IOUtils.cleanup(LOG, dfs); } } @Override @SuppressWarnings("unchecked") void doGet(HttpServletRequest request, HttpServletResponse response); static final String CONTENT_LENGTH; }### Answer: @Test public void testDoGetShouldWriteTheFileContentIntoServletOutputStream() throws Exception { MiniDFSCluster cluster = new MiniDFSCluster.Builder(CONF).numDataNodes(1) .build(); try { Path testFile = createFile(); setUpForDoGetTest(cluster, testFile); ServletOutputStreamExtn outStream = new ServletOutputStreamExtn(); Mockito.doReturn(outStream).when(mockHttpServletResponse) .getOutputStream(); StreamFile sfile = new StreamFile() { private static final long serialVersionUID = 7715590481809562722L; @Override public ServletContext getServletContext() { return mockServletContext; } }; sfile.doGet(mockHttpServletRequest, mockHttpServletResponse); assertEquals("Not writing the file data into ServletOutputStream", outStream.getResult(), "test"); } finally { cluster.shutdown(); } } @Test public void testDoGetShouldCloseTheDFSInputStreamIfResponseGetOutPutStreamThrowsAnyException() throws Exception { MiniDFSCluster cluster = new MiniDFSCluster.Builder(CONF).numDataNodes(1) .build(); try { Path testFile = createFile(); setUpForDoGetTest(cluster, testFile); Mockito.doThrow(new IOException()).when(mockHttpServletResponse) .getOutputStream(); DFSInputStream fsMock = Mockito.mock(DFSInputStream.class); Mockito.doReturn(fsMock).when(clientMock).open(testFile.toString()); Mockito.doReturn(Long.valueOf(4)).when(fsMock).getFileLength(); try { sfile.doGet(mockHttpServletRequest, mockHttpServletResponse); fail("Not throwing the IOException"); } catch (IOException e) { Mockito.verify(clientMock, Mockito.atLeastOnce()).close(); } } finally { cluster.shutdown(); } }
### Question: FileJournalManager implements JournalManager { @Override synchronized public void finalizeLogSegment(long firstTxId, long lastTxId) throws IOException { File inprogressFile = NNStorage.getInProgressEditsFile(sd, firstTxId); File dstFile = NNStorage.getFinalizedEditsFile( sd, firstTxId, lastTxId); LOG.info("Finalizing edits file " + inprogressFile + " -> " + dstFile); Preconditions.checkState(!dstFile.exists(), "Can't finalize edits file " + inprogressFile + " since finalized file " + "already exists"); if (!inprogressFile.renameTo(dstFile)) { errorReporter.reportErrorOnFile(dstFile); throw new IllegalStateException("Unable to finalize edits file " + inprogressFile); } if (inprogressFile.equals(currentInProgress)) { currentInProgress = null; } } 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=IllegalStateException.class) public void testFinalizeErrorReportedToNNStorage() throws IOException, InterruptedException { File f = new File(TestEditLog.TEST_DIR + "/filejournaltestError"); NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 10, new AbortSpec(10, 0)); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); FileJournalManager jm = new FileJournalManager(sd, storage); String sdRootPath = sd.getRoot().getAbsolutePath(); FileUtil.chmod(sdRootPath, "-w", true); try { jm.finalizeLogSegment(0, 1); } finally { assertTrue(storage.getRemovedStorageDirs().contains(sd)); FileUtil.chmod(sdRootPath, "+w", true); } }
### 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: ParseFilter { public static void registerFilter(String name, String filterClass) { if(LOG.isInfoEnabled()) LOG.info("Registering new filter " + name); filterHashMap.put(name, filterClass); } Filter parseFilterString(String filterString); Filter parseFilterString(byte [] filterStringAsByteArray); byte [] extractFilterSimpleExpression(byte [] filterStringAsByteArray, int filterExpressionStartOffset); Filter parseSimpleFilterExpression(byte [] filterStringAsByteArray); static byte [] getFilterName(byte [] filterStringAsByteArray); static ArrayList<byte []> getFilterArguments(byte [] filterStringAsByteArray); void reduce(Stack<ByteBuffer> operatorStack, Stack<Filter> filterStack, ByteBuffer operator); static Filter popArguments(Stack<ByteBuffer> operatorStack, Stack <Filter> filterStack); boolean hasHigherPriority(ByteBuffer a, ByteBuffer b); static byte [] createUnescapdArgument(byte [] filterStringAsByteArray, int argumentStartIndex, int argumentEndIndex); static boolean checkForOr(byte [] filterStringAsByteArray, int indexOfOr); static boolean checkForAnd(byte [] filterStringAsByteArray, int indexOfAnd); static boolean checkForSkip(byte [] filterStringAsByteArray, int indexOfSkip); static boolean checkForWhile(byte [] filterStringAsByteArray, int indexOfWhile); static boolean isQuoteUnescaped(byte [] array, int quoteIndex); static byte [] removeQuotesFromByteArray(byte [] quotedByteArray); static int convertByteArrayToInt(byte [] numberAsByteArray); static long convertByteArrayToLong(byte [] numberAsByteArray); static boolean convertByteArrayToBoolean(byte [] booleanAsByteArray); static CompareFilter.CompareOp createCompareOp(byte [] compareOpAsByteArray); static WritableByteArrayComparable createComparator(byte [] comparator); static byte [][] parseComparator(byte [] comparator); Set<String> getSupportedFilters(); static Map<String, String> getAllFilters(); static void registerFilter(String name, String filterClass); }### Answer: @Test public void testRegisterFilter() { ParseFilter.registerFilter("MyFilter", "some.class"); assertTrue(f.getSupportedFilters().contains("MyFilter")); }
### 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: ColumnRangeFilter extends FilterBase { @Override public String toString() { return this.getClass().getSimpleName() + " " + (this.minColumnInclusive ? "[" : "(") + Bytes.toStringBinary(this.minColumn) + ", " + Bytes.toStringBinary(this.maxColumn) + (this.maxColumnInclusive ? "]" : ")"); } ColumnRangeFilter(); ColumnRangeFilter(final byte[] minColumn, boolean minColumnInclusive, final byte[] maxColumn, boolean maxColumnInclusive); boolean isMinColumnInclusive(); boolean isMaxColumnInclusive(); byte[] getMinColumn(); boolean getMinColumnInclusive(); byte[] getMaxColumn(); boolean getMaxColumnInclusive(); @Override ReturnCode filterKeyValue(KeyValue kv); static Filter createFilterFromArguments(ArrayList<byte []> filterArguments); @Override void write(DataOutput out); @Override void readFields(DataInput in); @Override KeyValue getNextKeyHint(KeyValue kv); @Override String toString(); }### Answer: @Test public void TestColumnRangeFilterClient() throws Exception { String family = "Family"; String table = "TestColumnRangeFilterClient"; HTable ht = TEST_UTIL.createTable(Bytes.toBytes(table), Bytes.toBytes(family), Integer.MAX_VALUE); List<String> rows = generateRandomWords(10, 8); long maxTimestamp = 2; List<String> columns = generateRandomWords(20000, 8); List<KeyValue> kvList = new ArrayList<KeyValue>(); Map<StringRange, List<KeyValue>> rangeMap = new HashMap<StringRange, List<KeyValue>>(); rangeMap.put(new StringRange(null, true, "b", false), new ArrayList<KeyValue>()); rangeMap.put(new StringRange("p", true, "q", false), new ArrayList<KeyValue>()); rangeMap.put(new StringRange("r", false, "s", true), new ArrayList<KeyValue>()); rangeMap.put(new StringRange("z", false, null, false), new ArrayList<KeyValue>()); String valueString = "ValueString"; for (String row : rows) { Put p = new Put(Bytes.toBytes(row)); p.setWriteToWAL(false); for (String column : columns) { for (long timestamp = 1; timestamp <= maxTimestamp; timestamp++) { KeyValue kv = KeyValueTestUtil.create(row, family, column, timestamp, valueString); p.add(kv); kvList.add(kv); for (StringRange s : rangeMap.keySet()) { if (s.inRange(column)) { rangeMap.get(s).add(kv); } } } } ht.put(p); } TEST_UTIL.flush(); ColumnRangeFilter filter; Scan scan = new Scan(); scan.setMaxVersions(); for (StringRange s : rangeMap.keySet()) { filter = new ColumnRangeFilter(s.getStart() == null ? null : Bytes.toBytes(s.getStart()), s.isStartInclusive(), s.getEnd() == null ? null : Bytes.toBytes(s.getEnd()), s.isEndInclusive()); scan.setFilter(filter); ResultScanner scanner = ht.getScanner(scan); List<KeyValue> results = new ArrayList<KeyValue>(); LOG.info("scan column range: " + s.toString()); long timeBeforeScan = System.currentTimeMillis(); Result result; while ((result = scanner.next()) != null) { for (KeyValue kv : result.list()) { results.add(kv); } } long scanTime = System.currentTimeMillis() - timeBeforeScan; scanner.close(); LOG.info("scan time = " + scanTime + "ms"); LOG.info("found " + results.size() + " results"); LOG.info("Expecting " + rangeMap.get(s).size() + " results"); assertEquals(rangeMap.get(s).size(), results.size()); } ht.close(); }
### 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: BlockReaderLocalLegacy implements BlockReader { @Override public synchronized int read(ByteBuffer buf) throws IOException { int nRead = 0; if (verifyChecksum) { if (slowReadBuff.hasRemaining()) { int fromSlowReadBuff = Math.min(buf.remaining(), slowReadBuff.remaining()); writeSlice(slowReadBuff, buf, fromSlowReadBuff); nRead += fromSlowReadBuff; } if (buf.remaining() >= bytesPerChecksum && offsetFromChunkBoundary == 0) { int len = buf.remaining() - (buf.remaining() % bytesPerChecksum); len = Math.min(len, slowReadBuff.capacity()); int oldlimit = buf.limit(); buf.limit(buf.position() + len); int readResult = 0; try { readResult = doByteBufferRead(buf); } finally { buf.limit(oldlimit); } if (readResult == -1) { return nRead; } else { nRead += readResult; buf.position(buf.position() + readResult); } } if ((buf.remaining() > 0 && buf.remaining() < bytesPerChecksum) || offsetFromChunkBoundary > 0) { int toRead = Math.min(buf.remaining(), bytesPerChecksum - offsetFromChunkBoundary); int readResult = fillSlowReadBuffer(toRead); if (readResult == -1) { return nRead; } else { int fromSlowReadBuff = Math.min(readResult, buf.remaining()); writeSlice(slowReadBuff, buf, fromSlowReadBuff); nRead += fromSlowReadBuff; } } } else { nRead = doByteBufferRead(buf); if (nRead > 0) { buf.position(buf.position() + nRead); } } return nRead; } private BlockReaderLocalLegacy(Configuration conf, String hdfsfile, ExtendedBlock block, Token<BlockTokenIdentifier> token, long startOffset, long length, BlockLocalPathInfo pathinfo, FileInputStream dataIn); private BlockReaderLocalLegacy(Configuration conf, String hdfsfile, ExtendedBlock block, Token<BlockTokenIdentifier> token, long startOffset, long length, BlockLocalPathInfo pathinfo, DataChecksum checksum, boolean verifyChecksum, FileInputStream dataIn, long firstChunkOffset, FileInputStream checksumIn); @Override synchronized int read(ByteBuffer buf); @Override synchronized int read(byte[] buf, int off, int len); @Override synchronized long skip(long n); @Override synchronized void close(); @Override int readAll(byte[] buf, int offset, int len); @Override void readFully(byte[] buf, int off, int len); @Override int available(); @Override boolean isLocal(); @Override boolean isShortCircuit(); }### Answer: @Test public void testStablePositionAfterCorruptRead() throws Exception { final short REPL_FACTOR = 1; final long FILE_LENGTH = 512L; HdfsConfiguration conf = getConfiguration(null); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); FileSystem fs = cluster.getFileSystem(); Path path = new Path("/corrupted"); DFSTestUtil.createFile(fs, path, FILE_LENGTH, REPL_FACTOR, 12345L); DFSTestUtil.waitReplication(fs, path, REPL_FACTOR); ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, path); int blockFilesCorrupted = cluster.corruptBlockOnDataNodes(block); assertEquals("All replicas not corrupted", REPL_FACTOR, blockFilesCorrupted); FSDataInputStream dis = cluster.getFileSystem().open(path); ByteBuffer buf = ByteBuffer.allocateDirect((int)FILE_LENGTH); boolean sawException = false; try { dis.read(buf); } catch (ChecksumException ex) { sawException = true; } assertTrue(sawException); assertEquals(0, buf.position()); assertEquals(buf.capacity(), buf.limit()); dis = cluster.getFileSystem().open(path); buf.position(3); buf.limit(25); sawException = false; try { dis.read(buf); } catch (ChecksumException ex) { sawException = true; } assertTrue(sawException); assertEquals(3, buf.position()); assertEquals(25, buf.limit()); cluster.shutdown(); }
### Question: ColumnPrefixFilter extends FilterBase { public ColumnPrefixFilter() { super(); } ColumnPrefixFilter(); ColumnPrefixFilter(final byte [] prefix); byte[] getPrefix(); @Override ReturnCode filterKeyValue(KeyValue kv); ReturnCode filterColumn(byte[] buffer, int qualifierOffset, int qualifierLength); static Filter createFilterFromArguments(ArrayList<byte []> filterArguments); void write(DataOutput out); void readFields(DataInput in); KeyValue getNextKeyHint(KeyValue kv); @Override String toString(); }### Answer: @Test public void testColumnPrefixFilter() throws IOException { String family = "Family"; HTableDescriptor htd = new HTableDescriptor("TestColumnPrefixFilter"); 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 { List<String> rows = generateRandomWords(100, "row"); List<String> columns = generateRandomWords(10000, "column"); long maxTimestamp = 2; List<KeyValue> kvList = new ArrayList<KeyValue>(); Map<String, List<KeyValue>> prefixMap = new HashMap<String, List<KeyValue>>(); prefixMap.put("p", new ArrayList<KeyValue>()); prefixMap.put("s", new ArrayList<KeyValue>()); String valueString = "ValueString"; for (String row: rows) { Put p = new Put(Bytes.toBytes(row)); p.setWriteToWAL(false); for (String column: columns) { for (long timestamp = 1; timestamp <= maxTimestamp; timestamp++) { KeyValue kv = KeyValueTestUtil.create(row, family, column, timestamp, valueString); p.add(kv); kvList.add(kv); for (String s: prefixMap.keySet()) { if (column.startsWith(s)) { prefixMap.get(s).add(kv); } } } } region.put(p); } ColumnPrefixFilter filter; Scan scan = new Scan(); scan.setMaxVersions(); for (String s: prefixMap.keySet()) { filter = new ColumnPrefixFilter(Bytes.toBytes(s)); scan.setFilter(filter); InternalScanner scanner = region.getScanner(scan); List<KeyValue> results = new ArrayList<KeyValue>(); while(scanner.next(results)); assertEquals(prefixMap.get(s).size(), results.size()); } } finally { region.close(); region.getLog().closeAndDelete(); } region.close(); region.getLog().closeAndDelete(); }
### Question: MultipleColumnPrefixFilter extends FilterBase { public MultipleColumnPrefixFilter() { super(); } MultipleColumnPrefixFilter(); MultipleColumnPrefixFilter(final byte [][] prefixes); byte [][] getPrefix(); @Override ReturnCode filterKeyValue(KeyValue kv); ReturnCode filterColumn(byte[] buffer, int qualifierOffset, int qualifierLength); static Filter createFilterFromArguments(ArrayList<byte []> filterArguments); void write(DataOutput out); void readFields(DataInput in); KeyValue getNextKeyHint(KeyValue kv); TreeSet<byte []> createTreeSet(); @Override String toString(); }### Answer: @Test public void testMultipleColumnPrefixFilter() throws IOException { String family = "Family"; HTableDescriptor htd = new HTableDescriptor("TestMultipleColumnPrefixFilter"); 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); List<String> rows = generateRandomWords(100, "row"); List<String> columns = generateRandomWords(10000, "column"); long maxTimestamp = 2; List<KeyValue> kvList = new ArrayList<KeyValue>(); Map<String, List<KeyValue>> prefixMap = new HashMap<String, List<KeyValue>>(); prefixMap.put("p", new ArrayList<KeyValue>()); prefixMap.put("q", new ArrayList<KeyValue>()); prefixMap.put("s", new ArrayList<KeyValue>()); String valueString = "ValueString"; for (String row: rows) { Put p = new Put(Bytes.toBytes(row)); p.setWriteToWAL(false); for (String column: columns) { for (long timestamp = 1; timestamp <= maxTimestamp; timestamp++) { KeyValue kv = KeyValueTestUtil.create(row, family, column, timestamp, valueString); p.add(kv); kvList.add(kv); for (String s: prefixMap.keySet()) { if (column.startsWith(s)) { prefixMap.get(s).add(kv); } } } } region.put(p); } MultipleColumnPrefixFilter filter; Scan scan = new Scan(); scan.setMaxVersions(); byte [][] filter_prefix = new byte [2][]; filter_prefix[0] = new byte [] {'p'}; filter_prefix[1] = new byte [] {'q'}; filter = new MultipleColumnPrefixFilter(filter_prefix); scan.setFilter(filter); List<KeyValue> results = new ArrayList<KeyValue>(); InternalScanner scanner = region.getScanner(scan); while(scanner.next(results)); assertEquals(prefixMap.get("p").size() + prefixMap.get("q").size(), results.size()); region.close(); region.getLog().closeAndDelete(); }
### Question: LocalHBaseCluster { public LocalHBaseCluster(final Configuration conf) throws IOException { this(conf, DEFAULT_NO); } LocalHBaseCluster(final Configuration conf); LocalHBaseCluster(final Configuration conf, final int noRegionServers); LocalHBaseCluster(final Configuration conf, final int noMasters, final int noRegionServers); @SuppressWarnings("unchecked") LocalHBaseCluster(final Configuration conf, final int noMasters, final int noRegionServers, final Class<? extends HMaster> masterClass, final Class<? extends HRegionServer> regionServerClass); JVMClusterUtil.RegionServerThread addRegionServer(); JVMClusterUtil.RegionServerThread addRegionServer( Configuration config, final int index); JVMClusterUtil.RegionServerThread addRegionServer( final Configuration config, final int index, User user); JVMClusterUtil.MasterThread addMaster(); JVMClusterUtil.MasterThread addMaster(Configuration c, final int index); JVMClusterUtil.MasterThread addMaster( final Configuration c, final int index, User user); HRegionServer getRegionServer(int serverNumber); List<JVMClusterUtil.RegionServerThread> getRegionServers(); List<JVMClusterUtil.RegionServerThread> getLiveRegionServers(); String waitOnRegionServer(int serverNumber); String waitOnRegionServer(JVMClusterUtil.RegionServerThread rst); HMaster getMaster(int serverNumber); HMaster getActiveMaster(); List<JVMClusterUtil.MasterThread> getMasters(); List<JVMClusterUtil.MasterThread> getLiveMasters(); String waitOnMaster(int serverNumber); String waitOnMaster(JVMClusterUtil.MasterThread masterThread); void join(); void startup(); void shutdown(); static boolean isLocal(final Configuration c); static void main(String[] args); static final String LOCAL; static final String LOCAL_COLON; }### Answer: @Test public void testLocalHBaseCluster() throws Exception { Configuration conf = TEST_UTIL.getConfiguration(); conf.set(HConstants.HBASE_DIR, TEST_UTIL.getDataTestDir("hbase.rootdir"). makeQualified(TEST_UTIL.getTestFileSystem().getUri(), TEST_UTIL.getTestFileSystem().getWorkingDirectory()).toString()); MiniZooKeeperCluster zkCluster = TEST_UTIL.startMiniZKCluster(); conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, Integer.toString(zkCluster.getClientPort())); LocalHBaseCluster cluster = new LocalHBaseCluster(conf, 1, 1, MyHMaster.class, MyHRegionServer.class); try { ((MyHMaster)cluster.getMaster(0)).setZKCluster(zkCluster); } catch (ClassCastException e) { fail("Could not cast master to our class"); } try { ((MyHRegionServer)cluster.getRegionServer(0)).echo(42); } catch (ClassCastException e) { fail("Could not cast regionserver to our class"); } try { cluster.startup(); waitForClusterUp(conf); } catch (IOException e) { fail("LocalHBaseCluster did not start successfully"); } finally { cluster.shutdown(); } } @Test public void testLocalHBaseCluster() throws Exception { TEST_UTIL.startMiniCluster(1, 1, null, MyHMaster.class, MyHRegionServer.class); try { int val = ((MyHMaster)TEST_UTIL.getHBaseCluster().getMaster(0)).echo(42); assertEquals(42, val); } catch (ClassCastException e) { fail("Could not cast master to our class"); } try { int val = ((MyHRegionServer)TEST_UTIL.getHBaseCluster().getRegionServer(0)).echo(42); assertEquals(42, val); } catch (ClassCastException e) { fail("Could not cast regionserver to our class"); } TEST_UTIL.shutdownMiniCluster(); }
### 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: FileSystemAccessService extends BaseService implements FileSystemAccess { protected FileSystem createFileSystem(Configuration namenodeConf) throws IOException { String user = UserGroupInformation.getCurrentUser().getShortUserName(); CachedFileSystem newCachedFS = new CachedFileSystem(purgeTimeout); CachedFileSystem cachedFS = fsCache.putIfAbsent(user, newCachedFS); if (cachedFS == null) { cachedFS = newCachedFS; } Configuration conf = new Configuration(namenodeConf); conf.set(HTTPFS_FS_USER, user); return cachedFS.getFileSytem(conf); } FileSystemAccessService(); @Override void postInit(); @Override Class getInterface(); @Override Class[] getServiceDependencies(); @Override T execute(String user, final Configuration conf, final FileSystemExecutor<T> executor); FileSystem createFileSystemInternal(String user, final Configuration conf); @Override FileSystem createFileSystem(String user, final Configuration conf); @Override void releaseFileSystem(FileSystem fs); @Override Configuration getFileSystemConfiguration(); static final String PREFIX; static final String AUTHENTICATION_TYPE; static final String KERBEROS_KEYTAB; static final String KERBEROS_PRINCIPAL; static final String FS_CACHE_PURGE_FREQUENCY; static final String FS_CACHE_PURGE_TIMEOUT; static final String NAME_NODE_WHITELIST; static final String HADOOP_CONF_DIR; }### Answer: @Test @TestDir @TestHdfs public void createFileSystem() throws Exception { String dir = TestDirHelper.getTestDir().getAbsolutePath(); String services = StringUtils.join(",", Arrays.asList(InstrumentationService.class.getName(), SchedulerService.class.getName(), FileSystemAccessService.class.getName())); Configuration hadoopConf = new Configuration(false); hadoopConf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, TestHdfsHelper.getHdfsConf().get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY)); createHadoopConf(hadoopConf); Configuration conf = new Configuration(false); conf.set("server.services", services); conf.set("server.hadoop.filesystem.cache.purge.timeout", "0"); Server server = new Server("server", dir, dir, dir, dir, conf); server.init(); FileSystemAccess hadoop = server.get(FileSystemAccess.class); FileSystem fs = hadoop.createFileSystem("u", hadoop.getFileSystemConfiguration()); Assert.assertNotNull(fs); fs.mkdirs(new Path("/tmp/foo")); hadoop.releaseFileSystem(fs); try { fs.mkdirs(new Path("/tmp/foo")); Assert.fail(); } catch (IOException ex) { } catch (Exception ex) { Assert.fail(); } server.destroy(); }
### 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: LoadIncrementalHFiles extends Configured implements Tool { protected List<LoadQueueItem> splitStoreFile(final LoadQueueItem item, final HTable table, byte[] startKey, byte[] splitKey) throws IOException { final Path hfilePath = item.hfilePath; final Path tmpDir = new Path(item.hfilePath.getParent(), "_tmp"); LOG.info("HFile at " + hfilePath + " no longer fits inside a single " + "region. Splitting..."); String uniqueName = getUniqueName(table.getTableName()); HColumnDescriptor familyDesc = table.getTableDescriptor().getFamily(item.family); Path botOut = new Path(tmpDir, uniqueName + ".bottom"); Path topOut = new Path(tmpDir, uniqueName + ".top"); splitStoreFile(getConf(), hfilePath, familyDesc, splitKey, botOut, topOut); List<LoadQueueItem> lqis = new ArrayList<LoadQueueItem>(2); lqis.add(new LoadQueueItem(item.family, botOut)); lqis.add(new LoadQueueItem(item.family, topOut)); LOG.info("Successfully split into new HFiles " + botOut + " and " + topOut); return lqis; } LoadIncrementalHFiles(Configuration conf, Boolean useSecure); LoadIncrementalHFiles(Configuration conf); void doBulkLoad(Path hfofDir, final HTable table); static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap); @Override int run(String[] args); static void main(String[] args); static String NAME; }### Answer: @Test public void testSplitStoreFile() throws IOException { Path dir = util.getDataTestDir("testSplitHFile"); FileSystem fs = util.getTestFileSystem(); Path testIn = new Path(dir, "testhfile"); HColumnDescriptor familyDesc = new HColumnDescriptor(FAMILY); createHFile(util.getConfiguration(), fs, testIn, FAMILY, QUALIFIER, Bytes.toBytes("aaa"), Bytes.toBytes("zzz"), 1000); Path bottomOut = new Path(dir, "bottom.out"); Path topOut = new Path(dir, "top.out"); LoadIncrementalHFiles.splitStoreFile( util.getConfiguration(), testIn, familyDesc, Bytes.toBytes("ggg"), bottomOut, topOut); int rowCount = verifyHFile(bottomOut); rowCount += verifyHFile(topOut); assertEquals(1000, rowCount); }
### Question: LoadIncrementalHFiles extends Configured implements Tool { public static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap) { ArrayList<byte[]> keysArray = new ArrayList<byte[]>(); int runningValue = 0; byte[] currStartKey = null; boolean firstBoundary = true; for (Map.Entry<byte[], Integer> item: bdryMap.entrySet()) { if (runningValue == 0) currStartKey = item.getKey(); runningValue += item.getValue(); if (runningValue == 0) { if (!firstBoundary) keysArray.add(currStartKey); firstBoundary = false; } } return keysArray.toArray(new byte[0][0]); } LoadIncrementalHFiles(Configuration conf, Boolean useSecure); LoadIncrementalHFiles(Configuration conf); void doBulkLoad(Path hfofDir, final HTable table); static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap); @Override int run(String[] args); static void main(String[] args); static String NAME; }### Answer: @Test public void testInferBoundaries() { TreeMap<byte[], Integer> map = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); String first; String last; first = "a"; last = "e"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "r"; last = "s"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "o"; last = "p"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "g"; last = "k"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "v"; last = "x"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "c"; last = "i"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "m"; last = "q"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "s"; last = "t"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "u"; last = "w"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); byte[][] keysArray = LoadIncrementalHFiles.inferBoundaries(map); byte[][] compare = new byte[3][]; compare[0] = "m".getBytes(); compare[1] = "r".getBytes(); compare[2] = "u".getBytes(); assertEquals(keysArray.length, 3); for (int row = 0; row<keysArray.length; row++){ assertArrayEquals(keysArray[row], compare[row]); } }
### Question: ReaderUtil { public static void process(String path, String sheetName, ZeroCellReader reader) { if (path == null || path.trim().isEmpty()) { throw new IllegalArgumentException("'path' must be given"); } File file = new File(path); if (file.exists() && file.isDirectory()) { throw new IllegalArgumentException("path must not be a directory"); } try (OPCPackage opcPackage = OPCPackage.open(file.getAbsolutePath(), PackageAccess.READ)) { process(opcPackage, sheetName, reader); } catch(InvalidFormatException | EmptyFileException | NotOfficeXmlFileException ife) { throw new ZeroCellException(ERROR_NOT_OPENXML); } catch (IOException ioe) { throw new ZeroCellException("Failed to process file", ioe); } } static void process(String path, String sheetName, ZeroCellReader reader); static void process(File file, String sheetName, ZeroCellReader reader); static void process(InputStream is, String sheetName, ZeroCellReader reader); static final String ERROR_NOT_OPENXML; }### Answer: @Test public void testCanProcessFilePath() { final EntityHandler<Person> entityHandler = new EntityHandler<Person>( Person.class, false, 0, 0 ); ReaderUtil.process( "src/test/resources/test_people.xlsx", entityHandler.getSheetName(), entityHandler.getEntitySheetHandler() ); List<Person> people = entityHandler.readAsList(); assertNotNull(people); assertFalse(people.isEmpty()); assertEquals(5, people.size()); Person zikani = people.get(0); assertEquals(1, zikani.getRowNumber()); assertEquals("Zikani", zikani.getFirstName()); } @Test public void testCanProcessFile() { final EntityHandler<Person> entityHandler = new EntityHandler<Person>( Person.class, false, 0, 0 ); ReaderUtil.process( new File("src/test/resources/test_people.xlsx"), entityHandler.getSheetName(), entityHandler.getEntitySheetHandler() ); List<Person> people = entityHandler.readAsList(); assertNotNull(people); assertFalse(people.isEmpty()); assertEquals(5, people.size()); Person zikani = people.get(0); assertEquals(1, zikani.getRowNumber()); assertEquals("Zikani", zikani.getFirstName()); } @Test public void testFailToProcessFirstSheet() { final EntityHandler<Person> entityHandler = new EntityHandler<Person>( Person.class, false, 0, 0 ); try { ReaderUtil.process( new File("src/test/resources/test_people_with_offset_sheet.xlsx"), EntityHandler.DEFAULT_SHEET, entityHandler.getEntitySheetHandler() ); fail("Somehow read the correct sheet."); } catch(ZeroCellException e) { assertEquals("Expected Column 'ID' but found 'This sheet is the first but not the intended sheet'", e.getMessage()); } } @Test public void testCanProcessInputStream() throws IOException { final EntityHandler<Person> entityHandler = new EntityHandler<Person>( Person.class, false, 0, 0 ); ReaderUtil.process( Files.newInputStream( Paths.get("src", "test", "resources", "test_people.xlsx")), entityHandler.getSheetName(), entityHandler.getEntitySheetHandler() ); List<Person> people = entityHandler.readAsList(); assertNotNull(people); assertFalse(people.isEmpty()); assertEquals(5, people.size()); Person zikani = people.get(0); assertEquals(1, zikani.getRowNumber()); assertEquals("Zikani", zikani.getFirstName()); }
### Question: Reader { public static <T> ReaderBuilder<T> of(Class<T> clazz) { return new ReaderBuilder<>(clazz); } static String[] columnsOf(Class<T> clazz); static ReaderBuilder<T> of(Class<T> clazz); }### Answer: @Test public void testShouldThrowOnDuplicateIndex() { thrown.expect(ZeroCellException.class); thrown.expectMessage("Cannot map two columns to the same index: 0"); Reader.of(DuplicateIndex.class) .from(new File("src/test/resources/test_people.xlsx")) .sheet("uploads") .list(); } @Test public void testShouldThrowOnIncorrectColumnName() { thrown.expect(ZeroCellException.class); thrown.expectMessage("Expected Column 'DOB' but found 'DATE_OF_BIRTH'"); Reader.of(Person2.class) .from(new File("src/test/resources/test_people.xlsx")) .sheet("uploads") .list(); } @Test public void testShouldThrowForNonOpenXMLFile() throws IOException { File file = temporaryFolder.newFile(); thrown.expect(ZeroCellException.class); thrown.expectMessage("Cannot load file. The file must be an Excel 2007+ Workbook (.xlsx)"); Reader.of(Person.class) .from(file) .sheet("uploads") .list(); } @Test public void testShouldExtractPeopleFromFile() { List<Person> people = Reader.of(Person.class) .from(new File("src/test/resources/test_people.xlsx")) .sheet("uploads") .list(); assertNotNull(people); assertFalse(people.isEmpty()); assertEquals(5, people.size()); Person zikani = people.get(0); assertEquals(1, zikani.getRowNumber()); assertEquals("Zikani", zikani.getFirstName()); } @Test public void testShouldSkipFirst3RowsFromFile() { List<Person> people = Reader.of(Person.class) .from(new File("src/test/resources/test_people_with_offset_header.xlsx")) .sheet("uploads") .skipFirstNRows(3) .list(); assertNotNull(people); assertFalse(people.isEmpty()); assertEquals(5, people.size()); Person zikani = people.get(0); assertEquals(1, zikani.getRowNumber()); assertEquals("Zikani", zikani.getFirstName()); } @Test public void testShouldReadFromInputStream() throws IOException { InputStream inputStream = Files.newInputStream( Paths.get("src", "test", "resources", "test_people.xlsx")); List<Person> persons = Reader.of(Person.class) .from(inputStream) .sheet("uploads") .using( new RowNumberInfo("rowNumber", Integer.class), new ColumnInfo("ID", "id", 0, String.class), new ColumnInfo("FIRST_NAME", "firstName", 1, String.class), new ColumnInfo("MIDDLE_NAME", "middleName", 2, String.class), new ColumnInfo("LAST_NAME", "lastName", 3, String.class), new ColumnInfo("DATE_OF_BIRTH", "dateOfBirth", 4, LocalDate.class), new ColumnInfo("FAV_NUMBER", "favouriteNumber", 5, Integer.class), new ColumnInfo("DATE_REGISTERED", "dateOfRegistration", 6, Date.class) ) .list(); assertNotNull(persons); assertSame(5, persons.size()); assertEquals("Mwafulirwa", persons.get(2).getLastName()); assertEquals(1, persons.get(4).getFavouriteNumber()); } @Test public void testShouldThrowOnInvalidSheetName() { thrown.expect(ZeroCellException.class); thrown.expectMessage("Could not find sheet INVALID_SHEET_NAME"); Reader.of(Person.class) .from(new File("src/test/resources/test_people.xlsx")) .sheet("INVALID_SHEET_NAME") .list(); }
### Question: ConverterUtils { public static Object convertValueToType(Class<?> fieldType, String formattedValue, String columnName, int rowNum) { Object value = null; if (fieldType == String.class) { value = String.valueOf(formattedValue); } else if (fieldType == LocalDateTime.class) { return Converters.toLocalDateTime.convert(formattedValue, columnName, rowNum); } else if (fieldType == LocalDate.class) { return Converters.toLocalDate.convert(formattedValue, columnName, rowNum); } else if (fieldType == java.sql.Date.class) { return Converters.toSqlDate.convert(formattedValue, columnName, rowNum); } else if (fieldType == Timestamp.class) { return Converters.toSqlTimestamp.convert(formattedValue, columnName, rowNum); } else if (fieldType == Integer.class || fieldType == int.class) { return Converters.toInteger.convert(formattedValue, columnName, rowNum); } else if (fieldType == Long.class || fieldType == long.class) { return Converters.toLong.convert(formattedValue, columnName, rowNum); } else if (fieldType == Double.class || fieldType == double.class) { return Converters.toDouble.convert(formattedValue, columnName, rowNum); } else if (fieldType == Float.class || fieldType == float.class) { return Converters.toFloat.convert(formattedValue, columnName, rowNum); } else if (fieldType == Boolean.class) { return Converters.toBoolean.convert(formattedValue, columnName, rowNum); } return value; } ConverterUtils(); static Object convertValueToType(Class<?> fieldType, String formattedValue, String columnName, int rowNum); }### Answer: @Test public void testConvertValuesToString() { assertEquals("Hello", convertValueToType(String.class, "Hello", "A", 1)); assertEquals("HELLO", convertValueToType(String.class, "HELLO", "A", 1)); assertEquals("1.0", convertValueToType(String.class, "1.0", "A", 1)); assertEquals("2019-01-01", convertValueToType(String.class, "2019-01-01", "A", 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: NacosServiceDiscovery { public List<ServiceInstance> getInstances(String serviceId) throws NacosException { String group = discoveryProperties.getGroup(); List<Instance> instances = namingService().selectInstances(serviceId, group, true); return hostToServiceInstanceList(instances, serviceId); } 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 testGetInstances() throws NacosException { ArrayList<Instance> instances = new ArrayList<>(); HashMap<String, String> map = new HashMap<>(); map.put("test-key", "test-value"); map.put("secure", "true"); instances.add(serviceInstance(serviceName, true, host, port, map)); 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.selectInstances(eq(serviceName), eq("DEFAULT"), eq(true))) .thenReturn(instances); NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery( nacosDiscoveryProperties, nacosServiceManager); List<ServiceInstance> serviceInstances = serviceDiscovery .getInstances(serviceName); assertThat(serviceInstances.size()).isEqualTo(1); ServiceInstance serviceInstance = serviceInstances.get(0); assertThat(serviceInstance.getServiceId()).isEqualTo(serviceName); assertThat(serviceInstance.getHost()).isEqualTo(host); assertThat(serviceInstance.getPort()).isEqualTo(port); assertThat(serviceInstance.isSecure()).isEqualTo(true); assertThat(serviceInstance.getUri().toString()) .isEqualTo(getUri(serviceInstance)); assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value"); }
### 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: ReactiveSentinelCircuitBreaker implements ReactiveCircuitBreaker { @Override public <T> Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback) { Mono<T> toReturn = toRun.transform(new SentinelReactorTransformer<>( new EntryConfig(resourceName, entryType))); if (fallback != null) { toReturn = toReturn.onErrorResume(fallback); } return toReturn; } ReactiveSentinelCircuitBreaker(String resourceName, EntryType entryType, List<DegradeRule> rules); ReactiveSentinelCircuitBreaker(String resourceName, List<DegradeRule> rules); ReactiveSentinelCircuitBreaker(String resourceName); @Override Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback); @Override Flux<T> run(Flux<T> toRun, Function<Throwable, Flux<T>> fallback); }### Answer: @Test public void testCreateWithNullRule() { String id = "testCreateReactiveCbWithNullRule"; ReactiveSentinelCircuitBreaker cb = new ReactiveSentinelCircuitBreaker(id, Collections.singletonList(null)); assertThat(Mono.just("foobar").transform(it -> cb.run(it)).block()) .isEqualTo("foobar"); assertThat(DegradeRuleManager.hasConfig(id)).isFalse(); } @Test public void runMono() { ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() .create("foo"); assertThat(Mono.just("foobar").transform(it -> cb.run(it)).block()) .isEqualTo("foobar"); } @Test public void runMonoWithFallback() { ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() .create("foo"); assertThat(Mono.error(new RuntimeException("boom")) .transform(it -> cb.run(it, t -> Mono.just("fallback"))).block()) .isEqualTo("fallback"); } @Test public void runFlux() { ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() .create("foo"); assertThat(Flux.just("foobar", "hello world").transform(it -> cb.run(it)) .collectList().block()).isEqualTo(Arrays.asList("foobar", "hello world")); } @Test public void runFluxWithFallback() { ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() .create("foo"); assertThat(Flux.error(new RuntimeException("boom")) .transform(it -> cb.run(it, t -> Flux.just("fallback"))).collectList() .block()).isEqualTo(Arrays.asList("fallback")); }
### Question: SentinelCircuitBreaker implements CircuitBreaker { @Override public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) { Entry entry = null; try { entry = SphU.entry(resourceName, entryType); return toRun.get(); } catch (BlockException ex) { return fallback.apply(ex); } catch (Exception ex) { Tracer.trace(ex); return fallback.apply(ex); } finally { if (entry != null) { entry.exit(); } } } SentinelCircuitBreaker(String resourceName, EntryType entryType, List<DegradeRule> rules); SentinelCircuitBreaker(String resourceName, List<DegradeRule> rules); SentinelCircuitBreaker(String resourceName); @Override T run(Supplier<T> toRun, Function<Throwable, T> fallback); }### Answer: @Test public void testCreateDirectlyThenRun() { CircuitBreaker cb = new SentinelCircuitBreaker( "testSentinelCreateDirectlyThenRunA"); assertThat(cb.run(() -> "Sentinel")).isEqualTo("Sentinel"); assertThat(DegradeRuleManager.hasConfig("testSentinelCreateDirectlyThenRunA")) .isFalse(); CircuitBreaker cb2 = new SentinelCircuitBreaker( "testSentinelCreateDirectlyThenRunB", Collections.singletonList( new DegradeRule("testSentinelCreateDirectlyThenRunB") .setCount(100).setTimeWindow(10))); assertThat(cb2.run(() -> "Sentinel")).isEqualTo("Sentinel"); assertThat(DegradeRuleManager.hasConfig("testSentinelCreateDirectlyThenRunB")) .isTrue(); } @Test public void testCreateWithNullRule() { String id = "testCreateCbWithNullRule"; CircuitBreaker cb = new SentinelCircuitBreaker(id, Collections.singletonList(null)); assertThat(cb.run(() -> "Sentinel")).isEqualTo("Sentinel"); assertThat(DegradeRuleManager.hasConfig(id)).isFalse(); } @Test public void testCreateFromFactoryThenRun() { CircuitBreaker cb = new SentinelCircuitBreakerFactory().create("testSentinelRun"); assertThat(cb.run(() -> "foobar")).isEqualTo("foobar"); } @Test public void testRunWithFallback() { CircuitBreaker cb = new SentinelCircuitBreakerFactory() .create("testSentinelRunWithFallback"); assertThat(cb.<String>run(() -> { throw new RuntimeException("boom"); }, t -> "fallback")).isEqualTo("fallback"); }
### 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: TyrusClientEngine implements ClientEngine { @Override public UpgradeRequest createUpgradeRequest(TimeoutHandler timeoutHandler) { switch (clientEngineState) { case INIT: { ClientEndpointConfig config = (ClientEndpointConfig) endpointWrapper.getEndpointConfig(); this.timeoutHandler = timeoutHandler; clientHandShake = Handshake.createClientHandshake( RequestContext.Builder.create().requestURI(connectToServerUriParam) .secure("wss".equals(connectToServerUriParam.getScheme())).build()); clientHandShake.setExtensions(config.getExtensions()); clientHandShake.setSubProtocols(config.getPreferredSubprotocols()); clientHandShake.prepareRequest(); UpgradeRequest upgradeRequest = clientHandShake.getRequest(); config.getConfigurator().beforeRequest(upgradeRequest.getHeaders()); clientEngineState = TyrusClientEngineState.UPGRADE_REQUEST_CREATED; logUpgradeRequest(upgradeRequest); return upgradeRequest; } case REDIRECT_REQUIRED: { this.timeoutHandler = timeoutHandler; final URI requestUri = redirectLocation; RequestContext requestContext = RequestContext.Builder.create(clientHandShake.getRequest()) .requestURI(requestUri) .secure("wss".equalsIgnoreCase(requestUri.getScheme())).build(); Handshake.updateHostAndOrigin(requestContext); clientEngineState = TyrusClientEngineState.UPGRADE_REQUEST_CREATED; logUpgradeRequest(requestContext); return requestContext; } case AUTH_REQUIRED: { UpgradeRequest upgradeRequest = clientHandShake.getRequest(); if (clientEngineState.getAuthenticator() != null) { if (LOGGER.isLoggable(Level.CONFIG)) { debugContext.appendLogMessage(LOGGER, Level.CONFIG, DebugContext.Type.MESSAGE_OUT, "Using " + "authenticator: ", clientEngineState.getAuthenticator().getClass().getName()); } String authorizationHeader; try { final Credentials credentials = (Credentials) properties.get(ClientProperties.CREDENTIALS); debugContext.appendLogMessage(LOGGER, Level.CONFIG, DebugContext.Type.MESSAGE_OUT, "Using " + "credentials: ", credentials); authorizationHeader = clientEngineState.getAuthenticator() .generateAuthorizationHeader( upgradeRequest.getRequestURI(), clientEngineState.getWwwAuthenticateHeader(), credentials); } catch (AuthenticationException e) { listener.onError(e); return null; } upgradeRequest.getHeaders().put(UpgradeRequest.AUTHORIZATION, Collections.singletonList(authorizationHeader)); } clientEngineState = TyrusClientEngineState.AUTH_UPGRADE_REQUEST_CREATED; logUpgradeRequest(upgradeRequest); return upgradeRequest; } default: redirectUriHistory.clear(); throw new IllegalStateException(); } } TyrusClientEngine(TyrusEndpointWrapper endpointWrapper, ClientHandshakeListener listener, Map<String, Object> properties, URI connectToServerUriParam, DebugContext debugContext); @Override UpgradeRequest createUpgradeRequest(TimeoutHandler timeoutHandler); @Override ClientUpgradeInfo processResponse(final UpgradeResponse upgradeResponse, final Writer writer, final Connection.CloseListener closeListener); @Override void processError(Throwable t); TimeoutHandler getTimeoutHandler(); static final int DEFAULT_INCOMING_BUFFER_SIZE; }### Answer: @Test public void testCallCreateRequestTwice() throws DeploymentException { ClientEngine engine = getClientEngine(Collections.<String, Object>emptyMap()); UpgradeRequest upgradeRequest = engine.createUpgradeRequest(null); assertNotNull("First call must return instance of UpgradeRequest", upgradeRequest); try { engine.createUpgradeRequest(null); fail("Second call of createUpgradeRequest must fail"); } catch (IllegalStateException e) { } }
### 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: TyrusRemoteEndpoint implements javax.websocket.RemoteEndpoint { public void close(CloseReason cr) { LOGGER.fine("Close public void close(CloseReason cr): " + cr); webSocket.close(cr); } private TyrusRemoteEndpoint(TyrusSession session, TyrusWebSocket socket, TyrusEndpointWrapper endpointWrapper); @Override void sendPing(ByteBuffer applicationData); @Override void sendPong(ByteBuffer applicationData); @Override String toString(); @Override void setBatchingAllowed(boolean allowed); @Override boolean getBatchingAllowed(); @Override void flushBatch(); void close(CloseReason cr); }### Answer: @Test public void testGetSendStream() throws IOException { TestRemoteEndpoint tre = new TestRemoteEndpoint(); TyrusSession testSession = createTestSession(tre, endpointWrapper); TyrusRemoteEndpoint.Basic rew = new TyrusRemoteEndpoint.Basic(testSession, tre, endpointWrapper); OutputStream stream = rew.getSendStream(); for (byte b : sentBytes) { stream.write(b); } stream.flush(); stream.write(sentBytes); stream.close(); Assert.assertArrayEquals("Writing byte[] to stream and flushing.", sentBytesComplete, tre.getBytesAndClearBuffer()); } @Test public void testGetSendStreamWriteArrayWhole() throws IOException { TestRemoteEndpoint tre = new TestRemoteEndpoint(); TyrusSession testSession = createTestSession(tre, endpointWrapper); TyrusRemoteEndpoint.Basic rew = new TyrusRemoteEndpoint.Basic(testSession, tre, endpointWrapper); OutputStream stream = rew.getSendStream(); stream.write(sentBytesComplete); Assert.assertEquals(6, tre.getLastSentMessageSize()); stream.close(); Assert.assertEquals(0, tre.getLastSentMessageSize()); Assert.assertArrayEquals("Writing byte[] to stream and flushing.", sentBytesComplete, tre.getBytesAndClearBuffer()); } @Test public void testGetSendStreamWriteArrayPerPartes() throws IOException { TestRemoteEndpoint tre = new TestRemoteEndpoint(); TyrusSession testSession = createTestSession(tre, endpointWrapper); TyrusRemoteEndpoint.Basic rew = new TyrusRemoteEndpoint.Basic(testSession, tre, endpointWrapper); OutputStream stream = rew.getSendStream(); stream.write(sentBytes); Assert.assertEquals(3, tre.getLastSentMessageSize()); stream.write(sentBytes); Assert.assertEquals(3, tre.getLastSentMessageSize()); stream.close(); Assert.assertEquals(0, tre.getLastSentMessageSize()); Assert.assertArrayEquals("Writing byte[] to stream and flushing.", sentBytesComplete, tre.getBytesAndClearBuffer()); }
### Question: TyrusClientEngine implements ClientEngine { @Override public ClientUpgradeInfo processResponse(final UpgradeResponse upgradeResponse, final Writer writer, final Connection.CloseListener closeListener) { if (LOGGER.isLoggable(Level.FINE)) { debugContext.appendLogMessage(LOGGER, Level.FINE, DebugContext.Type.MESSAGE_IN, "Received handshake " + "response: \n" + Utils.stringifyUpgradeResponse(upgradeResponse)); } else { if (logUpgradeMessages) { debugContext.appendStandardOutputMessage(DebugContext.Type.MESSAGE_IN, "Received handshake response: " + "\n" + Utils.stringifyUpgradeResponse(upgradeResponse)); } } if (clientEngineState == TyrusClientEngineState.AUTH_UPGRADE_REQUEST_CREATED || clientEngineState == TyrusClientEngineState.UPGRADE_REQUEST_CREATED) { if (upgradeResponse == null) { throw new IllegalArgumentException(LocalizationMessages.ARGUMENT_NOT_NULL("upgradeResponse")); } switch (upgradeResponse.getStatus()) { case 101: return handleSwitchProtocol(upgradeResponse, writer, closeListener); case 300: case 301: case 302: case 303: case 307: case 308: return handleRedirect(upgradeResponse); case 401: return handleAuth(upgradeResponse); case 503: String retryAfterString = null; final List<String> retryAfterHeader = upgradeResponse.getHeaders() .get(UpgradeResponse.RETRY_AFTER); if (retryAfterHeader != null) { retryAfterString = Utils.getHeaderFromList(retryAfterHeader); } Long delay; if (retryAfterString != null) { try { Date date = Utils.parseHttpDate(retryAfterString); delay = (date.getTime() - System.currentTimeMillis()) / 1000; } catch (ParseException e) { try { delay = Long.parseLong(retryAfterString); } catch (NumberFormatException iae) { delay = null; } } } else { delay = null; } listener.onError(new RetryAfterException( LocalizationMessages.HANDSHAKE_HTTP_RETRY_AFTER_MESSAGE(), delay)); return UPGRADE_INFO_FAILED; default: clientEngineState = TyrusClientEngineState.FAILED; HandshakeException e = new HandshakeException( upgradeResponse.getStatus(), LocalizationMessages.INVALID_RESPONSE_CODE(101, upgradeResponse.getStatus())); listener.onError(e); redirectUriHistory.clear(); return UPGRADE_INFO_FAILED; } } redirectUriHistory.clear(); throw new IllegalStateException(); } TyrusClientEngine(TyrusEndpointWrapper endpointWrapper, ClientHandshakeListener listener, Map<String, Object> properties, URI connectToServerUriParam, DebugContext debugContext); @Override UpgradeRequest createUpgradeRequest(TimeoutHandler timeoutHandler); @Override ClientUpgradeInfo processResponse(final UpgradeResponse upgradeResponse, final Writer writer, final Connection.CloseListener closeListener); @Override void processError(Throwable t); TimeoutHandler getTimeoutHandler(); static final int DEFAULT_INCOMING_BUFFER_SIZE; }### Answer: @Test public void testCallProcessResponseFirst() throws DeploymentException { ClientEngine engine = getClientEngine(Collections.<String, Object>emptyMap()); try { engine.processResponse(getUpgradeResponse(""), null, null); fail("Second call of createUpgradeRequest must fail"); } catch (IllegalStateException e) { } }
### 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: TyrusSession implements Session, DistributedSession { @Override public String getId() { return id; } TyrusSession(WebSocketContainer container, TyrusWebSocket socket, TyrusEndpointWrapper endpointWrapper, String subprotocol, List<Extension> extensions, boolean isSecure, URI requestURI, String queryString, Map<String, String> pathParameters, Principal principal, Map<String, List<String>> requestParameterMap, final ClusterContext clusterContext, String connectionId, final String remoteAddr, DebugContext debugContext); @Override String getProtocolVersion(); @Override String getNegotiatedSubprotocol(); @Override javax.websocket.RemoteEndpoint.Async getAsyncRemote(); @Override javax.websocket.RemoteEndpoint.Basic getBasicRemote(); @Override boolean isOpen(); @Override void close(); @Override void close(CloseReason closeReason); @Override int getMaxBinaryMessageBufferSize(); @Override void setMaxBinaryMessageBufferSize(int maxBinaryMessageBufferSize); @Override int getMaxTextMessageBufferSize(); @Override void setMaxTextMessageBufferSize(int maxTextMessageBufferSize); @Override Set<Session> getOpenSessions(); Set<RemoteSession> getRemoteSessions(); Set<DistributedSession> getAllSessions(); @Override List<Extension> getNegotiatedExtensions(); @Override long getMaxIdleTimeout(); @Override void setMaxIdleTimeout(long maxIdleTimeout); @Override boolean isSecure(); @Override WebSocketContainer getContainer(); @Override void addMessageHandler(MessageHandler handler); @Override void addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler); @Override void addMessageHandler(Class<T> clazz, MessageHandler.Partial<T> handler); @Override Set<MessageHandler> getMessageHandlers(); @Override void removeMessageHandler(MessageHandler handler); @Override URI getRequestURI(); @Override Map<String, List<String>> getRequestParameterMap(); @Override Map<String, String> getPathParameters(); @Override Map<String, Object> getUserProperties(); @Override Map<String, Object> getDistributedProperties(); @Override String getQueryString(); @Override String getId(); @Override Principal getUserPrincipal(); Map<Session, Future<?>> broadcast(String message); Map<Session, Future<?>> broadcast(ByteBuffer message); long getHeartbeatInterval(); void setHeartbeatInterval(long heartbeatInterval); @Override String toString(); String getRemoteAddr(); }### Answer: @Test public void idTest() { Session session1 = createSession(endpointWrapper); Session session2 = createSession(endpointWrapper); Session session3 = createSession(endpointWrapper); assertFalse(session1.getId().equals(session2.getId())); assertFalse(session1.getId().equals(session3.getId())); assertFalse(session2.getId().equals(session3.getId())); }
### Question: TyrusSession implements Session, DistributedSession { @Override public Map<String, Object> getUserProperties() { return userProperties; } TyrusSession(WebSocketContainer container, TyrusWebSocket socket, TyrusEndpointWrapper endpointWrapper, String subprotocol, List<Extension> extensions, boolean isSecure, URI requestURI, String queryString, Map<String, String> pathParameters, Principal principal, Map<String, List<String>> requestParameterMap, final ClusterContext clusterContext, String connectionId, final String remoteAddr, DebugContext debugContext); @Override String getProtocolVersion(); @Override String getNegotiatedSubprotocol(); @Override javax.websocket.RemoteEndpoint.Async getAsyncRemote(); @Override javax.websocket.RemoteEndpoint.Basic getBasicRemote(); @Override boolean isOpen(); @Override void close(); @Override void close(CloseReason closeReason); @Override int getMaxBinaryMessageBufferSize(); @Override void setMaxBinaryMessageBufferSize(int maxBinaryMessageBufferSize); @Override int getMaxTextMessageBufferSize(); @Override void setMaxTextMessageBufferSize(int maxTextMessageBufferSize); @Override Set<Session> getOpenSessions(); Set<RemoteSession> getRemoteSessions(); Set<DistributedSession> getAllSessions(); @Override List<Extension> getNegotiatedExtensions(); @Override long getMaxIdleTimeout(); @Override void setMaxIdleTimeout(long maxIdleTimeout); @Override boolean isSecure(); @Override WebSocketContainer getContainer(); @Override void addMessageHandler(MessageHandler handler); @Override void addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler); @Override void addMessageHandler(Class<T> clazz, MessageHandler.Partial<T> handler); @Override Set<MessageHandler> getMessageHandlers(); @Override void removeMessageHandler(MessageHandler handler); @Override URI getRequestURI(); @Override Map<String, List<String>> getRequestParameterMap(); @Override Map<String, String> getPathParameters(); @Override Map<String, Object> getUserProperties(); @Override Map<String, Object> getDistributedProperties(); @Override String getQueryString(); @Override String getId(); @Override Principal getUserPrincipal(); Map<Session, Future<?>> broadcast(String message); Map<Session, Future<?>> broadcast(ByteBuffer message); long getHeartbeatInterval(); void setHeartbeatInterval(long heartbeatInterval); @Override String toString(); String getRemoteAddr(); }### Answer: @Test public void userPropertiesTest() { Session session1 = createSession(endpointWrapper); Session session2 = createSession(endpointWrapper); final String test1 = "test1"; final String test2 = "test2"; session1.getUserProperties().put(test1, test1); session2.getUserProperties().put(test2, test2); assertNull(session1.getUserProperties().get(test2)); assertNull(session2.getUserProperties().get(test1)); assertNotNull(session1.getUserProperties().get(test1)); assertNotNull(session2.getUserProperties().get(test2)); }
### 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: Utils { public static Date parseHttpDate(String stringValue) throws ParseException { SimpleDateFormat formatRfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); try { return formatRfc1123.parse(stringValue); } catch (ParseException e) { SimpleDateFormat formatRfc1036 = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz"); try { return formatRfc1036.parse(stringValue); } catch (ParseException e1) { SimpleDateFormat formatAnsiCAsc = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy"); return formatAnsiCAsc.parse(stringValue); } } } static List<String> parseHeaderValue(String headerValue); static byte[] getRemainingArray(ByteBuffer buffer); static String getHeaderFromList(List<T> list); static List<String> getStringList(List<T> list, Stringifier<T> stringifier); static String getHeaderFromList(List<T> list, Stringifier<T> stringifier); static void checkNotNull(T reference, String parameterName); static byte[] toArray(long value); static long toLong(byte[] bytes, int start, int end); static List<String> toString(byte[] bytes); static List<String> toString(byte[] bytes, int start, int end); static ByteBuffer appendBuffers(ByteBuffer buffer, ByteBuffer buffer1, int incomingBufferSize, int BUFFER_STEP_SIZE); static T getProperty(Map<String, Object> properties, String key, Class<T> type); @SuppressWarnings("unchecked") static T getProperty(final Map<String, Object> properties, final String key, final Class<T> type, final T defaultValue); static int getWsPort(URI uri); static int getWsPort(URI uri, String scheme); static Date parseHttpDate(String stringValue); static String stringifyUpgradeRequest(UpgradeRequest upgradeRequest); static String stringifyUpgradeResponse(UpgradeResponse upgradeResponse); }### Answer: @Test public void testParseHttpDateRfc1123() { try { Date date = Utils.parseHttpDate("Sun, 06 Nov 1994 08:49:37 GMT"); assertNotNull("Date cannot be null", date); } catch (ParseException e) { fail("Cannot parse valid date"); } } @Test public void testParseHttpDateRfc1036() { try { Date date = Utils.parseHttpDate("Sunday, 06-Nov-94 08:49:37 GMT"); assertNotNull("Date cannot be null", date); } catch (ParseException e) { fail("Cannot parse valid date"); } } @Test public void testParseHttpDateAnsiCAsc() { try { Date date = Utils.parseHttpDate("Sun Nov 6 08:49:37 1994"); assertNotNull("Date cannot be null", date); } catch (ParseException e) { fail("Cannot parse valid date"); } } @Test public void testParseHttpDateFail() { try { Utils.parseHttpDate("2014-08-08 23:11:22 GMT"); fail("Invalid date cannot be parsed"); } catch (ParseException e) { } }
### Question: TyrusServerConfiguration implements ServerApplicationConfig { @Override public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) { return Collections.unmodifiableSet(annotatedClasses); } TyrusServerConfiguration(Set<Class<?>> classes, Set<ServerEndpointConfig> serverEndpointConfigs); TyrusServerConfiguration(Set<Class<?>> classes, Set<Class<?>> dynamicallyAddedClasses, Set<ServerEndpointConfig> serverEndpointConfigs, ErrorCollector errorCollector); @Override Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> scanned); @Override Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned); }### Answer: @Test public void testNoServerApplicationConfig() { Set<Class<?>> scanned = new HashSet<Class<?>>() { { add(AnnotatedA.class); add(AnnotatedB.class); add(ProgrammaticConfA.class); add(ProgrammaticConfB.class); add(Other.class); } }; TyrusServerConfiguration configuration = new TyrusServerConfiguration(scanned, Collections .<ServerEndpointConfig>emptySet()); Assert.assertEquals(2, configuration.getAnnotatedEndpointClasses(null).size()); Assert.assertTrue(configuration.getAnnotatedEndpointClasses(null).contains(AnnotatedA.class)); Assert.assertTrue(configuration.getAnnotatedEndpointClasses(null).contains(AnnotatedB.class)); } @Test public void testOneServerApplicationConfig() { Set<Class<?>> scanned = new HashSet<Class<?>>() { { add(ApplicationConfA.class); add(ProgrammaticConfB.class); add(AnnotatedB.class); add(Other.class); } }; TyrusServerConfiguration configuration = new TyrusServerConfiguration(scanned, Collections .<ServerEndpointConfig>emptySet()); Assert.assertEquals(1, configuration.getAnnotatedEndpointClasses(null).size()); Assert.assertTrue(configuration.getAnnotatedEndpointClasses(null).contains(AnnotatedA.class)); } @Test public void testTwoServerApplicationConfig() { Set<Class<?>> scanned = new HashSet<Class<?>>() { { add(ApplicationConfA.class); add(ApplicationConfB.class); add(AnnotatedC.class); add(ProgrammaticC.class); add(ProgrammaticConfC.class); add(Other.class); } }; TyrusServerConfiguration configuration = new TyrusServerConfiguration(scanned, Collections .<ServerEndpointConfig>emptySet()); Assert.assertEquals(1, configuration.getAnnotatedEndpointClasses(null).size()); Assert.assertTrue(configuration.getAnnotatedEndpointClasses(null).contains(AnnotatedA.class)); }
### 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: AbstractDAOGenericInvoiceImpl extends AbstractDAO<TInterface, TEntity> implements AbstractDAOGenericInvoice<TInterface> { @SuppressWarnings("unchecked") @Override public TInterface getLatestInvoiceFromSeries(String series, String businessUID) { JPABusinessEntity business = this.queryBusiness(businessUID).findOne(); if (business == null) { throw new BillyRuntimeException("No Business found for id: " + businessUID); } QueryIterator<JPAGenericInvoiceEntity> invoiceIterator = this.queryInvoice(series, business).orderBy().seriesNumber.desc().findIterate(); return (TInterface) (invoiceIterator.hasNext() ? invoiceIterator.next() : null); } @SuppressWarnings("unchecked") @Override TInterface getLatestInvoiceFromSeries(String series, String businessUID); }### Answer: @Test public void getLatestInvoiceFromSeries() { GenericInvoiceEntity invoice = AbstractDAOGenericInvoiceImplTest.genericInvoiceDAO.getLatestInvoiceFromSeries( AbstractDAOGenericInvoiceImplTest.rightSeries, AbstractDAOGenericInvoiceImplTest.rightBusinessUid.toString()); Assert.assertEquals(invoice.getUID(), AbstractDAOGenericInvoiceImplTest.latestInvoiceUid); } @Test public void getLatestInvoiceFromSeries_noBusiness() { this.expectedException.expect(BillyRuntimeException.class); GenericInvoiceEntity invoice = AbstractDAOGenericInvoiceImplTest.genericInvoiceDAO.getLatestInvoiceFromSeries( AbstractDAOGenericInvoiceImplTest.rightSeries, AbstractDAOGenericInvoiceImplTest.wrongBusinessUid.toString()); } @Test public void getLatestInvoiceFromSeries_wrongSeries() { GenericInvoiceEntity invoice = AbstractDAOGenericInvoiceImplTest.genericInvoiceDAO.getLatestInvoiceFromSeries( AbstractDAOGenericInvoiceImplTest.wrongSeries, AbstractDAOGenericInvoiceImplTest.rightBusinessUid.toString()); Assert.assertEquals(invoice, null); } @Test public void getLatestInvoiceFromSeries_wrongBusiness() { this.expectedException.expect(BillyRuntimeException.class); GenericInvoiceEntity invoice = AbstractDAOGenericInvoiceImplTest.genericInvoiceDAO.getLatestInvoiceFromSeries( AbstractDAOGenericInvoiceImplTest.rightSeries, AbstractDAOGenericInvoiceImplTest.wrongBusinessUid.toString()); }
### Question: PTFinancialValidator extends FinancialValidator { @Override public boolean isValid() { if (this.financialID.length() != 9 || !this.financialID.matches("\\d+")) { return false; } List<Character> firstDigits = Lists.charactersOf("123568"); boolean validFirstDigit = firstDigits .stream() .map(c -> financialID.charAt(0) == c).filter(b -> b) .findAny() .orElse(false); List<String> firstDoubleDigits = Lists.newArrayList("45", "70", "71", "72", "74", "75", "77", "79", "90", "91", "98", "99"); boolean validDoubleDigits = firstDoubleDigits .stream() .map(c -> financialID.substring(0, 2).equals(c)) .filter(b -> b) .findAny() .orElse(false); if(!validFirstDigit && !validDoubleDigits){ return false; } int checkSum = 0; for (int i = 1; i < this.financialID.length(); i++) { int digit = Character.getNumericValue(this.financialID.charAt(i - 1)); checkSum += (10 - i) * digit; } int lastDigit = Character.getNumericValue(this.financialID.charAt(8)); int val = (checkSum / 11) * 11; checkSum -= val; if (checkSum == 0 || checkSum == 1) { checkSum = 0; } else { checkSum = 11 - checkSum; } if (checkSum == lastDigit) { return true; } else { return false; } } PTFinancialValidator(String financialID); @Override boolean isValid(); static final String PT_COUNTRY_CODE; }### Answer: @Test public void testValidNifUsual() { PTFinancialValidator validator = new PTFinancialValidator("123456789"); assertTrue(validator.isValid()); } @Test public void testValidNif0term() { PTFinancialValidator validator = new PTFinancialValidator("504426290"); assertTrue(validator.isValid()); } @Test public void testInvalidNif() { PTFinancialValidator validator = new PTFinancialValidator("124456789"); assertFalse(validator.isValid()); } @Test public void testAnotherInvalidNif() { PTFinancialValidator validator = new PTFinancialValidator("505646780"); assertFalse(validator.isValid()); } @Test public void testValidDoubleDigit() { PTFinancialValidator validator = new PTFinancialValidator("451234561"); assertTrue(validator.isValid()); } @Test public void testValidNif() { PTFinancialValidator validator = new PTFinancialValidator("241250609"); assertTrue(validator.isValid()); }
### 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: DAOInvoiceSeriesImpl extends AbstractDAO<InvoiceSeriesEntity, JPAInvoiceSeriesEntity> implements DAOInvoiceSeries { @Override public InvoiceSeriesEntity getSeries(String series, String businessUID, LockModeType lockMode) { QJPAInvoiceSeriesEntity querySeries = this.queryInvoiceSeries(series, businessUID); if (lockMode == LockModeType.WRITE || lockMode == LockModeType.PESSIMISTIC_WRITE) { querySeries = querySeries.forUpdate(); } return querySeries.findOne(); } @Override InvoiceSeriesEntity getEntityInstance(); @Override InvoiceSeriesEntity getSeries(String series, String businessUID, LockModeType lockMode); }### Answer: @Test public void getSeries() { InvoiceSeriesEntity series = DAOInvoiceSeriesImplTest.daoInvoiceSeriesImpl.getSeries( DAOInvoiceSeriesImplTest.rightSeries, DAOInvoiceSeriesImplTest.rightBusinessUid.toString(), null); Assert.assertEquals(series.getUID(), DAOInvoiceSeriesImplTest.invoiceSeriesUid); } @Test public void getSeries_wrongSeriesId() { InvoiceSeriesEntity series = DAOInvoiceSeriesImplTest.daoInvoiceSeriesImpl.getSeries( DAOInvoiceSeriesImplTest.wrongSeries, DAOInvoiceSeriesImplTest.rightBusinessUid.toString(), null); Assert.assertEquals(series, null); } @Test public void getSeries_wrongBusinessId() { InvoiceSeriesEntity series = DAOInvoiceSeriesImplTest.daoInvoiceSeriesImpl.getSeries( DAOInvoiceSeriesImplTest.rightSeries, DAOInvoiceSeriesImplTest.wrongBusinessUid.toString(), null); Assert.assertEquals(series, null); } @Test public void getSeries_concurrent_deadlock() { Ebean.beginTransaction(); InvoiceSeriesEntity series = DAOInvoiceSeriesImplTest.daoInvoiceSeriesImpl.getSeries(DAOInvoiceSeriesImplTest.rightSeries, DAOInvoiceSeriesImplTest.rightBusinessUid.toString(), LockModeType.PESSIMISTIC_WRITE); long threadTimeout = 1000; long millis = System.currentTimeMillis(); Thread concurrentThread = new Thread() { @Override public void run() { Ebean.beginTransaction(); InvoiceSeriesEntity series = DAOInvoiceSeriesImplTest.daoInvoiceSeriesImpl.getSeries(DAOInvoiceSeriesImplTest.rightSeries, DAOInvoiceSeriesImplTest.rightBusinessUid.toString(), LockModeType.PESSIMISTIC_WRITE); Ebean.commitTransaction(); } }; concurrentThread.start(); try { concurrentThread.join(threadTimeout); } catch (InterruptedException e) { e.printStackTrace(); } long diff = System.currentTimeMillis() - millis; Ebean.commitTransaction(); Assert.assertEquals(diff >= threadTimeout, true); }
### 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); } }