method2testcases
stringlengths 118
3.08k
|
---|
### Question:
SchemeHandlerFactory extends Factory<SchemeHandler> { public static SchemeHandler get() { return new SchemeHandlerFactory().create(); } protected SchemeHandlerFactory(); static SchemeHandler get(); }### Answer:
@Test public void testGet() { assertNotNull(SchemeHandlerFactory.get()); }
|
### Question:
SHA1ChecksumCompute extends AbstractChecksumCompute { @Override public Checksum compute(final InputStream in, final TransferStatus status) throws ChecksumException { return new Checksum(HashAlgorithm.sha1, Hex.encodeHexString(this.digest("SHA-1", this.normalize(in, status)))); } @Override Checksum compute(final InputStream in, final TransferStatus status); }### Answer:
@Test public void testCompute() throws Exception { assertEquals("da39a3ee5e6b4b0d3255bfef95601890afd80709", new SHA1ChecksumCompute().compute(new NullInputStream(0), new TransferStatus()).hash); }
@Test public void testNormalize() throws Exception { assertEquals("140f86aae51ab9e1cda9b4254fe98a74eb54c1a1", new SHA1ChecksumCompute().compute(IOUtils.toInputStream("input", Charset.defaultCharset()), new TransferStatus()).hash); assertEquals("140f86aae51ab9e1cda9b4254fe98a74eb54c1a1", new SHA1ChecksumCompute().compute(IOUtils.toInputStream("_input", Charset.defaultCharset()), new TransferStatus().skip(1)).hash); assertEquals("140f86aae51ab9e1cda9b4254fe98a74eb54c1a1", new SHA1ChecksumCompute().compute(IOUtils.toInputStream("_input_", Charset.defaultCharset()), new TransferStatus().skip(1).length(5)).hash); }
|
### Question:
S3DefaultMultipartService implements S3MultipartService { @Override public void delete(final MultipartUpload upload) throws BackgroundException { if(log.isInfoEnabled()) { log.info(String.format("Delete multipart upload %s", upload.getUploadId())); } try { session.getClient().multipartAbortUpload(upload); } catch(S3ServiceException e) { throw new S3ExceptionMappingService().map("Cannot delete {0}", e, new Path(new Path(PathNormalizer.normalize(upload.getBucketName()), EnumSet.of(Path.Type.directory)), upload.getObjectKey(), EnumSet.of(Path.Type.file))); } } S3DefaultMultipartService(final S3Session session); @Override List<MultipartUpload> find(final Path file); @Override List<MultipartPart> list(final MultipartUpload upload); @Override void delete(final MultipartUpload upload); static final int MAXIMUM_UPLOAD_PARTS; }### Answer:
@Test public void testDelete() throws Exception { final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3DefaultMultipartService service = new S3DefaultMultipartService(session); for(MultipartUpload multipart : service.find(container)) { service.delete(multipart); } }
|
### Question:
SHA256ChecksumCompute extends AbstractChecksumCompute { @Override public Checksum compute(final InputStream in, final TransferStatus status) throws ChecksumException { return new Checksum(HashAlgorithm.sha256, Hex.encodeHexString(this.digest("SHA-256", this.normalize(in, status)))); } @Override Checksum compute(final InputStream in, final TransferStatus status); }### Answer:
@Test public void testCompute() throws Exception { assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", new SHA256ChecksumCompute().compute(new NullInputStream(0), new TransferStatus()).hash); }
@Test public void testNormalize() throws Exception { assertEquals("c96c6d5be8d08a12e7b5cdc1b207fa6b2430974c86803d8891675e76fd992c20", new SHA256ChecksumCompute().compute(IOUtils.toInputStream("input", Charset.defaultCharset()), new TransferStatus()).hash); assertEquals("c96c6d5be8d08a12e7b5cdc1b207fa6b2430974c86803d8891675e76fd992c20", new SHA256ChecksumCompute().compute(IOUtils.toInputStream("_input", Charset.defaultCharset()), new TransferStatus().skip(1)).hash); assertEquals("c96c6d5be8d08a12e7b5cdc1b207fa6b2430974c86803d8891675e76fd992c20", new SHA256ChecksumCompute().compute(IOUtils.toInputStream("_input_", Charset.defaultCharset()), new TransferStatus().skip(1).length(5)).hash); }
|
### Question:
DisabledChecksumCompute implements ChecksumCompute { @Override public Checksum compute(final InputStream in, final TransferStatus status) { IOUtils.closeQuietly(in); return Checksum.NONE; } @Override Checksum compute(final InputStream in, final TransferStatus status); @Override Checksum compute(final String data, final TransferStatus status); }### Answer:
@Test(expected = IOException.class) public void compute() throws Exception { final NullInputStream in = new NullInputStream(0L); new DisabledChecksumCompute().compute(in, new TransferStatus()); assertEquals(-1, in.read()); in.read(); }
|
### Question:
FileBuffer implements Buffer { @Override public void truncate(final Long length) { this.length = length; if(temporary.exists()) { try { final RandomAccessFile file = random(); if(length < file.length()) { file.setLength(length); } } catch(IOException e) { log.warn(String.format("Failure truncating file %s to %d", temporary, length)); } } } FileBuffer(); FileBuffer(final Local temporary); @Override synchronized int write(final byte[] chunk, final Long offset); @Override synchronized int read(final byte[] chunk, final Long offset); @Override synchronized Long length(); @Override void truncate(final Long length); @Override synchronized void close(); @Override String toString(); }### Answer:
@Test public void testTruncate() throws Exception { final FileBuffer buffer = new FileBuffer(); assertEquals(0L, buffer.length(), 0L); final byte[] chunk = RandomUtils.nextBytes(100); buffer.write(chunk, 0L); assertEquals(100L, buffer.length(), 0L); buffer.truncate(1L); assertEquals(1L, buffer.length(), 0L); final byte[] read = new byte[1]; assertEquals(1, buffer.read(read, 0L)); assertEquals(chunk[0], read[0]); assertEquals(1L, buffer.length(), 0L); }
|
### Question:
FileBuffer implements Buffer { @Override public synchronized void close() { this.length = 0L; if(temporary.exists()) { try { if(file != null) { file.close(); } } catch(IOException e) { log.error(String.format("Failure closing buffer %s", this)); } finally { try { temporary.delete(); file = null; } catch(AccessDeniedException | NotfoundException e) { log.warn(String.format("Failure removing temporary file %s for buffer %s. Schedule for delete on exit.", temporary, this)); Paths.get(temporary.getAbsolute()).toFile().deleteOnExit(); } } } } FileBuffer(); FileBuffer(final Local temporary); @Override synchronized int write(final byte[] chunk, final Long offset); @Override synchronized int read(final byte[] chunk, final Long offset); @Override synchronized Long length(); @Override void truncate(final Long length); @Override synchronized void close(); @Override String toString(); }### Answer:
@Test public void testClose() throws Exception { final FileBuffer buffer = new FileBuffer(); assertEquals(0L, buffer.length(), 0L); final byte[] chunk = RandomUtils.nextBytes(100); buffer.write(chunk, 0L); assertEquals(100L, buffer.length(), 0L); buffer.close(); assertEquals(0L, buffer.length(), 0L); buffer.write(chunk, 0L); assertEquals(100L, buffer.length(), 0L); }
|
### Question:
NIOEventWatchService implements RegisterWatchService { @Override public WatchKey register(final Watchable folder, final WatchEvent.Kind<?>[] events, final WatchEvent.Modifier... modifiers) throws IOException { if(null == monitor) { monitor = FileSystems.getDefault().newWatchService(); } final WatchKey key = folder.register(monitor, events, modifiers); if(log.isInfoEnabled()) { log.info(String.format("Registered for events for %s", key)); } return key; } @Override WatchKey register(final Watchable folder, final WatchEvent.Kind<?>[] events,
final WatchEvent.Modifier... modifiers); @Override void release(); @Override void close(); @Override WatchKey poll(); @Override WatchKey poll(final long timeout, final TimeUnit unit); @Override WatchKey take(); }### Answer:
@Test(expected = IOException.class) public void testNotfound() throws Exception { final FileWatcher watcher = new FileWatcher(new NIOEventWatchService()); final Local file = new Local(System.getProperty("java.io.tmpdir") + "/notfound", UUID.randomUUID().toString()); assertFalse(file.exists()); watcher.register(file.getParent(), new FileWatcher.DefaultFileFilter(file), new DisabledFileWatcherListener()); }
@Test public void testRegister() throws Exception { final RegisterWatchService fs = new NIOEventWatchService(); final Watchable folder = Paths.get( File.createTempFile(UUID.randomUUID().toString(), "t").getParent()); final WatchKey key = fs.register(folder, new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY}); assertTrue(key.isValid()); fs.close(); assertFalse(key.isValid()); }
|
### Question:
CRC32ChecksumCompute extends AbstractChecksumCompute { @Override public Checksum compute(final InputStream in, final TransferStatus status) throws ChecksumException { final InputStream normalized = this.normalize(in, status); final CRC32 crc32 = new CRC32(); try { byte[] buffer = new byte[16384]; int bytesRead; while((bytesRead = normalized.read(buffer, 0, buffer.length)) != -1) { crc32.update(buffer, 0, bytesRead); } } catch(IOException e) { throw new ChecksumException(LocaleFactory.localizedString("Checksum failure", "Error"), e.getMessage(), e); } finally { IOUtils.closeQuietly(normalized); } return new Checksum(HashAlgorithm.crc32, Long.toHexString(crc32.getValue())); } @Override Checksum compute(final InputStream in, final TransferStatus status); }### Answer:
@Test public void testCompute() throws Exception { assertEquals("0", new CRC32ChecksumCompute().compute(new NullInputStream(0), new TransferStatus()).hash); assertEquals("d202ef8d", new CRC32ChecksumCompute().compute(new NullInputStream(1L), new TransferStatus()).hash); }
|
### Question:
DefaultStreamCloser implements StreamCloser { @Override public void close(final InputStream in) throws BackgroundException { if(null == in) { return; } try { in.close(); } catch(IOException e) { if(e.getCause() instanceof BackgroundException) { throw (BackgroundException) e.getCause(); } throw new DefaultIOExceptionMappingService().map(e); } } @Override void close(final InputStream in); @Override void close(final OutputStream out); }### Answer:
@Test(expected = InteroperabilityException.class) public void testClose() throws Exception { new DefaultStreamCloser().close(new HttpResponseOutputStream<Void>(new NullOutputStream()) { @Override public Void getStatus() throws BackgroundException { throw new InteroperabilityException("d"); } }); }
|
### Question:
MemorySegementingOutputStream extends SegmentingOutputStream { @Override public void flush() throws IOException { log.warn(String.format("Flush stream %s", proxy)); this.flush(true); } MemorySegementingOutputStream(final OutputStream proxy, final Integer threshold); MemorySegementingOutputStream(final OutputStream proxy, final Integer threshold, final ByteArrayOutputStream buffer); @Override void flush(); @Override void close(); }### Answer:
@Test public void testFlush() throws Exception { final ByteArrayOutputStream proxy = new ByteArrayOutputStream(20); final MemorySegementingOutputStream out = new MemorySegementingOutputStream(proxy, 32768); final byte[] content = RandomUtils.nextBytes(40500); out.write(content, 0, 32800); assertEquals(32768, proxy.toByteArray().length); out.flush(); assertEquals(32800, proxy.toByteArray().length); out.write(content, 32800, 7700); out.close(); assertArrayEquals(content, proxy.toByteArray()); }
|
### Question:
BookmarkSearchFilter implements HostFilter { @Override public boolean accept(final Host bookmark) { final String[] elements = StringUtils.split(StringUtils.lowerCase(searchString, Locale.ROOT)); for(String search : elements) { if(StringUtils.lowerCase(BookmarkNameProvider.toString(bookmark), Locale.ROOT).contains(search)) { return true; } if(null != bookmark.getCredentials().getUsername()) { if(StringUtils.lowerCase(bookmark.getCredentials().getUsername(), Locale.ROOT).contains(search)) { return true; } } if(null != bookmark.getComment()) { if(StringUtils.lowerCase(bookmark.getComment(), Locale.ROOT).contains(search)) { return true; } } if(StringUtils.lowerCase(bookmark.getHostname(), Locale.ROOT).contains(search)) { return true; } for(String label : bookmark.getLabels()) { if(StringUtils.lowerCase(label, Locale.ROOT).contains(search)) { return true; } } } return false; } BookmarkSearchFilter(final String searchString); @Override boolean accept(final Host bookmark); }### Answer:
@Test public void accept() { final Host bookmark = new Host(new TestProtocol(Scheme.http), "a"); assertTrue(new BookmarkSearchFilter("b a").accept(bookmark)); assertFalse(new BookmarkSearchFilter("b testa").accept(bookmark)); assertFalse(new BookmarkSearchFilter("b b").accept(bookmark)); assertTrue(new BookmarkSearchFilter("HTTP").accept(bookmark)); bookmark.setNickname("t"); assertTrue(new BookmarkSearchFilter("t").accept(bookmark)); assertFalse(new BookmarkSearchFilter("t2").accept(bookmark)); bookmark.setLabels(Collections.singleton("l")); assertTrue(new BookmarkSearchFilter("l").accept(bookmark)); assertFalse(new BookmarkSearchFilter("l2").accept(bookmark)); }
|
### Question:
ReceiptFactory extends LicenseFactory { @Override protected License create() { return new DefaultLicenseFactory(this).create(); } ReceiptFactory(); ReceiptFactory(final Local folder); @Override List<License> open(); }### Answer:
@Test public void testCreate() { assertEquals(new Receipt(null, "b8e85600dffe"), new ReceiptFactory(new Local("src/test/resources")).create()); }
|
### Question:
ReceiptFactory extends LicenseFactory { @Override protected License open(final Local file) { final ReceiptVerifier verifier = new ReceiptVerifier(file); if(verifier.verify(new DisabledLicenseVerifierCallback())) { final Receipt receipt = new Receipt(file, verifier.getGuid()); if(log.isInfoEnabled()) { log.info(String.format("Valid receipt %s in %s", receipt, file)); } final Local support = SupportDirectoryFinderFactory.get().find(); try { file.copy(LocalFactory.get(support, String.format("%s.cyberduckreceipt", receipt.getName()))); } catch(AccessDeniedException e) { log.warn(e.getMessage()); } return receipt; } else { log.error(String.format("Invalid receipt found in %s", file)); System.exit(APPSTORE_VALIDATION_FAILURE); return null; } } ReceiptFactory(); ReceiptFactory(final Local folder); @Override List<License> open(); }### Answer:
@Test public void testOpen() throws Exception { new ReceiptFactory().open(); }
@Test public void testOpenDirectory() throws Exception { assertEquals(1, new ReceiptFactory(new Local("/Applications/Cyberduck.app/Contents/_MASReceipt")).open().size()); }
|
### Question:
DonationKeyFactory extends LicenseFactory { @Override protected License create() { return new DefaultLicenseFactory(this).create(); } @Override List<License> open(); }### Answer:
@Test public void testCreate() { assertEquals(new Receipt(null, "c42c030b8670"), new DonationKeyFactory().create()); }
|
### Question:
DefaultSearchFeature implements Search { @Override public AttributedList<Path> search(final Path workdir, final Filter<Path> filter, final ListProgressListener listener) throws BackgroundException { final AttributedList<Path> list; if(!cache.isCached(workdir)) { list = session.getFeature(ListService.class).list(workdir, new SearchListProgressListener(filter, listener)).filter(filter); } else { list = cache.get(workdir).filter(filter); } listener.chunk(workdir, list); return list; } DefaultSearchFeature(final Session<?> session); @Override AttributedList<Path> search(final Path workdir, final Filter<Path> filter, final ListProgressListener listener); @Override boolean isRecursive(); @Override Search withCache(final Cache<Path> cache); }### Answer:
@Test public void testSearch() throws Exception { final Path workdir = new Path("/", EnumSet.of(Path.Type.directory)); final Path f1 = new Path(workdir, "f1", EnumSet.of(Path.Type.file)); final Path f2 = new Path(workdir, "f2", EnumSet.of(Path.Type.file)); final DefaultSearchFeature feature = new DefaultSearchFeature(new NullSession(new Host(new TestProtocol())) { @Override public AttributedList<Path> list(final Path folder, final ListProgressListener listener) throws BackgroundException { if(folder.equals(workdir)) { final AttributedList<Path> list = new AttributedList<>(Arrays.asList(f1, f2)); listener.chunk(folder, list); return list; } return AttributedList.emptyList(); } }); final Filter<Path> filter = new NullFilter<Path>() { @Override public boolean accept(final Path file) { if(file.isDirectory()) { return true; } return file.getName().equals("f1"); } }; final AttributedList<Path> search = feature.search(workdir, filter, new DisabledListProgressListener()); assertTrue(search.contains(f1)); assertFalse(search.contains(f2)); assertEquals(1, search.size()); }
|
### Question:
PasswordStrengthValidator { public Strength getScore(final String password) { if(StringUtils.isEmpty(password)) { return Strength.veryweak; } else { final int score = zxcvbn.measure(password, Collections.singletonList( PreferencesFactory.get().getProperty("application.name"))).getScore(); switch(score) { case 0: return Strength.veryweak; case 1: return Strength.weak; case 2: return Strength.fair; case 3: return Strength.strong; case 4: default: return Strength.verystrong; } } } Strength getScore(final String password); }### Answer:
@Test public void testGetScore() { assertEquals(PasswordStrengthValidator.Strength.veryweak, new PasswordStrengthValidator().getScore("")); assertEquals(PasswordStrengthValidator.Strength.veryweak, new PasswordStrengthValidator().getScore("Cyberduck")); assertEquals(PasswordStrengthValidator.Strength.verystrong, new PasswordStrengthValidator().getScore("ahvae7faY3ae")); }
|
### Question:
AclDictionary { public <T> Acl deserialize(T serialized) { final Deserializer<?> dict = deserializer.create(serialized); final Acl acl = new Acl(); final List<String> keys = dict.keys(); for(String key : keys) { final List<Object> rolesObj = dict.listForKey(key); for(Object roleObj : rolesObj) { final Acl.Role role = new Acl.RoleDictionary(deserializer).deserialize(roleObj); acl.addAll(new Acl.CanonicalUser(key), role); } } return acl; } AclDictionary(); AclDictionary(final DeserializerFactory deserializer); Acl deserialize(T serialized); }### Answer:
@Test public void testSerialize() { Acl attributes = new Acl(new Acl.UserAndRole(new Acl.CanonicalUser(""), new Acl.Role("w"))); Acl clone = new AclDictionary().deserialize(attributes.serialize(SerializerFactory.get())); assertEquals(attributes.get(new Acl.CanonicalUser()), clone.get(new Acl.CanonicalUser())); assertNotEquals(attributes, new Acl(new Acl.UserAndRole(new Acl.CanonicalUser("t"), new Acl.Role("w")))); assertEquals(attributes.get(new Acl.CanonicalUser()), clone.get(new Acl.CanonicalUser())); assertNotEquals(attributes.get(new Acl.CanonicalUser()), new Acl(new Acl.UserAndRole(new Acl.CanonicalUser(""), new Acl.Role("r"))).get(new Acl.CanonicalUser())); }
|
### Question:
Archive { public static Archive forName(final String name) { if(StringUtils.isNotBlank(name)) { for(Archive archive : getKnownArchives()) { for(String extension : archive.getExtensions()) { if(name.toLowerCase(Locale.ROOT).endsWith(extension.toLowerCase(Locale.ROOT))) { return archive; } } } } log.fatal(String.format("Unknown archive %s", name)); return null; } private Archive(final String extension); static Archive getDefault(); static Archive[] getKnownArchives(); static Archive forName(final String name); String[] getExtensions(); String getIdentifier(); abstract String getDescription(); Path getArchive(final List<Path> files); List<Path> getExpanded(final List<Path> files); String getTitle(final List<Path> files); String getCompressCommand(final Path workdir, final List<Path> files); String getDecompressCommand(final Path path); static boolean isArchive(final String filename); static final Archive TAR; static final Archive TARGZ; static final Archive TARBZ2; static final Archive ZIP; static final Archive GZIP; static final Archive BZ2; }### Answer:
@Test public void testForName() { assertEquals(Archive.TAR, Archive.forName("tar")); assertEquals(Archive.TARGZ, Archive.forName("tar.gz")); assertEquals(Archive.ZIP, Archive.forName("zip")); }
|
### Question:
Archive { protected String escape(final String path) { final StringBuilder escaped = new StringBuilder(); for(char c : path.toCharArray()) { if(StringUtils.isAlphanumeric(String.valueOf(c)) || c == Path.DELIMITER) { escaped.append(c); } else { escaped.append("\\").append(c); } } return escaped.toString(); } private Archive(final String extension); static Archive getDefault(); static Archive[] getKnownArchives(); static Archive forName(final String name); String[] getExtensions(); String getIdentifier(); abstract String getDescription(); Path getArchive(final List<Path> files); List<Path> getExpanded(final List<Path> files); String getTitle(final List<Path> files); String getCompressCommand(final Path workdir, final List<Path> files); String getDecompressCommand(final Path path); static boolean isArchive(final String filename); static final Archive TAR; static final Archive TARGZ; static final Archive TARBZ2; static final Archive ZIP; static final Archive GZIP; static final Archive BZ2; }### Answer:
@Test public void testEscape() { Archive a = Archive.TAR; assertEquals("file\\ name", a.escape("file name")); assertEquals("file\\(name", a.escape("file(name")); assertEquals("\\$filename", a.escape("$filename")); }
|
### Question:
UploadRegexFilter implements Filter<Local> { @Override public boolean accept(final Local file) { if(pattern.matcher(file.getName()).matches()) { if(log.isDebugEnabled()) { log.debug(String.format("Skip %s excluded with regex", file)); } return false; } return true; } UploadRegexFilter(); UploadRegexFilter(final Pattern pattern); @Override boolean accept(final Local file); @Override Pattern toPattern(); @Override String toString(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testAccept() { final Pattern pattern = Pattern.compile(".*~\\..*|\\.DS_Store|\\.svn|CVS"); assertFalse(new UploadRegexFilter(pattern).accept(new NullLocal(".DS_Store"))); assertTrue(new UploadRegexFilter(pattern).accept(new NullLocal("f"))); assertTrue(new UploadRegexFilter(Pattern.compile("")).accept(new NullLocal("f"))); assertTrue(new UploadRegexFilter(Pattern.compile("")).accept(new NullLocal(".DS_Store"))); }
|
### Question:
DownloadRegexFilter extends DownloadDuplicateFilter { @Override public boolean accept(final Path file) { if(!super.accept(file)) { return false; } if(pattern.matcher(file.getName()).matches()) { if(log.isDebugEnabled()) { log.debug(String.format("Skip %s excluded with regex", file.getAbsolute())); } return false; } return true; } DownloadRegexFilter(); DownloadRegexFilter(final Pattern pattern); @Override boolean accept(final Path file); @Override Pattern toPattern(); @Override String toString(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testAccept() { final Pattern pattern = Pattern.compile(".*~\\..*|\\.DS_Store|\\.svn|CVS|RCS|SCCS|\\.git|\\.bzr|\\.bzrignore|\\.bzrtags|\\.hg|\\.hgignore|\\.hgtags|_darcs|\\.file-segments"); assertFalse(new DownloadRegexFilter(pattern).accept(new Path(".DS_Store", EnumSet.of(Path.Type.file)))); assertTrue(new DownloadRegexFilter(pattern).accept(new Path("f", EnumSet.of(Path.Type.file)))); assertTrue(new DownloadRegexFilter(Pattern.compile("")).accept(new Path("f", EnumSet.of(Path.Type.file)))); assertTrue(new DownloadRegexFilter(Pattern.compile("")).accept(new Path("f", EnumSet.of(Path.Type.file)))); }
|
### Question:
NaturalOrderComparator implements Comparator<String>, java.io.Serializable { @Override public int compare(final String s1, final String s2) { return collator.compare(s1, s2); } @Override int compare(final String s1, final String s2); }### Answer:
@Test public void testCompare() { assertEquals(-1, new NaturalOrderComparator().compare("123a", "a")); assertEquals(-1, new NaturalOrderComparator().compare("365", "400")); }
|
### Question:
StringAppender { public StringAppender append(final String message) { if(StringUtils.isBlank(message)) { return this; } if(buffer.length() > 0) { buffer.append(" "); } buffer.append(StringUtils.trim(message)); if(buffer.charAt(buffer.length() - 1) == '.') { return this; } if(buffer.charAt(buffer.length() - 1) == ':') { buffer.deleteCharAt(buffer.length() - 1); } if(!Pattern.matches("[.?!]", String.valueOf(buffer.charAt(buffer.length() - 1)))) { buffer.append(suffix); } return this; } StringAppender(); StringAppender(final char suffix); StringAppender(final StringBuilder buffer); StringAppender(final StringBuilder buffer, final char suffix); StringAppender append(final String message); @Override String toString(); }### Answer:
@Test public void testAppend() { assertEquals("Verification Code.", new StringAppender().append("Verification Code:").toString()); assertEquals("Message.", new StringAppender().append("Message").toString()); assertEquals("Message.", new StringAppender().append("Message.").toString()); assertEquals("Message?", new StringAppender().append("Message?").toString()); assertEquals("Message).", new StringAppender().append("Message)").toString()); assertEquals("m.", new StringAppender().append("m").append(" ").toString()); }
|
### Question:
S3LocationFeature implements Location { @Override public Set<Name> getLocations() { if(StringUtils.isNotBlank(session.getHost().getRegion())) { return Collections.singleton(new S3Region(session.getHost().getRegion())); } if(S3Session.isAwsHostname(session.getHost().getHostname())) { return session.getHost().getProtocol().getRegions(); } return Collections.emptySet(); } S3LocationFeature(final S3Session session); S3LocationFeature(final S3Session session, final RegionEndpointCache cache); @Override Set<Name> getLocations(); @Override Name getLocation(final Path file); }### Answer:
@Test public void testEmptyThirdPartyProvider() { final Host host = new Host(new S3Protocol(), "mys3", new Credentials( PreferencesFactory.get().getProperty("connection.login.anon.name"), null )); final S3Session session = new S3Session(host); assertTrue(new S3LocationFeature(session).getLocations().isEmpty()); }
|
### Question:
SessionListWorker extends Worker<AttributedList<Path>> { @Override public AttributedList<Path> initialize() { return AttributedList.emptyList(); } SessionListWorker(final Cache<Path> cache, final Path directory, final ListProgressListener listener); @Override AttributedList<Path> run(final Session<?> session); @Override void cleanup(final AttributedList<Path> list); @Override String getActivity(); @Override AttributedList<Path> initialize(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testInitialValueOnFailure() { final SessionListWorker worker = new SessionListWorker(PathCache.empty(), new Path("/home/notfound", EnumSet.of(Path.Type.directory)), new DisabledListProgressListener()); assertSame(AttributedList.emptyList(), worker.initialize()); }
|
### Question:
DefaultExceptionMappingService extends AbstractExceptionMappingService<Throwable> { @Override public BackgroundException map(final Throwable failure) { final StringBuilder buffer = new StringBuilder(); if(failure instanceof RuntimeException) { this.append(buffer, LocaleFactory.localizedString("Unknown application error")); } this.append(buffer, failure.getMessage()); for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(!StringUtils.contains(failure.getMessage(), cause.getMessage())) { this.append(buffer, cause.getMessage()); } } return this.wrap(failure, LocaleFactory.localizedString("Error", "Error"), buffer); } @Override BackgroundException map(final Throwable failure); }### Answer:
@Test public void testMap() { assertEquals("Error", new DefaultExceptionMappingService().map(new NullPointerException()).getMessage()); assertEquals("Unknown application error.", new DefaultExceptionMappingService().map(new NullPointerException()).getDetail()); assertEquals("Unknown application error. R.", new DefaultExceptionMappingService().map(new NullPointerException("r")).getDetail()); }
|
### Question:
ReadSizeWorker extends Worker<Long> { @Override public Long run(final Session<?> session) throws BackgroundException { for(Path next : files) { if(this.isCanceled()) { throw new ConnectionCanceledException(); } if(-1 == next.attributes().getSize()) { continue; } total += next.attributes().getSize(); } return total; } ReadSizeWorker(final List<Path> files); @Override Long run(final Session<?> session); @Override String getActivity(); @Override Long initialize(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testRun() throws Exception { final Path d = new Path("/d", EnumSet.of(Path.Type.directory)); d.attributes().setSize(-1L); final ReadSizeWorker worker = new ReadSizeWorker(Collections.singletonList(d)) { @Override public void cleanup(final Long result) { } }; assertEquals(0L, worker.run(new NullSession(new Host(new TestProtocol()))), 0L); }
|
### Question:
CalculateSizeWorker extends Worker<Long> { @Override public Long run(final Session<?> session) throws BackgroundException { for(Path next : files) { next.attributes().setSize(this.calculateSize(session, next)); } return total; } CalculateSizeWorker(final List<Path> files, final ProgressListener listener); @Override Long run(final Session<?> session); @Override String getActivity(); @Override Long initialize(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testRun() throws Exception { final List<Path> files = new ArrayList<Path>(); final Path a = new Path("a", EnumSet.of(Path.Type.file)); a.attributes().setSize(1L); files.add(a); final Path b = new Path("a", EnumSet.of(Path.Type.file)); b.attributes().setSize(3L); files.add(b); assertEquals(4L, new CalculateSizeWorker(files, new DisabledProgressListener()) { int i = 0; @Override public void cleanup(final Long result) { assertEquals(4L, result, 0L); } @Override protected void update(final long size) { if(0 == i) { assertEquals(1L, size, 0L); } if(1 == i) { assertEquals(4L, size, 0L); } i++; } }.run(new NullSession(new Host(new TestProtocol()))), 0L); }
|
### Question:
LoggingConfiguration { @Override public boolean equals(final Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final LoggingConfiguration that = (LoggingConfiguration) o; if(enabled != that.enabled) { return false; } if(!Objects.equals(loggingTarget, that.loggingTarget)) { return false; } return true; } LoggingConfiguration(); LoggingConfiguration(final boolean enabled); LoggingConfiguration(final boolean enabled, final String loggingTarget); static LoggingConfiguration empty(); boolean isEnabled(); String getLoggingTarget(); List<Path> getContainers(); void setContainers(final List<Path> containers); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testEquals() { assertEquals(LoggingConfiguration.empty(), new LoggingConfiguration()); assertEquals(new LoggingConfiguration(true), new LoggingConfiguration(true)); assertEquals(new LoggingConfiguration(false), new LoggingConfiguration(false)); assertNotEquals(new LoggingConfiguration(true), new LoggingConfiguration(false)); assertNotEquals(new LoggingConfiguration(true), new LoggingConfiguration(true, "a")); assertNotEquals(new LoggingConfiguration(true, "b"), new LoggingConfiguration(true, "a")); }
|
### Question:
AttributedList implements Iterable<E> { @Override public boolean equals(final Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final AttributedList<?> that = (AttributedList<?>) o; return Objects.equals(impl, that.impl); } AttributedList(); AttributedList(final Iterable<E> collection); @SuppressWarnings("unchecked") static AttributedList<T> emptyList(); AttributedListAttributes<E> attributes(); boolean add(final E e); void add(final int index, final E e); boolean addAll(final Iterable<? extends E> c); E get(final int index); E get(final E reference); void set(final int i, final E e); @Override Iterator<E> iterator(); AttributedList<E> filter(final Filter<E> filter); AttributedList<E> filter(final Comparator<E> comparator); AttributedList<E> filter(final Comparator<E> comparator, final Filter<E> filter); void clear(); boolean isEmpty(); int size(); boolean contains(final E e); E find(final Predicate<E> predicate); @SuppressWarnings("unchecked") E[] toArray(); List<E> toList(); int indexOf(final E e); void remove(final int index); boolean remove(final E e); boolean removeAll(final java.util.Collection<E> e); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testEquals() { final AttributedList<Path> list1 = new AttributedList<Path>(); final AttributedList<Path> list2 = new AttributedList<Path>(); final Path a = new Path("/a", EnumSet.of(Path.Type.directory)); assertTrue(list1.add(a)); assertTrue(list2.add(a)); assertEquals(list1, list2); }
|
### Question:
MonitorFolderHostCollection extends AbstractFolderHostCollection { @Override public void load() throws AccessDeniedException { super.load(); if(preferences.getBoolean("bookmarks.folder.monitor")) { try { monitor.register(folder, FILE_FILTER, this); } catch(IOException e) { throw new LocalAccessDeniedException(String.format("Failure monitoring directory %s", folder.getName()), e); } } } MonitorFolderHostCollection(final Local f); @Override void load(); @Override void fileWritten(final Local file); @Override void fileDeleted(final Local file); @Override void fileCreated(final Local file); }### Answer:
@Test public void testLoad() throws Exception { final Local source = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final MonitorFolderHostCollection c = new MonitorFolderHostCollection(source); c.load(); final Host bookmark = new Host(new TestProtocol()); c.add(bookmark); assertEquals(1, c.size()); bookmark.setLabels(Collections.singleton("l")); c.collectionItemChanged(bookmark); assertEquals(1, c.size()); }
|
### Question:
DefaultPathKindDetector implements PathKindDetector { @Override public Path.Type detect(final String path) { if(StringUtils.isBlank(path)) { return Path.Type.directory; } if(path.endsWith(String.valueOf(Path.DELIMITER))) { return Path.Type.directory; } if(StringUtils.isBlank(Path.getExtension(path))) { return Path.Type.directory; } return Path.Type.file; } @Override Path.Type detect(final String path); }### Answer:
@Test public void testDetect() { DefaultPathKindDetector d = new DefaultPathKindDetector(); assertEquals(Path.Type.directory, d.detect(null)); assertEquals(Path.Type.directory, d.detect("/")); assertEquals(Path.Type.directory, d.detect("/a")); assertEquals(Path.Type.directory, d.detect("/a/")); assertEquals(Path.Type.file, d.detect("/a/b.z")); assertEquals(Path.Type.file, d.detect("/a/b.zip")); }
|
### Question:
PathNormalizer { public static String name(final String path) { if(String.valueOf(Path.DELIMITER).equals(path)) { return path; } if(!StringUtils.contains(path, Path.DELIMITER)) { return UNICODE_NORMALIZER.normalize(path).toString(); } if(StringUtils.endsWith(path, String.valueOf(Path.DELIMITER))) { return UNICODE_NORMALIZER.normalize(StringUtils.substringAfterLast(normalize(path), String.valueOf(Path.DELIMITER))).toString(); } return UNICODE_NORMALIZER.normalize(StringUtils.substringAfterLast(path, String.valueOf(Path.DELIMITER))).toString(); } private PathNormalizer(); static String name(final String path); static String parent(final String absolute, final char delimiter); static String normalize(final String path); static String normalize(final String path, final boolean absolute); static List<Path> normalize(final List<Path> selected); }### Answer:
@Test public void testName() { assertEquals("p", PathNormalizer.name("/p")); assertEquals("n", PathNormalizer.name("/p/n")); assertEquals("p", PathNormalizer.name("p")); assertEquals("n", PathNormalizer.name("p/n")); }
@Test public void testNormalizeNameWithBackslash() { assertEquals("file\\name", PathNormalizer.name("/path/to/file\\name")); }
|
### Question:
PathNormalizer { public static String parent(final String absolute, final char delimiter) { if(String.valueOf(delimiter).equals(absolute)) { return null; } int index = absolute.length() - 1; if(absolute.charAt(index) == delimiter) { if(index > 0) { index--; } } int cut = absolute.lastIndexOf(delimiter, index); if(cut > 0) { return UNICODE_NORMALIZER.normalize(absolute.substring(0, cut)).toString(); } return String.valueOf(delimiter); } private PathNormalizer(); static String name(final String path); static String parent(final String absolute, final char delimiter); static String normalize(final String path); static String normalize(final String path, final boolean absolute); static List<Path> normalize(final List<Path> selected); }### Answer:
@Test public void testParent() { assertEquals("/", PathNormalizer.parent("/p", '/')); assertEquals("/p", PathNormalizer.parent("/p/n", '/')); assertNull(PathNormalizer.parent("/", '/')); }
|
### Question:
PreferencesUseragentProvider implements UseragentProvider { @Override public String get() { return ua; } @Override String get(); }### Answer:
@Test public void testGet() { assertTrue(new PreferencesUseragentProvider().get().startsWith("Cyberduck/")); }
|
### Question:
CaseInsensitivePathPredicate implements CacheReference<Path> { @Override public boolean test(final Path test) { return this.equals(new CaseInsensitivePathPredicate(test)); } CaseInsensitivePathPredicate(final Path file); @Override boolean equals(final Object o); @Override int hashCode(); @Override boolean test(final Path test); @Override String toString(); }### Answer:
@Test public void testPredicateTest() { final Path t = new Path("/f", EnumSet.of(Path.Type.file)); assertTrue(new CaseInsensitivePathPredicate(t).test(new Path("/f", EnumSet.of(Path.Type.file)))); assertTrue(new CaseInsensitivePathPredicate(t).test(new Path("/F", EnumSet.of(Path.Type.file)))); assertFalse(new CaseInsensitivePathPredicate(t).test(new Path("/f/a", EnumSet.of(Path.Type.file)))); assertFalse(new CaseInsensitivePathPredicate(t).test(new Path("/f", EnumSet.of(Path.Type.directory)))); }
@Test public void testCollision() { final Path t = new Path("/d/2R", EnumSet.of(Path.Type.directory)); assertFalse(new SimplePathPredicate(t).test(new Path("/d/33", EnumSet.of(Path.Type.directory)))); }
|
### Question:
PunycodeConverter { public String convert(final String hostname) { if(!PreferencesFactory.get().getBoolean("connection.hostname.idn")) { return StringUtils.strip(hostname); } if(StringUtils.isNotEmpty(hostname)) { try { final String idn = IDN.toASCII(StringUtils.strip(hostname)); if(log.isDebugEnabled()) { if(!StringUtils.equals(StringUtils.strip(hostname), idn)) { log.debug(String.format("IDN hostname for %s is %s", hostname, idn)); } } if(StringUtils.isNotEmpty(idn)) { return idn; } } catch(IllegalArgumentException e) { log.warn(String.format("Failed to convert hostname %s to IDNA", hostname), e); } } return StringUtils.strip(hostname); } String convert(final String hostname); }### Answer:
@Test public void testConvert() { assertEquals("host.localdomain", new PunycodeConverter().convert("host.localdomain")); assertNull(new PunycodeConverter().convert(null)); assertEquals("", new PunycodeConverter().convert("")); assertEquals("xn--4ca", new PunycodeConverter().convert("ä")); }
@Test public void testConvertWhitespace() { assertEquals("host.localdomain", new PunycodeConverter().convert("host.localdomain ")); }
@Test public void testHostnameStartsWithDot() { assertEquals(".blob.core.windows.net", new PunycodeConverter().convert(".blob.core.windows.net")); }
|
### Question:
SSLExceptionMappingService extends AbstractExceptionMappingService<SSLException> { @Override public BackgroundException map(final SSLException failure) { final StringBuilder buffer = new StringBuilder(); for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(cause instanceof SocketException) { return new DefaultSocketExceptionMappingService().map((SocketException) cause); } } final String message = failure.getMessage(); for(Alert alert : Alert.values()) { if(StringUtils.containsIgnoreCase(message, alert.name())) { this.append(buffer, alert.getDescription()); break; } } if(failure instanceof SSLHandshakeException) { if(ExceptionUtils.getRootCause(failure) instanceof CertificateException) { log.warn(String.format("Ignore certificate failure %s and drop connection", failure.getMessage())); return new ConnectionCanceledException(failure); } if(ExceptionUtils.getRootCause(failure) instanceof EOFException) { return this.wrap(failure, buffer); } return new SSLNegotiateException(buffer.toString(), failure); } if(ExceptionUtils.getRootCause(failure) instanceof GeneralSecurityException) { this.append(buffer, ExceptionUtils.getRootCause(failure).getMessage()); return new InteroperabilityException(buffer.toString(), failure); } this.append(buffer, message); return new InteroperabilityException(buffer.toString(), failure); } @Override BackgroundException map(final SSLException failure); }### Answer:
@Test public void testMap() { final BackgroundException f = new SSLExceptionMappingService().map(new SSLException( "Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe", new SSLException("javax.net.ssl.SSLException: java.net.SocketException: Broken pipe", new SocketException("Broken pipe")))); assertEquals("Connection failed", f.getMessage()); assertEquals("Broken pipe. The connection attempt was rejected. The server may be down, or your network may not be properly configured.", f.getDetail()); }
|
### Question:
DefaultX509KeyManager extends AbstractX509KeyManager implements X509KeyManager { @Override public List<String> list() { final List<String> list = new ArrayList<String>(); try { final javax.net.ssl.X509KeyManager manager = this.getKeystore(); { final String[] aliases = manager.getClientAliases("RSA", null); if(null != aliases) { Collections.addAll(list, aliases); } } { final String[] aliases = manager.getClientAliases("DSA", null); if(null != aliases) { Collections.addAll(list, aliases); } } } catch(IOException e) { log.warn(String.format("Failure listing aliases. %s", e.getMessage())); return Collections.emptyList(); } return list; } @Override X509KeyManager init(); @Override X509Certificate getCertificate(final String alias, final String[] keyTypes, final Principal[] issuers); @Override List<String> list(); @Override String[] getClientAliases(final String keyType, final Principal[] issuers); @Override String chooseClientAlias(final String[] keyType, final Principal[] issuers, final Socket socket); @Override String[] getServerAliases(final String keyType, final Principal[] issuers); @Override String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket); @Override X509Certificate[] getCertificateChain(final String alias); @Override PrivateKey getPrivateKey(final String alias); }### Answer:
@Test public void testList() { assertTrue(new DefaultX509KeyManager().init().list().isEmpty()); }
|
### Question:
DEREncoder implements CertificateEncoder { @Override public Object[] encode(final List<X509Certificate> certificates) throws CertificateException { final Object[] encoded = new Object[certificates.size()]; for(int i = 0; i < certificates.size(); i++) { encoded[i] = certificates.get(i).getEncoded(); } return encoded; } @Override Object[] encode(final List<X509Certificate> certificates); }### Answer:
@Test public void testEncode() throws Exception { InputStream inStream = new FileInputStream("src/test/resources CertificateFactory cf = CertificateFactory.getInstance("X.509"); final X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); assertEquals(1, new DEREncoder().encode(Collections.singletonList(cert)).length); }
|
### Question:
CustomTrustSSLProtocolSocketFactory extends SSLSocketFactory { public SSLContext getSSLContext() { return context; } CustomTrustSSLProtocolSocketFactory(final X509TrustManager trust, final X509KeyManager key); CustomTrustSSLProtocolSocketFactory(final X509TrustManager trust, final X509KeyManager key, final String... protocols); CustomTrustSSLProtocolSocketFactory(final X509TrustManager trust, final X509KeyManager key,
final SecureRandom seeder,
final String... protocols); SSLContext getSSLContext(); @Override String[] getDefaultCipherSuites(); @Override String[] getSupportedCipherSuites(); @Override Socket createSocket(); @Override Socket createSocket(final String host, final int port,
final InetAddress clientHost, final int clientPort); @Override Socket createSocket(final InetAddress host, final int port); @Override Socket createSocket(final InetAddress host, final int port,
final InetAddress localHost, final int localPort); @Override Socket createSocket(final String host, final int port); @Override Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose); }### Answer:
@Test public void testGetSSLContext() { assertNotNull(new CustomTrustSSLProtocolSocketFactory(new DefaultX509TrustManager(), new CertificateStoreX509KeyManager( new DisabledCertificateIdentityCallback(), new Host(new TestProtocol()), new DisabledCertificateStore() )).getSSLContext()); }
|
### Question:
ThreadLocalHostnameDelegatingTrustManager implements X509TrustManager, TrustManagerHostnameCallback { public void setTarget(final String hostname) { this.target.set(hostname); } ThreadLocalHostnameDelegatingTrustManager(final X509TrustManager delegate, final String hostname); @Override X509TrustManager init(); @Override void verify(final String hostname, final X509Certificate[] certs, final String cipher); @Override void checkClientTrusted(final X509Certificate[] certs, final String cipher); @Override void checkServerTrusted(final X509Certificate[] certs, final String cipher); @Override X509Certificate[] getAcceptedIssuers(); @Override String getTarget(); void setTarget(final String hostname); @Override String toString(); }### Answer:
@Test public void testSetTarget() { assertEquals("s3.amazonaws.com", new ThreadLocalHostnameDelegatingTrustManager(new DisabledX509TrustManager(), "s3.amazonaws.com").getTarget()); assertEquals("cyberduck.s3.amazonaws.com", new ThreadLocalHostnameDelegatingTrustManager(new DisabledX509TrustManager(), "cyberduck.s3.amazonaws.com").getTarget()); assertEquals("cyber.duck.s3.amazonaws.com", new ThreadLocalHostnameDelegatingTrustManager(new DisabledX509TrustManager(), "cyber.duck.s3.amazonaws.com").getTarget()); }
|
### Question:
DefaultX509TrustManager extends AbstractX509TrustManager { @Override public void checkServerTrusted(final X509Certificate[] certs, final String cipher) throws CertificateException { if((certs != null)) { if(log.isDebugEnabled()) { log.debug("Server certificate chain:"); for(int i = 0; i < certs.length; i++) { log.debug(String.format("X509Certificate[%d]=%s", i, certs[i])); } } } if((certs != null) && (certs.length == 1)) { this.verify(null, certs, cipher); } else { system.checkServerTrusted(certs, cipher); } } DefaultX509TrustManager init(); @Override void verify(final String hostname, final X509Certificate[] certs, final String cipher); @Override void checkClientTrusted(final X509Certificate[] certs, final String cipher); @Override void checkServerTrusted(final X509Certificate[] certs, final String cipher); }### Answer:
@Test(expected = CertificateExpiredException.class) public void testCheckServerTrusted() throws Exception { final DefaultX509TrustManager m = new DefaultX509TrustManager(); InputStream inStream = new FileInputStream("src/test/resources/OXxlRDVcWqdPEvFm.cer"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); m.checkServerTrusted(new X509Certificate[]{cert}, "RSA"); }
|
### Question:
PathCache extends AbstractCache<Path> { public static PathCache empty() { return EMPTY; } PathCache(final int size); static PathCache empty(); @Override CacheReference<?> reference(final Path file); }### Answer:
@Test public void testDisabledCache() { PathCache cache = PathCache.empty(); final Path file = new Path("name", EnumSet.of(Path.Type.file)); cache.put(file, AttributedList.<Path>emptyList()); assertFalse(cache.containsKey(file)); assertEquals(0, cache.size()); }
|
### Question:
LocaleFactory extends Factory<Locale> { public static String localizedString(final String key) { return localizedString(key, "Localizable"); } LocaleFactory(); static synchronized Locale get(); static synchronized void set(Locale l); static String localizedString(final String key); static String localizedString(final String key, final String table); }### Answer:
@Test public void testFormat() { assertEquals("La clé d'hôte fournie est 1.", MessageFormat.format(LocaleFactory.localizedString("La clé d'hôte fournie est {0}."), "1")); }
@Test public void testLocalizedString() { assertEquals("La clé d''hôte fournie est {0}.", LocaleFactory.localizedString("La clé d'hôte fournie est {0}.", "Localizable")); }
|
### Question:
Path extends AbstractPath implements Referenceable, Serializable { @Override public <T> T serialize(final Serializer dict) { dict.setStringForKey(String.valueOf(type), "Type"); dict.setStringForKey(this.getAbsolute(), "Remote"); if(symlink != null) { dict.setObjectForKey(symlink, "Symbolic Link"); } dict.setObjectForKey(attributes, "Attributes"); return dict.getSerialized(); } Path(final Path copy); Path(final Path parent, final String name, final EnumSet<Type> type); Path(final String absolute, final EnumSet<Type> type); Path(final String absolute, final EnumSet<Type> type, final PathAttributes attributes); Path(final Path parent, final String name, final EnumSet<Type> type, final PathAttributes attributes); @Override T serialize(final Serializer dict); @Override EnumSet<Type> getType(); void setType(final EnumSet<Type> type); boolean isVolume(); boolean isDirectory(); boolean isPlaceholder(); boolean isFile(); boolean isSymbolicLink(); @Override char getDelimiter(); Path getParent(); PathAttributes attributes(); void setAttributes(final PathAttributes attributes); Path withAttributes(final PathAttributes attributes); @Override String getName(); @Override String getAbsolute(); Path getSymlinkTarget(); void setSymlinkTarget(final Path target); @Override int hashCode(); @Override boolean equals(Object other); @Override String toString(); boolean isChild(final Path directory); static final char DELIMITER; }### Answer:
@Test public void testDictionaryDirectory() { Path path = new Path("/path", EnumSet.of(Path.Type.directory)); assertEquals(path, new PathDictionary().deserialize(path.serialize(SerializerFactory.get()))); }
@Test public void testDictionaryFile() { Path path = new Path("/path", EnumSet.of(Path.Type.file)); assertEquals(path, new PathDictionary().deserialize((path.serialize(SerializerFactory.get())))); }
|
### Question:
Path extends AbstractPath implements Referenceable, Serializable { public PathAttributes attributes() { return attributes; } Path(final Path copy); Path(final Path parent, final String name, final EnumSet<Type> type); Path(final String absolute, final EnumSet<Type> type); Path(final String absolute, final EnumSet<Type> type, final PathAttributes attributes); Path(final Path parent, final String name, final EnumSet<Type> type, final PathAttributes attributes); @Override T serialize(final Serializer dict); @Override EnumSet<Type> getType(); void setType(final EnumSet<Type> type); boolean isVolume(); boolean isDirectory(); boolean isPlaceholder(); boolean isFile(); boolean isSymbolicLink(); @Override char getDelimiter(); Path getParent(); PathAttributes attributes(); void setAttributes(final PathAttributes attributes); Path withAttributes(final PathAttributes attributes); @Override String getName(); @Override String getAbsolute(); Path getSymlinkTarget(); void setSymlinkTarget(final Path target); @Override int hashCode(); @Override boolean equals(Object other); @Override String toString(); boolean isChild(final Path directory); static final char DELIMITER; }### Answer:
@Test public void testPopulateRegion() { { Path container = new Path("test", EnumSet.of(Path.Type.directory)); container.attributes().setRegion("DFW"); Path path = new Path(container, "f", EnumSet.of(Path.Type.file)); assertEquals("DFW", path.attributes().getRegion()); } { Path container = new Path("test", EnumSet.of(Path.Type.directory)); container.attributes().setRegion("DFW"); assertEquals("DFW", container.attributes().getRegion()); } }
|
### Question:
Path extends AbstractPath implements Referenceable, Serializable { public Path getParent() { if(this.isRoot()) { return this; } return parent; } Path(final Path copy); Path(final Path parent, final String name, final EnumSet<Type> type); Path(final String absolute, final EnumSet<Type> type); Path(final String absolute, final EnumSet<Type> type, final PathAttributes attributes); Path(final Path parent, final String name, final EnumSet<Type> type, final PathAttributes attributes); @Override T serialize(final Serializer dict); @Override EnumSet<Type> getType(); void setType(final EnumSet<Type> type); boolean isVolume(); boolean isDirectory(); boolean isPlaceholder(); boolean isFile(); boolean isSymbolicLink(); @Override char getDelimiter(); Path getParent(); PathAttributes attributes(); void setAttributes(final PathAttributes attributes); Path withAttributes(final PathAttributes attributes); @Override String getName(); @Override String getAbsolute(); Path getSymlinkTarget(); void setSymlinkTarget(final Path target); @Override int hashCode(); @Override boolean equals(Object other); @Override String toString(); boolean isChild(final Path directory); static final char DELIMITER; }### Answer:
@Test public void testGetParent() { assertEquals(new Path("/b/t", EnumSet.of(Path.Type.directory)), new Path("/b/t/f.type", EnumSet.of(Path.Type.file)).getParent()); }
|
### Question:
Path extends AbstractPath implements Referenceable, Serializable { @Override public String getAbsolute() { return path; } Path(final Path copy); Path(final Path parent, final String name, final EnumSet<Type> type); Path(final String absolute, final EnumSet<Type> type); Path(final String absolute, final EnumSet<Type> type, final PathAttributes attributes); Path(final Path parent, final String name, final EnumSet<Type> type, final PathAttributes attributes); @Override T serialize(final Serializer dict); @Override EnumSet<Type> getType(); void setType(final EnumSet<Type> type); boolean isVolume(); boolean isDirectory(); boolean isPlaceholder(); boolean isFile(); boolean isSymbolicLink(); @Override char getDelimiter(); Path getParent(); PathAttributes attributes(); void setAttributes(final PathAttributes attributes); Path withAttributes(final PathAttributes attributes); @Override String getName(); @Override String getAbsolute(); Path getSymlinkTarget(); void setSymlinkTarget(final Path target); @Override int hashCode(); @Override boolean equals(Object other); @Override String toString(); boolean isChild(final Path directory); static final char DELIMITER; }### Answer:
@Test public void testPathContainer() { final Path path = new Path(new Path("test.cyberduck.ch", EnumSet.of(Path.Type.volume, Path.Type.directory)), "/test", EnumSet.of(Path.Type.directory)); assertEquals("/test.cyberduck.ch/test", path.getAbsolute()); }
|
### Question:
ChecksumComparisonService implements ComparisonService { @Override public Comparison compare(final Attributes remote, final Attributes local) { if(Checksum.NONE == remote.getChecksum()) { log.warn(String.format("No remote checksum available for comparison %s", remote)); return Comparison.unknown; } if(Checksum.NONE == local.getChecksum()) { log.warn(String.format("No local checksum available for comparison %s", local)); return Comparison.unknown; } if(remote.getChecksum().equals(local.getChecksum())) { return Comparison.equal; } return Comparison.notequal; } @Override Comparison compare(final Attributes remote, final Attributes local); }### Answer:
@Test public void testCompare() { ComparisonService s = new ChecksumComparisonService(); assertEquals(Comparison.equal, s.compare(new PathAttributes() { @Override public Checksum getChecksum() { return new Checksum(HashAlgorithm.md5, "a"); } }, new LocalAttributes("/t") { @Override public Checksum getChecksum() { return new Checksum(HashAlgorithm.md5, "a"); } } )); assertEquals(Comparison.notequal, s.compare(new PathAttributes() { @Override public Checksum getChecksum() { return new Checksum(HashAlgorithm.md5, "b"); } }, new LocalAttributes("/t") { @Override public Checksum getChecksum() { return new Checksum(HashAlgorithm.md5, "a"); } } )); }
@Test public void testDirectory() { ComparisonService s = new ChecksumComparisonService(); assertEquals(Comparison.unknown, s.compare(new PathAttributes(), new LocalAttributes("/t"))); }
|
### Question:
SizeComparisonService implements ComparisonService { @Override public Comparison compare(final Attributes remote, final Attributes local) { if(log.isDebugEnabled()) { log.debug(String.format("Compare size for %s with %s", remote, local)); } if(remote.getSize() == 0 && local.getSize() == 0) { return Comparison.equal; } if(remote.getSize() == 0) { return Comparison.local; } if(local.getSize() == 0) { return Comparison.remote; } if(remote.getSize() == local.getSize()) { return Comparison.equal; } return Comparison.notequal; } @Override Comparison compare(final Attributes remote, final Attributes local); }### Answer:
@Test public void testCompare() { ComparisonService s = new SizeComparisonService(); assertEquals(Comparison.equal, s.compare(new PathAttributes() { @Override public long getSize() { return 1L; } }, new LocalAttributes("/t") { @Override public long getSize() { return 1L; } } )); assertEquals(Comparison.notequal, s.compare(new PathAttributes() { @Override public long getSize() { return 2L; } }, new LocalAttributes("/t") { @Override public long getSize() { return 1L; } } )); }
|
### Question:
HostParser { public static Host parse(final String url) throws HostParserException { final Host parsed = new HostParser(ProtocolFactory.get(), ProtocolFactory.get().forName( preferences.getProperty("connection.protocol.default"))).get(url); if(log.isDebugEnabled()) { log.debug(String.format("Parsed %s as %s", url, parsed)); } return parsed; } HostParser(); HostParser(final ProtocolFactory factory); HostParser(final ProtocolFactory factory, final Protocol defaultScheme); Host get(final String url); static Host parse(final String url); }### Answer:
@Test public void parse() throws HostParserException { final Host host = new HostParser(new ProtocolFactory(Collections.singleton(new TestProtocol(Scheme.https)))) .get("https: assertEquals("host", host.getHostname()); assertEquals(443, host.getPort()); assertEquals("t@u", host.getCredentials().getUsername()); assertEquals("/key", host.getDefaultPath()); }
|
### Question:
HostParser { static URITypes findURIType(final StringReader reader) { final StringReader copy = reader.copy(); if(!copy.endOfString()) { char c = (char) copy.read(); if(c == '/') { reader.skip(1); if(!copy.endOfString()) { c = (char) copy.read(); if(c == '/') { reader.skip(1); return URITypes.Authority; } reader.skip(-1); } return URITypes.Absolute; } return URITypes.Rootless; } return URITypes.Undefined; } HostParser(); HostParser(final ProtocolFactory factory); HostParser(final ProtocolFactory factory, final Protocol defaultScheme); Host get(final String url); static Host parse(final String url); }### Answer:
@Test public void testFindUriType() { final Map<String, HostParser.URITypes> tests = ImmutableMap.<String, HostParser.URITypes>builder() .put("/path", HostParser.URITypes.Absolute) .put("user@domain/path", HostParser.URITypes.Rootless) .put(" .put("", HostParser.URITypes.Undefined).build(); for(Map.Entry<String, HostParser.URITypes> entry : tests.entrySet()) { final HostParser.StringReader reader = new HostParser.StringReader(entry.getKey()); assertEquals(HostParser.findURIType(reader), entry.getValue()); } }
|
### Question:
HostParser { static boolean parseScheme(final StringReader reader, final Value<String> scheme) { final StringBuilder stringBuilder = new StringBuilder(); int tracker = reader.position; while(!reader.endOfString()) { final char c = (char) reader.read(); if(Character.isAlphabetic(c) || Character.isDigit(c) || URI_SCHEME.indexOf(c) != -1) { if(c == '.') { reader.skip(tracker - reader.position); return false; } stringBuilder.append(c); } else if(c == ':') { tracker = reader.position; break; } else { if(c == ' ' && stringBuilder.length() == 0) { continue; } reader.skip(tracker - reader.position); return false; } } reader.skip(tracker - reader.position); scheme.setValue(stringBuilder.toString()); return true; } HostParser(); HostParser(final ProtocolFactory factory); HostParser(final ProtocolFactory factory, final Protocol defaultScheme); Host get(final String url); static Host parse(final String url); }### Answer:
@Test public void testParseScheme() { final HostParser.Value<String> value = new HostParser.Value<>(); final String test = "https:"; final HostParser.StringReader reader = new HostParser.StringReader(test); assertTrue(HostParser.parseScheme(reader, value)); assertEquals("https", value.getValue()); }
|
### Question:
HostParser { static void parseAbsolute(final StringReader reader, final Host host) { parsePath(reader, host, true); } HostParser(); HostParser(final ProtocolFactory factory); HostParser(final ProtocolFactory factory, final Protocol defaultScheme); Host get(final String url); static Host parse(final String url); }### Answer:
@Test public void testParseAbsolute() { final Host host = new Host(new TestProtocol()); final String path = "/path/sub/directory"; final HostParser.StringReader reader = new HostParser.StringReader(path); HostParser.parseAbsolute(reader, host); assertEquals(path, host.getDefaultPath()); }
|
### Question:
HostParser { static void parseRootless(final StringReader reader, final Host host) throws HostParserException { final boolean userInfoResult = parseUserInfo(reader, host); if(host.getProtocol().isHostnameConfigurable() && StringUtils.isWhitespace(host.getHostname())) { parseHostname(reader, host); } parsePath(reader, host, false); } HostParser(); HostParser(final ProtocolFactory factory); HostParser(final ProtocolFactory factory, final Protocol defaultScheme); Host get(final String url); static Host parse(final String url); }### Answer:
@Test public void testParseRootless() throws HostParserException { final Host host = new Host(new TestProtocol() { @Override public boolean isHostnameConfigurable() { return false; } }); final String path = "path/sub/directory"; final HostParser.StringReader reader = new HostParser.StringReader(path); HostParser.parseRootless(reader, host); assertEquals(path, host.getDefaultPath()); }
@Test public void testParseRootlessWithUser() throws HostParserException { final Host host = new Host(new TestProtocol() { @Override public boolean isHostnameConfigurable() { return false; } }); final String path = "user@path/sub/directory"; final HostParser.StringReader reader = new HostParser.StringReader(path); HostParser.parseRootless(reader, host); assertEquals("user", host.getCredentials().getUsername()); assertEquals("path/sub/directory", host.getDefaultPath()); }
|
### Question:
PathPasteboardFactory { public static PathPasteboard getPasteboard(final Host bookmark) { if(null == bookmark) { return null; } if(!pasteboards.containsKey(bookmark)) { pasteboards.put(bookmark, new PathPasteboard(bookmark)); } return pasteboards.get(bookmark); } private PathPasteboardFactory(); static PathPasteboard getPasteboard(final Host bookmark); static List<PathPasteboard> allPasteboards(); static void delete(final Host bookmark); }### Answer:
@Test public void testGetPasteboard() { final Host s = new Host(new TestProtocol(Scheme.ftp), "l"); final PathPasteboard pasteboard = PathPasteboardFactory.getPasteboard(s); assertNotNull(pasteboard); assertEquals(pasteboard, PathPasteboardFactory.getPasteboard(s)); assertSame(pasteboard, PathPasteboardFactory.getPasteboard(s)); }
|
### Question:
OverwriteFilter extends AbstractCopyFilter { @Override public boolean accept(final Path source, final Local local, final TransferStatus parent) { return true; } OverwriteFilter(final Session<?> source, final Session<?> destination, final Map<Path, Path> files); OverwriteFilter(final Session<?> source, final Session<?> destination, final Map<Path, Path> files, final UploadFilterOptions options); @Override boolean accept(final Path source, final Local local, final TransferStatus parent); }### Answer:
@Test public void testAcceptDirectoryNew() throws Exception { final HashMap<Path, Path> files = new HashMap<Path, Path>(); final Path source = new Path("a", EnumSet.of(Path.Type.directory)); files.put(source, new Path("a", EnumSet.of(Path.Type.directory))); AbstractCopyFilter f = new OverwriteFilter(new NullSession(new Host(new TestProtocol())), new NullSession(new Host(new TestProtocol())), files); assertTrue(f.accept(source, null, new TransferStatus())); }
@Test public void testAcceptDirectoryExists() throws Exception { final HashMap<Path, Path> files = new HashMap<Path, Path>(); final Path source = new Path("a", EnumSet.of(Path.Type.directory)); files.put(source, new Path("a", EnumSet.of(Path.Type.directory))); final Find find = new Find() { @Override public boolean find(final Path file) { return true; } }; AbstractCopyFilter f = new OverwriteFilter(new NullTransferSession(new Host(new TestProtocol())), new NullTransferSession(new Host(new TestProtocol())) { @Override @SuppressWarnings("unchecked") public <T> T _getFeature(final Class<T> type) { if(type.equals(Find.class)) { return (T) find; } return super._getFeature(type); } }, files); assertTrue(f.accept(source, null, new TransferStatus().exists(true))); final TransferStatus status = f.prepare(source, null, new TransferStatus().exists(true), new DisabledProgressListener()); assertTrue(status.isExists()); }
|
### Question:
AssistantUtils { @Nullable public static String getActionIntent(RootRequest rootRequest) { if (rootRequest.inputs != null && rootRequest.inputs.size() > 0) { Inputs inputs = rootRequest.inputs.get(0); return inputs.intent; } return null; } @Nullable static String getActionIntent(RootRequest rootRequest); }### Answer:
@Test public void testShouldReturnActionIntent() throws Exception { String expectedIntent = "expected_intent"; RootRequest rootRequest = TestObjects.requestWithIntent(expectedIntent); assertEquals(expectedIntent, AssistantUtils.getActionIntent(rootRequest)); }
@Test public void testActionIntent_whenNoInputs_thenShouldReturnNull() throws Exception { RootRequest rootRequest = new RootRequest(); assertNull(AssistantUtils.getActionIntent(rootRequest)); }
|
### Question:
PermissionRequestHandler extends RequestHandler { @Nullable public Location getLocation() { if (isPermissionGranted()) { return getRootRequest().device.location; } else { return null; } } protected PermissionRequestHandler(RootRequest rootRequest); boolean isPermissionGranted(); @Nullable UserProfile getUserProfile(); @Nullable Location getLocation(); }### Answer:
@Test public void testPermission_whenPermissionIsGranted_thenShouldReturnLocation() throws Exception { RootRequest rootRequest = TestObjects.permissionGrantedLocationRequest(true); PermissionRequestHandler permissionRequestHandler = new PermissionRequestHandler(rootRequest) { @Override public RootResponse getResponse() { return new RootResponse(); } }; Location location = permissionRequestHandler.getLocation(); assertNotNull(location); assertEquals(rootRequest.device.location, location); }
@Test public void testPermission_whenPermissionIsNotGranted_thenShouldntReturnLocation() throws Exception { RootRequest rootRequest = TestObjects.permissionGrantedLocationRequest(false); PermissionRequestHandler permissionRequestHandler = new PermissionRequestHandler(rootRequest) { @Override public RootResponse getResponse() { return new RootResponse(); } }; assertNull(permissionRequestHandler.getLocation()); }
|
### Question:
PermissionRequestHandler extends RequestHandler { public boolean isPermissionGranted() { RootRequest rootRequest = getRootRequest(); if (StandardIntents.PERMISSION.equals(AssistantUtils.getActionIntent(rootRequest))) { for (Argument argument : rootRequest.inputs.get(0).arguments) { if (ActionsConfig.ARG_PERMISSION_GRANTED.equals(argument.name)) { return Boolean.valueOf(argument.text_value); } } } return false; } protected PermissionRequestHandler(RootRequest rootRequest); boolean isPermissionGranted(); @Nullable UserProfile getUserProfile(); @Nullable Location getLocation(); }### Answer:
@Test public void testPermission_shouldReturnGrantedPermission() throws Exception { RootRequest rootRequest = TestObjects.permissionGrantedRequest(true); PermissionRequestHandler permissionRequestHandler = new PermissionRequestHandler(rootRequest) { @Override public RootResponse getResponse() { return new RootResponse(); } }; assertTrue(permissionRequestHandler.isPermissionGranted()); }
@Test public void testPermission_shouldReturnNotGrantedPermission() throws Exception { RootRequest rootRequest = TestObjects.permissionGrantedRequest(false); PermissionRequestHandler permissionRequestHandler = new PermissionRequestHandler(rootRequest) { @Override public RootResponse getResponse() { return new RootResponse(); } }; assertFalse(permissionRequestHandler.isPermissionGranted()); }
|
### Question:
PermissionRequestHandler extends RequestHandler { @Nullable public UserProfile getUserProfile() { if (isPermissionGranted()) { return getRootRequest().user.profile; } else { return null; } } protected PermissionRequestHandler(RootRequest rootRequest); boolean isPermissionGranted(); @Nullable UserProfile getUserProfile(); @Nullable Location getLocation(); }### Answer:
@Test public void testPermission_whenPermissionIsNotGranted_thenShouldntReturnUserProfile() throws Exception { RootRequest rootRequest = TestObjects.permissionGrantedUserProfileRequest(false); PermissionRequestHandler permissionRequestHandler = new PermissionRequestHandler(rootRequest) { @Override public RootResponse getResponse() { return new RootResponse(); } }; assertNull(permissionRequestHandler.getUserProfile()); }
@Test public void testPermission_whenPermissionIsGranted_thenShouldReturnUserProfile() throws Exception { RootRequest rootRequest = TestObjects.permissionGrantedUserProfileRequest(true); PermissionRequestHandler permissionRequestHandler = new PermissionRequestHandler(rootRequest) { @Override public RootResponse getResponse() { return new RootResponse(); } }; UserProfile userProfile = permissionRequestHandler.getUserProfile(); assertNotNull(userProfile); assertEquals(rootRequest.user.profile, userProfile); }
|
### Question:
UsersRSRedisRepository extends AbstractCacheSupport implements UsersRepository { @Override public Users findUsersByUsername(String username) { final Cache usersCache = getUsersCache(); final String key = generateUsersKey(username); Users users = (Users) getFromCache(usersCache, key); if (users == null) { users = usersRepository.findUsersByUsername(username); putToCache(usersCache, key, users); LOG.debug("Load Users[{}] from DB and cache it, key = {}", users, key); } return users; } @Override Users findUsersByUsername(String username); @Override List<Roles> findRolesByUsername(String username); }### Answer:
@Test public void findUsersByUsername() { final Users users = usersJdbcRepository.findUsersByUsername("abc"); assertNull(users); }
|
### Question:
OauthJdbcRepository extends AbstractJdbcRepository implements OauthRepository { @Override public int deleteAccessToken(final AccessToken accessToken) { final String sql = " delete from oauth_access_token where client_id = ? and username = ? and authentication_id = ?"; return jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, accessToken.clientId()); ps.setString(2, accessToken.username()); ps.setString(3, accessToken.authenticationId()); } }); } @Override ClientDetails findClientDetails(String clientId); @Override int saveClientDetails(final ClientDetails clientDetails); @Override int saveOauthCode(final OauthCode oauthCode); @Override OauthCode findOauthCode(String code, String clientId); @Override OauthCode findOauthCodeByUsernameClientId(String username, String clientId); @Override int deleteOauthCode(final OauthCode oauthCode); @Override AccessToken findAccessToken(String clientId, String username, String authenticationId); @Override int deleteAccessToken(final AccessToken accessToken); @Override int saveAccessToken(final AccessToken accessToken); @Override AccessToken findAccessTokenByRefreshToken(String refreshToken, String clientId); }### Answer:
@Test public void deleteAccessToken() { AccessToken accessToken = new AccessToken() .username("user") .authenticationId("auted") .clientId("client"); oauthJdbcRepository.deleteAccessToken(accessToken); }
|
### Question:
OauthJdbcRepository extends AbstractJdbcRepository implements OauthRepository { @Override public int saveAccessToken(final AccessToken accessToken) { final String sql = "insert into oauth_access_token(token_id,token_expired_seconds,authentication_id," + "username,client_id,token_type,refresh_token_expired_seconds,refresh_token) values (?,?,?,?,?,?,?,?) "; return jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, accessToken.tokenId()); ps.setInt(2, accessToken.tokenExpiredSeconds()); ps.setString(3, accessToken.authenticationId()); ps.setString(4, accessToken.username()); ps.setString(5, accessToken.clientId()); ps.setString(6, accessToken.tokenType()); ps.setInt(7, accessToken.refreshTokenExpiredSeconds()); ps.setString(8, accessToken.refreshToken()); } }); } @Override ClientDetails findClientDetails(String clientId); @Override int saveClientDetails(final ClientDetails clientDetails); @Override int saveOauthCode(final OauthCode oauthCode); @Override OauthCode findOauthCode(String code, String clientId); @Override OauthCode findOauthCodeByUsernameClientId(String username, String clientId); @Override int deleteOauthCode(final OauthCode oauthCode); @Override AccessToken findAccessToken(String clientId, String username, String authenticationId); @Override int deleteAccessToken(final AccessToken accessToken); @Override int saveAccessToken(final AccessToken accessToken); @Override AccessToken findAccessTokenByRefreshToken(String refreshToken, String clientId); }### Answer:
@Test public void saveAccessToken() { AccessToken accessToken = new AccessToken() .username("user") .authenticationId("auted") .clientId("client"); final int i = oauthJdbcRepository.saveAccessToken(accessToken); assertEquals(i, 1); }
|
### Question:
UsersRSRedisRepository extends AbstractCacheSupport implements UsersRepository { @Override public List<Roles> findRolesByUsername(String username) { final Cache usersCache = getUsersCache(); final String key = generateUserRolesKey(username); @SuppressWarnings("unchecked") List<Roles> rolesList = (List<Roles>) getFromCache(usersCache, key); if (rolesList == null) { rolesList = usersRepository.findRolesByUsername(username); putToCache(usersCache, key, rolesList); LOG.debug("Load User roles[{}] from DB and cache it, key = {}", rolesList, key); } return rolesList; } @Override Users findUsersByUsername(String username); @Override List<Roles> findRolesByUsername(String username); }### Answer:
@Test public void findRolesByUsername() { final List<Roles> list = usersJdbcRepository.findRolesByUsername("abcd"); assertTrue(list.isEmpty()); }
|
### Question:
UsersJdbcRepository extends AbstractJdbcRepository implements UsersRepository { @Override public Users findUsersByUsername(String username) { final String sql = " select u.* from users u where u.archived = false and u.username = ? "; final List<Users> usersList = jdbcTemplate.query(sql, usersRowMapper, username); return usersList.isEmpty() ? null : usersList.get(0); } @Override Users findUsersByUsername(String username); @Override List<Roles> findRolesByUsername(String username); }### Answer:
@Test public void findUsersByUsername() { final Users users = usersJdbcRepository.findUsersByUsername("abc"); assertNull(users); }
|
### Question:
UsersJdbcRepository extends AbstractJdbcRepository implements UsersRepository { @Override public List<Roles> findRolesByUsername(String username) { final String roleSql = " select r.* from roles r, user_roles ur, users u where u.archived = false " + " and u.id = ur.users_id and ur.roles_id = r.id and u.username = ? "; final List<Roles> rolesList = jdbcTemplate.query(roleSql, rolesRowMapper, username); for (Roles roles : rolesList) { loadRolesPermissions(roles); } return rolesList; } @Override Users findUsersByUsername(String username); @Override List<Roles> findRolesByUsername(String username); }### Answer:
@Test public void findRolesByUsername() { final List<Roles> list = usersJdbcRepository.findRolesByUsername("abcd"); assertTrue(list.isEmpty()); }
|
### Question:
OauthJdbcRepository extends AbstractJdbcRepository implements OauthRepository { @Override public ClientDetails findClientDetails(String clientId) { final String sql = " select * from oauth_client_details where archived = 0 and client_id = ? "; final List<ClientDetails> list = jdbcTemplate.query(sql, clientDetailsRowMapper, clientId); return list.isEmpty() ? null : list.get(0); } @Override ClientDetails findClientDetails(String clientId); @Override int saveClientDetails(final ClientDetails clientDetails); @Override int saveOauthCode(final OauthCode oauthCode); @Override OauthCode findOauthCode(String code, String clientId); @Override OauthCode findOauthCodeByUsernameClientId(String username, String clientId); @Override int deleteOauthCode(final OauthCode oauthCode); @Override AccessToken findAccessToken(String clientId, String username, String authenticationId); @Override int deleteAccessToken(final AccessToken accessToken); @Override int saveAccessToken(final AccessToken accessToken); @Override AccessToken findAccessTokenByRefreshToken(String refreshToken, String clientId); }### Answer:
@Test public void testFindClientDetails() throws Exception { String clientId = "oaoedd"; final ClientDetails clientDetails = oauthJdbcRepository.findClientDetails(clientId); assertNull(clientDetails); ClientDetails clientDetails1 = new ClientDetails(); clientDetails1.clientId(clientId); clientDetails1.clientSecret("Ole397dde2"); final int i = oauthJdbcRepository.saveClientDetails(clientDetails1); assertEquals(i, 1); final ClientDetails clientDetails2 = oauthJdbcRepository.findClientDetails(clientId); assertNotNull(clientDetails2); assertNotNull(clientDetails2.clientId()); }
|
### Question:
OauthJdbcRepository extends AbstractJdbcRepository implements OauthRepository { @Override public AccessToken findAccessTokenByRefreshToken(String refreshToken, String clientId) { final String sql = " select * from oauth_access_token where refresh_token = ? and client_id = ? "; final List<AccessToken> list = jdbcTemplate.query(sql, accessTokenRowMapper, refreshToken, clientId); return list.isEmpty() ? null : list.get(0); } @Override ClientDetails findClientDetails(String clientId); @Override int saveClientDetails(final ClientDetails clientDetails); @Override int saveOauthCode(final OauthCode oauthCode); @Override OauthCode findOauthCode(String code, String clientId); @Override OauthCode findOauthCodeByUsernameClientId(String username, String clientId); @Override int deleteOauthCode(final OauthCode oauthCode); @Override AccessToken findAccessToken(String clientId, String username, String authenticationId); @Override int deleteAccessToken(final AccessToken accessToken); @Override int saveAccessToken(final AccessToken accessToken); @Override AccessToken findAccessTokenByRefreshToken(String refreshToken, String clientId); }### Answer:
@Test public void findAccessTokenByRefreshToken() throws Exception { String clientId = "oaoedd"; String refreshToken = GuidGenerator.generate(); final AccessToken accessToken = oauthJdbcRepository.findAccessTokenByRefreshToken(refreshToken, clientId); assertNull(accessToken); }
|
### Question:
OauthJdbcRepository extends AbstractJdbcRepository implements OauthRepository { @Override public AccessToken findAccessToken(String clientId, String username, String authenticationId) { final String sql = " select * from oauth_access_token where client_id = ? and username = ? and authentication_id = ?"; final List<AccessToken> list = jdbcTemplate.query(sql, accessTokenRowMapper, clientId, username, authenticationId); return list.isEmpty() ? null : list.get(0); } @Override ClientDetails findClientDetails(String clientId); @Override int saveClientDetails(final ClientDetails clientDetails); @Override int saveOauthCode(final OauthCode oauthCode); @Override OauthCode findOauthCode(String code, String clientId); @Override OauthCode findOauthCodeByUsernameClientId(String username, String clientId); @Override int deleteOauthCode(final OauthCode oauthCode); @Override AccessToken findAccessToken(String clientId, String username, String authenticationId); @Override int deleteAccessToken(final AccessToken accessToken); @Override int saveAccessToken(final AccessToken accessToken); @Override AccessToken findAccessTokenByRefreshToken(String refreshToken, String clientId); }### Answer:
@Test public void findAccessToken() { final AccessToken accessToken = oauthJdbcRepository.findAccessToken("client_id", "username", "authid"); assertNull(accessToken); }
|
### Question:
BoundaryRangeValues { public BoundaryRangeValues(T lesser, T equal, T greater) { lesserValue = lesser; equalValue = equal; greaterValue = greater; } BoundaryRangeValues(T lesser, T equal, T greater); BoundaryRangeValues(final BoundaryRangeValues<T> original); @Override int hashCode(); @Override @SuppressWarnings("rawtypes") boolean equals(Object obj); @Override String toString(); final T lesserValue; final T equalValue; final T greaterValue; }### Answer:
@Test public void testBoundaryRangeValues() { assertNotNull(brv1); assertNotNull(brv2); }
|
### Question:
BoundedFloat extends AbstractBounded<Float> { public void setValue(String s) { setValue( Float.valueOf(s) ); } BoundedFloat(final Float lower, final Float initValue, final Float upper, boolean lowerStrict, boolean upperStrict); void setValue(String s); Float clamp(Float value); }### Answer:
@Test(expected=IllegalArgumentException.class) public final void testSettingInvalidValueAtLowerBound() throws Exception { bf.setValue(-1.0f); }
@Test(expected=IllegalArgumentException.class) public final void testSettingInvalidValueBelowLowerBound() throws Exception { final BoundedFloat bf3 = new BoundedFloat(-1.0f, 0.0f, 1.0f, false, true); bf3.setValue(-1.5f); }
@Test(expected=IllegalArgumentException.class) public final void testSettingInvalidValueAtUpperBound() throws Exception { final BoundedFloat bf2 = new BoundedFloat(-1.0f, 0.0f, 1.0f, false, true); bf2.setValue(1.0f); }
@Test public final void testSettingValueEqualToUpperBound() throws Exception { bf.setValue(1.0f); assertEquals("Value not as expected!", Float.valueOf(1.0f), bf.getValue()); }
@Test public final void testSettingValidValue() throws Exception { bf.setValue(0.3f); assertEquals("Value not as expected!", Float.valueOf(0.3f), bf.getValue()); }
@Test public final void testSettingValidValueWithString() throws Exception { bf.setValue("0.3"); assertEquals("Value not as expected!", Float.valueOf(0.3f), bf.getValue()); }
|
### Question:
AbstractCyEdit { public abstract void undo(); AbstractCyEdit(String presentationName); final String getPresentationName(); final String getRedoPresentationName(); final String getUndoPresentationName(); abstract void undo(); abstract void redo(); }### Answer:
@Test public final void testUndo() { saveState(); changeState(); undoableEdit.undo(); assertTrue("state is back to orginal after undo", currentStateIsIdenticalToSavedState()); }
|
### Question:
AbstractCyEdit { public abstract void redo(); AbstractCyEdit(String presentationName); final String getPresentationName(); final String getRedoPresentationName(); final String getUndoPresentationName(); abstract void undo(); abstract void redo(); }### Answer:
@Test public final void testRedo() { saveState(); changeState(); undoableEdit.undo(); undoableEdit.redo(); assertTrue("state is different from orginal after undo followed by redo", !currentStateIsIdenticalToSavedState()); }
|
### Question:
AbstractTunableInterceptor { public boolean hasTunables(final Object o) { for (final Field field : o.getClass().getFields()) { if (field.isAnnotationPresent(Tunable.class)) { return true; } else if (field.isAnnotationPresent(ContainsTunables.class)) { try { Object tunableContainer = field.get(o); return hasTunables(tunableContainer); } catch (final Throwable ex) { logger.debug("ContainsTunables field intercept failed for " + field.toString(), ex); return false; } } } for (final Method method : o.getClass().getMethods()) { if (method.isAnnotationPresent(Tunable.class)) return true; } return false; } AbstractTunableInterceptor(); final List<T> getHandlers(final Object o); boolean hasTunables(final Object o); void addTunableHandlerFactory(TunableHandlerFactory<T> thf, Map properties); void removeTunableHandlerFactory(TunableHandlerFactory<T> thf, Map properties); }### Answer:
@Test public final void testHasTunables() { assertTrue("Should have found tunables!", interceptor.hasTunables(hasAnnotatedField)); assertTrue("Should have found tunables!", interceptor.hasTunables(hasAnnotatedSetterAndGetterMethods)); }
|
### Question:
AbstractTunableInterceptor { public final List<T> getHandlers(final Object o) { if (o == null) return Collections.emptyList(); return loadTunables(o, 0.0); } AbstractTunableInterceptor(); final List<T> getHandlers(final Object o); boolean hasTunables(final Object o); void addTunableHandlerFactory(TunableHandlerFactory<T> thf, Map properties); void removeTunableHandlerFactory(TunableHandlerFactory<T> thf, Map properties); }### Answer:
@Test(expected=IllegalArgumentException.class) public final void testInvalidGetter() { interceptor.getHandlers(new HasInvalidGetter()); }
@Test(expected=IllegalArgumentException.class) public final void testInvalidGetterReturnType() { interceptor.getHandlers(new HasInvalidGetterReturnType()); }
@Test(expected=IllegalArgumentException.class) public final void testMisnamedGetter() { interceptor.getHandlers(new HasMisnamedGetter()); }
@Test(expected=IllegalArgumentException.class) public final void testInvalidSetter() { interceptor.getHandlers(new HasInvalidSetter()); }
@Test(expected=IllegalArgumentException.class) public final void testInvalidAnnotatedType() { interceptor.getHandlers(new HasInvalidAnotatedType()); }
@Test(expected=IllegalArgumentException.class) public final void testSetterAnnotatedInsteadOfGetter() { interceptor.getHandlers(new SetterAnnotatedInsteadOfGetter()); }
@Test(expected=IllegalArgumentException.class) public final void testContainsTunablesUninitialized() { Object o = new UninitializedContainsTunablesClass(); interceptor.getHandlers(o); }
@Test public final void testNullTaskObject() { List l = interceptor.getHandlers(null); assertTrue(l.isEmpty()); }
|
### Question:
ContinuousMappingPoint { public void setRange(BoundaryRangeValues<V> range) { BoundaryRangeValues<V> oldRange = this.range; if ((range == null && oldRange != null) || (range != null && !range.equals(oldRange))) { this.range = range; eventHelper.addEventPayload(parentMapping, new VisualMappingFunctionChangeRecord(), VisualMappingFunctionChangedEvent.class); } } ContinuousMappingPoint(K value, BoundaryRangeValues<V> range, final ContinuousMapping<K, V> parentMapping,
final CyEventHelper eventHelper); K getValue(); void setValue(K value); BoundaryRangeValues<V> getRange(); void setRange(BoundaryRangeValues<V> range); }### Answer:
@Test public void testSetRange() { point.setRange(brv2); assertEquals(brv2, point.getRange()); verify(eventHelper, times(1)) .addEventPayload( eq(continuousMapping), any(VisualMappingFunctionChangeRecord.class), eq(VisualMappingFunctionChangedEvent.class)); }
|
### Question:
AbstractTaskManager implements TaskManager<T,C> { @Override public TunableMutator<?,?> getTunableMutator() { return tunableMutator; } AbstractTaskManager(final TunableMutator tunableMutator); final void addTunableRecorder(TunableRecorder tunableRecorder, Map props); final void removeTunableRecorder(TunableRecorder tunableRecorder, Map props); void setExecutionContext(C context); @Override TunableMutator<?,?> getTunableMutator(); }### Answer:
@Test public void testConstructor() { assertEquals("The TunableMutator passed into the TaskMananger's constructor is not that same as that of the protected data members!", interceptor, taskManager.getTunableMutator()); }
|
### Question:
AbstractTaskManager implements TaskManager<T,C> { public final void addTunableRecorder(TunableRecorder tunableRecorder, Map props) { if ( tunableRecorder != null ) tunableRecorders.add(tunableRecorder); } AbstractTaskManager(final TunableMutator tunableMutator); final void addTunableRecorder(TunableRecorder tunableRecorder, Map props); final void removeTunableRecorder(TunableRecorder tunableRecorder, Map props); void setExecutionContext(C context); @Override TunableMutator<?,?> getTunableMutator(); }### Answer:
@Test public void testAddTunableRecorders() { taskManager.addTunableRecorder( mock(TunableRecorder.class), new Properties()); assertEquals( 1, taskManager.getNumTunableRecorders()); }
|
### Question:
AbstractTask implements Task { protected final void insertTasksAfterCurrentTask(final Task... newTasks) { taskIterator.insertTasksAfter(this, newTasks); } final void setTaskIterator(final TaskIterator taskIterator); TaskIterator getTaskIterator(); @Override abstract void run(TaskMonitor taskMonitor); @Override void cancel(); }### Answer:
@Test public final void testTaskInsertion1() throws Exception { initialTask.insertTasksAfterCurrentTask(new SimpleTask2(2), new SimpleTask2(3)); initialTask.insertTasksAfterCurrentTask(new SimpleTask2(4)); final int expectedSequence[] = { 1, 4, 2, 3 }; for (int taskId : expectedSequence) { assertTrue("Invalid task count in iterator!", iter.hasNext()); final Task task = iter.next(); assertEquals("Task ID does not match expected ID!", taskId, ((SimpleTask2)task).getId()); } assertFalse("Invalid task count in iterator!", iter.hasNext()); }
@Test public final void testTaskInsertion2() throws Exception { final TaskIterator tasks = new TaskIterator(new SimpleTask2(2), new SimpleTask2(3)); initialTask.insertTasksAfterCurrentTask(tasks); initialTask.insertTasksAfterCurrentTask(new SimpleTask2(4)); final int expectedSequence[] = { 1, 4, 2, 3 }; for (int taskId : expectedSequence) { assertTrue("Invalid task count in iterator!", iter.hasNext()); final Task task = iter.next(); assertEquals("Task ID does not match expected ID!", taskId, ((SimpleTask2)task).getId()); } assertFalse("Invalid task count in iterator!", iter.hasNext()); }
|
### Question:
VisualPropertyDependency { public VisualPropertyDependency(final String id, final String displayName, final Set<VisualProperty<T>> vpSet, final VisualLexicon lexicon) { this.id = id; this.displayName = displayName; this.vpSet = vpSet; this.enabled = false; this.parentVisualProperty = getParent(lexicon); } VisualPropertyDependency(final String id, final String displayName, final Set<VisualProperty<T>> vpSet, final VisualLexicon lexicon); String getDisplayName(); String getIdString(); Set<VisualProperty<?>> getVisualProperties(); void setDependency(boolean enable); boolean isDependencyEnabled(); VisualProperty<T> getParentVisualProperty(); void setEventHelper(CyEventHelper eventHelper); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test(expected=IllegalArgumentException.class) public void testVisualPropertyDependency() { assertNotNull(dependency); final Set<VisualProperty<Paint>> badSet = new HashSet<VisualProperty<Paint>>(); badSet.add(BasicVisualLexicon.EDGE_LABEL_COLOR); badSet.add(BasicVisualLexicon.NODE_FILL_COLOR); final VisualPropertyDependency<Paint> badDependency = new VisualPropertyDependency<Paint>(id, displayName, badSet, lexicon); }
|
### Question:
AbstractTask implements Task { @Override public void cancel() { cancelled = true; } final void setTaskIterator(final TaskIterator taskIterator); TaskIterator getTaskIterator(); @Override abstract void run(TaskMonitor taskMonitor); @Override void cancel(); }### Answer:
@Test public final void testCancellation() throws Exception { final SimpleTask2 task = new SimpleTask2(1); assertFalse("\"cancelled\" must start out set to false!", task.cancelled()); task.cancel(); assertTrue("\"cancelled\" must be true after a call to cancel()!", task.cancelled()); }
|
### Question:
SUIDFactory { public static long getNextSUID() { return count.incrementAndGet(); } private SUIDFactory(); static long getNextSUID(); }### Answer:
@Test public void testPointless1() { assertTrue(SUIDFactory.getNextSUID() != SUIDFactory.getNextSUID()); }
@Test public void testPointless2() { assertTrue(SUIDFactory.getNextSUID() < SUIDFactory.getNextSUID()); }
|
### Question:
ColumnNameChangedEvent extends AbstractCyEvent<CyTable> { public String getOldColumnName() { return oldColumnName; } ColumnNameChangedEvent(final CyTable source, final String oldColumnName, final String newColumnName); String getOldColumnName(); String getOldNamespace(); String getOldNameOnly(); String getNewColumnName(); String getNewNamespace(); String getNewNameOnly(); }### Answer:
@Test public void testGetOldColumnName() { assertEquals(event.getOldColumnName(), oldColumnName); }
|
### Question:
ColumnNameChangedEvent extends AbstractCyEvent<CyTable> { public String getNewColumnName() { return newColumnName; } ColumnNameChangedEvent(final CyTable source, final String oldColumnName, final String newColumnName); String getOldColumnName(); String getOldNamespace(); String getOldNameOnly(); String getNewColumnName(); String getNewNamespace(); String getNewNameOnly(); }### Answer:
@Test public void testGetNewColumnName() { assertEquals(event.getNewColumnName(), newColumnName); }
|
### Question:
AbstractNetworkEvent extends AbstractCyEvent<CyNetworkManager> { public final CyNetwork getNetwork() { return net; } AbstractNetworkEvent(final CyNetworkManager source, final Class<?> listenerClass, final CyNetwork net); final CyNetwork getNetwork(); }### Answer:
@Test public final void testGetNetwork() { final CyNetworkManager networkManager = mock(CyNetworkManager.class); final CyNetwork network = mock(CyNetwork.class); final AbstractNetworkEvent event = new AbstractNetworkEvent(networkManager, Object.class, network); assertEquals("Network returned by getNetwork() is *not* the one passed into the constructor!", network, event.getNetwork()); }
|
### Question:
TableAddedEvent extends AbstractCyEvent<CyTableManager> { public final CyTable getTable() { return table; } TableAddedEvent(final CyTableManager source, final CyTable table); final CyTable getTable(); }### Answer:
@Test public final void testGetTable() { final TableAddedEvent event = new TableAddedEvent(tableManager, table); assertEquals("TableManager returned by getSource() is *not* the one passed into the constructor!", tableManager, event.getSource()); assertEquals("Table returned by getTable() is *not* the one passed into the constructor!", table, event.getTable()); }
|
### Question:
RowsDeletedEvent extends AbstractCyEvent<CyTable> { public Collection<Object> getKeys() { return keys; } RowsDeletedEvent(CyTable source, Collection<Object> primaryKeys); Collection<Object> getKeys(); }### Answer:
@Test public void testGetKeys() { for ( Object n : event.getKeys() ) assertTrue( pkCollection.contains(n)); }
|
### Question:
TableAboutToBeDeletedEvent extends AbstractCyEvent<CyTableManager> { public final CyTable getTable() { return table; } TableAboutToBeDeletedEvent(final CyTableManager source, final CyTable table); final CyTable getTable(); }### Answer:
@Test public final void testGetTable() { final CyTableManager tableManager = mock(CyTableManager.class); final CyTable table = mock(CyTable.class); final TableAboutToBeDeletedEvent event = new TableAboutToBeDeletedEvent(tableManager, table); assertEquals("TableManager returned by getSource() is *not* the one passed into the constructor!", tableManager, event.getSource()); assertEquals("Table returned by getTable() is *not* the one passed into the constructor!", table, event.getTable()); }
|
### Question:
DropDownMenuButton extends JButton { public DropDownMenuButton(AbstractAction action) { this(); setAction(action); } DropDownMenuButton(AbstractAction action); DropDownMenuButton(JPopupMenu popupMenu); DropDownMenuButton(); @Override void paintComponent(Graphics g); void setPopupMenu(JPopupMenu popupMenu); @Override Dimension getPreferredSize(); }### Answer:
@Test public void testDropDownMenuButton() { assertNotNull(action); }
|
### Question:
VisualPropertyDependency { public String getDisplayName() { return displayName; } VisualPropertyDependency(final String id, final String displayName, final Set<VisualProperty<T>> vpSet, final VisualLexicon lexicon); String getDisplayName(); String getIdString(); Set<VisualProperty<?>> getVisualProperties(); void setDependency(boolean enable); boolean isDependencyEnabled(); VisualProperty<T> getParentVisualProperty(); void setEventHelper(CyEventHelper eventHelper); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testGetDisplayName() { assertEquals(displayName, dependency.getDisplayName()); }
|
### Question:
ColumnResizer { public static void adjustColumnPreferredWidths(final JTable table) { adjustColumnPreferredWidths(table, true); } private ColumnResizer(); static void adjustColumnPreferredWidths(final JTable table); static void adjustColumnPreferredWidths(final JTable table, final boolean checkAllRows); static void adjustColumnPreferredWidth(final JTable table, final int col); static void adjustColumnPreferredWidth(final JTable table, final int col, final boolean checkAllRows); }### Answer:
@Test public void testAdjustColumnPreferredWidths() { JTable table = new JTable(); final TableColumn col = new TableColumn(); col.setHeaderValue("Test"); col.setWidth(1); int w = col.getWidth(); table.addColumn(col); ColumnResizer.adjustColumnPreferredWidths(table); assertTrue(table.getColumn("Test").getWidth() == w); }
|
### Question:
JTreeTable extends JTable { @Override public void updateUI() { super.updateUI(); if (tree != null) tree.updateUI(); LookAndFeel.installColorsAndFont(this, "Tree.background", "Tree.foreground", "Tree.font"); } JTreeTable(final TreeTableModel treeTableModel); @Override String getToolTipText(MouseEvent event); @Override void updateUI(); @Override int getEditingRow(); void setRowHeight(int rowHeight); JTree getTree(); }### Answer:
@Test public void testUpdateUI() { table.updateUI(); }
|
### Question:
JTreeTable extends JTable { public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); if ((tree != null) && (tree.getRowHeight() != rowHeight)) { tree.setRowHeight(getRowHeight()); } } JTreeTable(final TreeTableModel treeTableModel); @Override String getToolTipText(MouseEvent event); @Override void updateUI(); @Override int getEditingRow(); void setRowHeight(int rowHeight); JTree getTree(); }### Answer:
@Test public void testSetRowHeightInt() { table.setRowHeight(100); assertEquals(100, table.getRowHeight()); }
|
### Question:
JTreeTable extends JTable { @Override public int getEditingRow() { return (getColumnClass(editingColumn) == TreeTableModel.class) ? (-1) : editingRow; } JTreeTable(final TreeTableModel treeTableModel); @Override String getToolTipText(MouseEvent event); @Override void updateUI(); @Override int getEditingRow(); void setRowHeight(int rowHeight); JTree getTree(); }### Answer:
@Test public void testGetEditingRow() { assertEquals(-1,table.getEditingRow()); }
|
### Question:
JTreeTable extends JTable { public JTreeTable(final TreeTableModel treeTableModel) { super(); tree = new TreeTableCellRenderer(treeTableModel); super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); setShowGrid(false); setIntercellSpacing(new Dimension(0, 0)); if (tree.getRowHeight() < 1) { setRowHeight(18); } } JTreeTable(final TreeTableModel treeTableModel); @Override String getToolTipText(MouseEvent event); @Override void updateUI(); @Override int getEditingRow(); void setRowHeight(int rowHeight); JTree getTree(); }### Answer:
@Test public void testJTreeTable() { assertNotNull(table); assertTrue(table.getModel() instanceof TreeTableModelAdapter); }
|
### Question:
JTreeTable extends JTable { @Override public String getToolTipText(MouseEvent event) { String tip = null; Point p = event.getPoint(); int hitColumnIndex = columnAtPoint(p); int hitRowIndex = rowAtPoint(p); if ((hitColumnIndex != -1) && (hitRowIndex != -1)) { TableCellRenderer renderer = getCellRenderer(hitRowIndex, hitColumnIndex); Component component = prepareRenderer(renderer, hitRowIndex, hitColumnIndex); if (component instanceof JComponent) { Rectangle cellRect = getCellRect(hitRowIndex, hitColumnIndex, false); p.translate(-cellRect.x, 0); MouseEvent newEvent = new MouseEvent(component, event.getID(), event.getWhen(), event.getModifiers(), p.x, p.y, event.getClickCount(), event.isPopupTrigger()); tip = ((JComponent) component).getToolTipText(newEvent); } } if (tip == null) tip = getToolTipText(); return tip; } JTreeTable(final TreeTableModel treeTableModel); @Override String getToolTipText(MouseEvent event); @Override void updateUI(); @Override int getEditingRow(); void setRowHeight(int rowHeight); JTree getTree(); }### Answer:
@Test public void testGetToolTipTextMouseEvent() { when(mouseEvent.getPoint()).thenReturn(new Point(10, 20)); table.setToolTipText("test"); assertEquals("test", table.getToolTipText(mouseEvent)); }
|
### Question:
JTreeTable extends JTable { public JTree getTree() { return tree; } JTreeTable(final TreeTableModel treeTableModel); @Override String getToolTipText(MouseEvent event); @Override void updateUI(); @Override int getEditingRow(); void setRowHeight(int rowHeight); JTree getTree(); }### Answer:
@Test public void testGetTree() { assertNotNull(table.getTree()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.