method2testcases
stringlengths 118
3.08k
|
---|
### Question:
CryptorCache { public String hashDirectoryId(final String cleartextDirectoryId) { if(!directoryIdCache.contains(cleartextDirectoryId)) { directoryIdCache.put(cleartextDirectoryId, impl.hashDirectoryId(cleartextDirectoryId)); } return directoryIdCache.get(cleartextDirectoryId); } CryptorCache(final FileNameCryptor impl); String hashDirectoryId(final String cleartextDirectoryId); String encryptFilename(final BaseEncoding encoding, final String cleartextName, final byte[] associatedData); String decryptFilename(final BaseEncoding encoding, final String ciphertextName, final byte[] associatedData); static final BaseEncoding BASE32; }### Answer:
@Test public void TestHashDirectoryId() { final FileNameCryptor mock = mock(FileNameCryptor.class); final CryptorCache cryptor = new CryptorCache(mock); when(mock.hashDirectoryId(anyString())).thenReturn("hashed"); assertEquals("hashed", cryptor.hashDirectoryId("id")); assertEquals("hashed", cryptor.hashDirectoryId("id")); verify(mock, times(1)).hashDirectoryId(anyString()); verifyNoMoreInteractions(mock); }
|
### Question:
RotatingNonceGenerator implements NonceGenerator { @Override public byte[] next() { if(index >= capacity) { index = 0; } if(nonces.size() <= index) { final byte[] nonce = new byte[len]; random.nextBytes(nonce); nonces.add(nonce); } return nonces.get(index++); } RotatingNonceGenerator(final int capacity); @Override byte[] next(); @Override String toString(); }### Answer:
@Test public void testRotation() { final RotatingNonceGenerator generator = new RotatingNonceGenerator(2); final byte[] r1 = generator.next(); final byte[] r2 = generator.next(); final byte[] r3 = generator.next(); assertFalse(Arrays.equals(r1, r2)); assertArrayEquals(r1, r3); }
|
### Question:
CryptoDirectoryV7Provider extends CryptoDirectoryV6Provider { @Override public String toEncrypted(final Session<?> session, final String directoryId, final String filename, final EnumSet<Path.Type> type) throws BackgroundException { final String ciphertextName = cryptomator.getFileNameCryptor().encryptFilename(BaseEncoding.base64Url(), filename, directoryId.getBytes(StandardCharsets.UTF_8)) + EXTENSION_REGULAR; if(log.isDebugEnabled()) { log.debug(String.format("Encrypted filename %s to %s", filename, ciphertextName)); } return cryptomator.getFilenameProvider().deflate(session, ciphertextName); } CryptoDirectoryV7Provider(final Path vault, final CryptoVault cryptomator); @Override String toEncrypted(final Session<?> session, final String directoryId, final String filename, final EnumSet<Path.Type> type); static final String EXTENSION_REGULAR; static final String FILENAME_DIRECTORYID; static final String DIRECTORY_METADATAFILE; }### Answer:
@Test(expected = NotfoundException.class) public void testToEncryptedInvalidArgument() throws Exception { final Path home = new Path("/vault", EnumSet.of(Path.Type.directory)); final CryptoVault vault = new CryptoVault(home); final CryptoDirectory provider = new CryptoDirectoryV7Provider(home, vault); provider.toEncrypted(new NullSession(new Host(new TestProtocol())), null, new Path("/vault/f", EnumSet.of(Path.Type.file))); }
@Test(expected = NotfoundException.class) public void testToEncryptedInvalidPath() throws Exception { final Path home = new Path("/vault", EnumSet.of(Path.Type.directory)); final CryptoVault vault = new CryptoVault(home); final CryptoDirectory provider = new CryptoDirectoryV7Provider(home, vault); provider.toEncrypted(new NullSession(new Host(new TestProtocol())), null, new Path("/", EnumSet.of(Path.Type.directory))); }
|
### Question:
CryptoDirectoryV6Provider implements CryptoDirectory { @Override public String toEncrypted(final Session<?> session, final String directoryId, final String filename, final EnumSet<Path.Type> type) throws BackgroundException { final String prefix = type.contains(Path.Type.directory) ? CryptoVault.DIR_PREFIX : ""; final String ciphertextName = prefix + cryptomator.getFileNameCryptor().encryptFilename(CryptorCache.BASE32, filename, directoryId.getBytes(StandardCharsets.UTF_8)); if(log.isDebugEnabled()) { log.debug(String.format("Encrypted filename %s to %s", filename, ciphertextName)); } return cryptomator.getFilenameProvider().deflate(session, ciphertextName); } CryptoDirectoryV6Provider(final Path vault, final CryptoVault cryptomator); @Override String toEncrypted(final Session<?> session, final String directoryId, final String filename, final EnumSet<Path.Type> type); @Override Path toEncrypted(final Session<?> session, final String directoryId, final Path directory); void delete(final Path directory); @Override void destroy(); }### Answer:
@Test(expected = NotfoundException.class) public void testToEncryptedInvalidArgument() throws Exception { final Path home = new Path("/vault", EnumSet.of(Path.Type.directory)); final CryptoVault vault = new CryptoVault(home); final CryptoDirectory provider = new CryptoDirectoryV6Provider(home, vault); provider.toEncrypted(new NullSession(new Host(new TestProtocol())), null, new Path("/vault/f", EnumSet.of(Path.Type.file))); }
@Test(expected = NotfoundException.class) public void testToEncryptedInvalidPath() throws Exception { final Path home = new Path("/vault", EnumSet.of(Path.Type.directory)); final CryptoVault vault = new CryptoVault(home); final CryptoDirectory provider = new CryptoDirectoryV6Provider(home, vault); provider.toEncrypted(new NullSession(new Host(new TestProtocol())), null, new Path("/", EnumSet.of(Path.Type.directory))); }
|
### Question:
SpectraReadFeature implements Read { @Override public boolean offset(final Path file) { return false; } SpectraReadFeature(final SpectraSession session); SpectraReadFeature(final SpectraSession session, final SpectraBulkService bulk); @Override InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback); @Override boolean offset(final Path file); }### Answer:
@Test public void testOffsetSupport() { final Host host = new Host(new SpectraProtocol() { @Override public Scheme getScheme() { return Scheme.http; } }, System.getProperties().getProperty("spectra.hostname"), Integer.valueOf(System.getProperties().getProperty("spectra.port")), new Credentials( System.getProperties().getProperty("spectra.user"), System.getProperties().getProperty("spectra.key") )); final SpectraSession session = new SpectraSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager()); assertFalse(new SpectraReadFeature(session).offset(null)); }
|
### Question:
S3MoveFeature implements Move { @Override public boolean isSupported(final Path source, final Path target) { return !containerService.isContainer(source); } S3MoveFeature(final S3Session session); S3MoveFeature(final S3Session session, final S3AccessControlListFeature accessControlListFeature); @Override Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback); @Override boolean isSupported(final Path source, final Path target); }### Answer:
@Test public void testSupport() { final Path c = new Path("/c", EnumSet.of(Path.Type.directory)); assertFalse(new S3MoveFeature(null).isSupported(c, c)); final Path cf = new Path("/c/f", EnumSet.of(Path.Type.directory)); assertTrue(new S3MoveFeature(null).isSupported(cf, cf)); }
|
### Question:
SpectraProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", SpectraProtocol.class.getPackage().getName(), "Spectra"); } @Override String getName(); @Override String getDescription(); @Override String getIdentifier(); @Override boolean isPortConfigurable(); @Override Scheme getScheme(); @Override Type getType(); @Override String getPrefix(); @Override boolean isHostnameConfigurable(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override String disk(); @Override String getAuthorization(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.spectra.Spectra", new SpectraProtocol().getPrefix()); }
|
### Question:
SpectraTouchFeature implements Touch { @Override public boolean isSupported(final Path workdir, final String filename) { return !workdir.isRoot(); } SpectraTouchFeature(final SpectraSession session); @Override Path touch(final Path file, final TransferStatus transferStatus); @Override boolean isSupported(final Path workdir, final String filename); @Override SpectraTouchFeature withWriter(final Write writer); }### Answer:
@Test public void testFile() { final Host host = new Host(new SpectraProtocol() { @Override public Scheme getScheme() { return Scheme.http; } }, System.getProperties().getProperty("spectra.hostname"), Integer.valueOf(System.getProperties().getProperty("spectra.port")), new Credentials( System.getProperties().getProperty("spectra.user"), System.getProperties().getProperty("spectra.key") )); final SpectraSession session = new SpectraSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager()); assertFalse(new SpectraTouchFeature(session).isSupported(new Path("/", EnumSet.of(Path.Type.volume)), StringUtils.EMPTY)); assertTrue(new SpectraTouchFeature(session).isSupported(new Path(new Path("/", EnumSet.of(Path.Type.volume)), "/container", EnumSet.of(Path.Type.volume)), StringUtils.EMPTY)); }
|
### Question:
S3MetadataFeature implements Headers { @Override public Map<String, String> getMetadata(final Path file) throws BackgroundException { return new S3AttributesFinderFeature(session).find(file).getMetadata(); } S3MetadataFeature(final S3Session session, final S3AccessControlListFeature accessControlListFeature); @Override Map<String, String> getDefault(final Local local); @Override Map<String, String> getMetadata(final Path file); @Override void setMetadata(final Path file, final TransferStatus status); }### Answer:
@Test public void testGetMetadataBucket() throws Exception { final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume)); final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session)).getMetadata(container); assertTrue(metadata.isEmpty()); }
@Test public void testGetMetadataFile() throws Exception { final Path container = new Path("versioning-test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume)); final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new S3TouchFeature(session).touch(test, new TransferStatus().withMime("text/plain")); final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session)).getMetadata(test); new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(metadata.isEmpty()); assertTrue(metadata.containsKey("Content-Type")); assertEquals("text/plain", metadata.get("Content-Type")); assertFalse(metadata.containsKey(Constants.KEY_FOR_USER_METADATA)); assertFalse(metadata.containsKey(Constants.KEY_FOR_SERVICE_METADATA)); assertFalse(metadata.containsKey(Constants.KEY_FOR_COMPLETE_METADATA)); }
|
### Question:
IRODSFindFeature implements Find { @Override public boolean find(final Path file) throws BackgroundException { if(file.isRoot()) { return true; } try { final IRODSFileSystemAO fs = session.getClient(); final IRODSFile f = fs.getIRODSFileFactory().instanceIRODSFile(file.getAbsolute()); return fs.isFileExists(f); } catch(JargonException e) { throw new IRODSExceptionMappingService().map("Failure to read attributes of {0}", e, file); } } IRODSFindFeature(IRODSSession session); @Override boolean find(final Path file); }### Answer:
@Test public void testFind() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile")); final Host host = new Host(profile, profile.getDefaultHostname(), new Credentials( System.getProperties().getProperty("irods.key"), System.getProperties().getProperty("irods.secret") )); final IRODSSession session = new IRODSSession(host); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); final Path test = new Path(new IRODSHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); session.getFeature(Directory.class).mkdir(test, null, new TransferStatus()); assertTrue(new IRODSFindFeature(session).find(test)); session.getFeature(Delete.class).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new IRODSFindFeature(session).find(test)); session.close(); }
|
### Question:
IRODSExceptionMappingService extends AbstractExceptionMappingService<JargonException> { @Override public BackgroundException map(final JargonException e) { final StringBuilder buffer = new StringBuilder(); this.append(buffer, e.getMessage()); if(e instanceof CatNoAccessException) { return new AccessDeniedException(buffer.toString(), e); } if(e instanceof FileNotFoundException) { return new NotfoundException(buffer.toString(), e); } if(e instanceof DataNotFoundException) { return new NotfoundException(buffer.toString(), e); } if(e instanceof AuthenticationException) { return new LoginFailureException(buffer.toString(), e); } if(e instanceof InvalidUserException) { return new LoginFailureException(buffer.toString(), e); } if(e instanceof InvalidGroupException) { return new LoginFailureException(buffer.toString(), e); } return this.wrap(e, buffer); } @Override BackgroundException map(final JargonException e); }### Answer:
@Test public void testMap() { assertTrue(new IRODSExceptionMappingService().map(new CatNoAccessException("no access")) instanceof AccessDeniedException); assertTrue(new IRODSExceptionMappingService().map(new FileNotFoundException("no file")) instanceof NotfoundException); assertTrue(new IRODSExceptionMappingService().map(new AuthenticationException("no user")) instanceof LoginFailureException); }
|
### Question:
S3Protocol extends AbstractProtocol { @Override public Scheme getScheme() { return Scheme.https; } @Override String getName(); @Override String getDescription(); @Override String getIdentifier(); @Override Scheme getScheme(); @Override boolean isHostnameConfigurable(); @Override boolean isPortConfigurable(); @Override String getDefaultHostname(); @Override Set<Location.Name> getRegions(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override String getTokenPlaceholder(); @Override String favicon(); @Override String getAuthorization(); @Override CredentialsConfigurator getCredentialsFinder(); @Override DirectoryTimestamp getDirectoryTimestamp(); }### Answer:
@Test public void testScheme() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new S3Protocol()))); final Profile profile = new ProfilePlistReader(factory).read( new Local("../profiles/Verizon Cloud Storage (AMS1A).cyberduckprofile")); assertTrue(profile.isSecure()); assertEquals(Scheme.https, profile.getScheme()); }
|
### Question:
IRODSProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", IRODSProtocol.class.getPackage().getName(), StringUtils.upperCase(this.getType().name())); } @Override String getIdentifier(); @Override String getDescription(); @Override Statefulness getStatefulness(); @Override Scheme getScheme(); @Override String disk(); @Override String getPrefix(); }### Answer:
@Test public void testGetPrefix() { assertEquals("ch.cyberduck.core.irods.IRODS", new IRODSProtocol().getPrefix()); }
|
### Question:
IRODSTouchFeature implements Touch { @Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { try { final IRODSFileSystemAO fs = session.getClient(); final int descriptor = fs.createFile(file.getAbsolute(), DataObjInp.OpenFlags.WRITE_TRUNCATE, DataObjInp.DEFAULT_CREATE_MODE); fs.fileClose(descriptor, false); return new Path(file.getParent(), file.getName(), file.getType(), new IRODSAttributesFinderFeature(session).find(file)); } catch(JargonException e) { throw new IRODSExceptionMappingService().map("Cannot create file {0}", e, file); } } IRODSTouchFeature(final IRODSSession session); @Override Path touch(final Path file, final TransferStatus status); @Override Touch withWriter(final Write writer); }### Answer:
@Test public void testTouch() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile")); final Host host = new Host(profile, profile.getDefaultHostname(), new Credentials( System.getProperties().getProperty("irods.key"), System.getProperties().getProperty("irods.secret") )); final IRODSSession session = new IRODSSession(host); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); final Path test = new Path(new IRODSHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new IRODSTouchFeature(session).touch(test, new TransferStatus()); assertTrue(new IRODSFindFeature(session).find(test)); new IRODSDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new IRODSFindFeature(session).find(test)); session.close(); }
|
### Question:
FireFtpBookmarkCollection extends ThirdpartyBookmarkCollection { protected void read(final ProtocolFactory protocols, final Local file) throws AccessDeniedException { try (final BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) { String l; while((l = in.readLine()) != null) { Matcher array = Pattern.compile("\\[(.*?)\\]").matcher(l); while(array.find()) { Matcher entries = Pattern.compile("\\{(.*?)\\}").matcher(array.group(1)); while(entries.find()) { final String entry = entries.group(1); this.read(protocols, entry); } } } } catch(IOException e) { throw new AccessDeniedException(e.getMessage(), e); } } @Override String getBundleIdentifier(); @Override String getName(); @Override Local getFile(); }### Answer:
@Test(expected = AccessDeniedException.class) public void testParseNotFound() throws Exception { new FireFtpBookmarkCollection().read(new ProtocolFactory(Collections.emptySet()), new Local(System.getProperty("java.io.tmpdir"), "f")); }
|
### Question:
FireFtpBookmarkCollection extends ThirdpartyBookmarkCollection { @Override protected void parse(final ProtocolFactory protocols, final Local folder) throws AccessDeniedException { for(Local settings : folder.list().filter(new NullFilter<Local>() { @Override public boolean accept(Local file) { return file.isDirectory(); } })) { for(Local child : settings.list().filter(new NullFilter<Local>() { @Override public boolean accept(Local file) { if(file.isFile()) { return "fireFTPsites.dat".equals(file.getName()); } return false; } })) { this.read(protocols, child); } } } @Override String getBundleIdentifier(); @Override String getName(); @Override Local getFile(); }### Answer:
@Test public void testParse() throws Exception { FireFtpBookmarkCollection c = new FireFtpBookmarkCollection(); assertEquals(0, c.size()); c.parse(new ProtocolFactory(new HashSet<>(Arrays.asList(new TestProtocol(Scheme.ftp), new TestProtocol(Scheme.ftps), new TestProtocol(Scheme.sftp)))), new Local("src/test/resources/org.mozdev.fireftp")); assertEquals(1, c.size()); }
|
### Question:
SmartFtpBookmarkCollection extends XmlBookmarkCollection { @Override protected void parse(final ProtocolFactory protocols, final Local folder) throws AccessDeniedException { for(Local child : folder.list().filter(new Filter<Local>() { @Override public boolean accept(Local file) { if(file.isDirectory()) { return true; } return "xml".equals(file.getExtension()); } @Override public Pattern toPattern() { return Pattern.compile(".*\\.xml"); } })) { if(child.isDirectory()) { this.parse(protocols, child); } else { this.read(protocols, child); } } } @Override String getBundleIdentifier(); @Override String getName(); @Override Local getFile(); }### Answer:
@Test(expected = AccessDeniedException.class) public void testParse() throws Exception { new SmartFtpBookmarkCollection().read(new ProtocolFactory(), new Local(System.getProperty("java.io.tmpdir"), "f")); }
|
### Question:
Transmit4BookmarkCollection extends XmlBookmarkCollection { @Override public Local getFile() { return LocalFactory.get(PreferencesFactory.get().getProperty("bookmark.import.transmit4.location")); } @Override Local getFile(); @Override String getBundleIdentifier(); @Override String getName(); }### Answer:
@Test public void testGetFile() throws Exception { Transmit4BookmarkCollection c = new Transmit4BookmarkCollection(); assertEquals(0, c.size()); c.parse(new ProtocolFactory(new HashSet<>(Arrays.asList(new TestProtocol(Scheme.ftp), new TestProtocol(Scheme.ftps), new TestProtocol(Scheme.sftp), new TestProtocol(Scheme.davs)))), new Local("src/test/resources/Favorites.xml")); assertEquals(3, c.size()); }
|
### Question:
WsFtpBookmarkCollection extends ThirdpartyBookmarkCollection { protected void read(final ProtocolFactory protocols, Local file) throws AccessDeniedException { try (final BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) { Host current = null; String line; while((line = in.readLine()) != null) { log.trace(line); if(line.startsWith("[")) { this.add(current); current = new Host(protocols.forScheme(Scheme.ftp)); current.getCredentials().setUsername( PreferencesFactory.get().getProperty("connection.login.anon.name")); Pattern pattern = Pattern.compile("\\[(.*)\\]"); Matcher matcher = pattern.matcher(line); if(matcher.matches()) { current.setNickname(matcher.group(1)); } } else if(StringUtils.isBlank(line)) { this.add(current); } else { if(null == current) { log.warn("Failed to detect start of bookmark"); continue; } this.parse(protocols, current, line); } } } catch(IOException e) { log.error(e.getMessage()); } } @Override String getBundleIdentifier(); @Override String getName(); @Override Local getFile(); @Override boolean add(Host bookmark); }### Answer:
@Test(expected = AccessDeniedException.class) public void testParseNotFound() throws Exception { new WsFtpBookmarkCollection().read(new ProtocolFactory(), new Local(System.getProperty("java.io.tmpdir"), "f")); }
|
### Question:
HubicProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", HubicProtocol.class.getPackage().getName(), "Hubic"); } @Override String getIdentifier(); @Override String getDescription(); @Override Scheme getScheme(); @Override Type getType(); @Override String getPrefix(); @Override String getDefaultHostname(); @Override boolean isHostnameConfigurable(); @Override boolean isPortConfigurable(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override boolean isUsernameConfigurable(); @Override boolean isPasswordConfigurable(); @Override String disk(); @Override String icon(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.hubic.Hubic", new HubicProtocol().getPrefix()); }
|
### Question:
NSImageIconCache implements IconCache<NSImage> { @Override public NSImage documentIcon(final String extension, final Integer size) { NSImage image = this.load(extension, size); if(null == image) { return this.cache(extension, this.convert(extension, NSWorkspace.sharedWorkspace().iconForFileType(extension), size), size); } return image; } @Override NSImage documentIcon(final String extension, final Integer size); @Override NSImage documentIcon(final String extension, final Integer size, final NSImage badge); @Override NSImage folderIcon(final Integer size); @Override NSImage folderIcon(final Integer size, final NSImage badge); @Override NSImage iconNamed(final String name, final Integer width, final Integer height); @Override NSImage fileIcon(final Local file, final Integer size); @Override NSImage applicationIcon(final Application app, final Integer size); @Override NSImage fileIcon(final Path file, final Integer size); @Override NSImage aliasIcon(final String extension, final Integer size); }### Answer:
@Test public void testDocumentIcon() { final NSImage icon = new NSImageIconCache().documentIcon("txt", 64); assertNotNull(icon); assertTrue(icon.isValid()); assertFalse(icon.isTemplate()); assertEquals(64, icon.size().width.intValue()); assertEquals(64, icon.size().height.intValue()); assertNotNull(NSImage.imageNamed("txt (64px)")); }
@Test public void testDocumentIconNoExtension() { final NSImage icon = new NSImageIconCache().documentIcon("", 64); assertNotNull(icon); assertTrue(icon.isValid()); assertFalse(icon.isTemplate()); assertEquals(64, icon.size().width.intValue()); assertEquals(64, icon.size().height.intValue()); }
@Test public void testDocumentIconNullExtension() { final NSImage icon = new NSImageIconCache().documentIcon(null, 64); assertNotNull(icon); assertTrue(icon.isValid()); assertFalse(icon.isTemplate()); assertEquals(64, icon.size().width.intValue()); assertEquals(64, icon.size().height.intValue()); }
|
### Question:
BundleLocale implements Locale { @Override public String localize(final String key, final String table) { final String identifier = String.format("%s.%s", table, key); if(!cache.contains(identifier)) { cache.put(identifier, bundle.localizedString(key, table)); } return cache.get(identifier); } BundleLocale(); BundleLocale(final NSBundle bundle); @Override String localize(final String key, final String table); @Override void setDefault(final String language); }### Answer:
@Test public void testGet() { assertEquals("Il y a eu un problème lors de la recherche de mises à jour", new BundleLocale().localize("Il y a eu un problème lors de la recherche de mises à jour", "Localizable")); }
|
### Question:
SFCertificatePanel extends NSPanel { public static SFCertificatePanel sharedCertificatePanel() { return Rococoa.createClass("SFCertificatePanel", SFCertificatePanel._Class.class).sharedCertificatePanel(); } static SFCertificatePanel sharedCertificatePanel(); abstract void beginSheetForWindow_modalDelegate_didEndSelector_contextInfo_certificates_showGroup(
NSWindow docWindow, ID delegate, Selector didEndSelector, PointerByReference contextInfo, NSArray certificates, boolean showGroup); abstract void setAlternateButtonTitle(String title); abstract void setDefaultButtonTitle(String title); abstract void setShowsHelp(final boolean showsHelp); }### Answer:
@Test public void sharedCertificatePanel() { assertNotNull(SFCertificatePanel.sharedCertificatePanel()); }
|
### Question:
SFCertificateTrustPanel extends SFCertificatePanel { public static SFCertificateTrustPanel sharedCertificateTrustPanel() { return Rococoa.createClass("SFCertificateTrustPanel", SFCertificateTrustPanel._Class.class).sharedCertificateTrustPanel(); } static SFCertificateTrustPanel sharedCertificateTrustPanel(); abstract void beginSheetForWindow_modalDelegate_didEndSelector_contextInfo_trust_message(
NSWindow docWindow, ID delegate, Selector didEndSelector, PointerByReference contextInfo, SecTrustRef trust, String message); abstract NSInteger runModalForTrust_message(SecTrustRef trust, String message); abstract void setInformativeText(String informativeText); abstract void setPolicies(SecPolicyRef policies); }### Answer:
@Test public void sharedCertificateTrustPanel() { assertNotNull(SFCertificateTrustPanel.sharedCertificateTrustPanel()); }
|
### Question:
SFChooseIdentityPanel extends NSPanel { public static SFChooseIdentityPanel sharedChooseIdentityPanel() { return Rococoa.createClass("SFChooseIdentityPanel", SFChooseIdentityPanel._Class.class).sharedChooseIdentityPanel(); } static SFChooseIdentityPanel sharedChooseIdentityPanel(); abstract void setDomain(String domainString); abstract void setAlternateButtonTitle(String title); abstract void setDefaultButtonTitle(String title); abstract void setPolicies(SecPolicyRef policies); abstract void setInformativeText(String text); abstract void beginSheetForWindow_modalDelegate_didEndSelector_contextInfo_identities_message(
NSWindow docWindow, ID delegate, Selector didEndSelector, PointerByReference contextInfo, NSArray identities, String message); abstract NSInteger runModalForIdentities_message(NSArray identities, String message); abstract SecIdentityRef identity(); abstract void setShowsHelp(final boolean showsHelp); }### Answer:
@Test public void sharedChooseIdentityPanel() { assertNotNull(SFChooseIdentityPanel.sharedChooseIdentityPanel()); }
|
### Question:
SystemConfigurationProxy extends AbstractProxyFinder implements ProxyFinder { @Override public Proxy find(final Host target) { if(!preferences.getBoolean("connection.proxy.enable")) { return Proxy.DIRECT; } final String route = this.findNative(provider.get(target)); if(null == route) { if(log.isInfoEnabled()) { log.info(String.format("No proxy configuration found for target %s", target)); } return Proxy.DIRECT; } final URI proxy; try { proxy = new URI(route); try { return new Proxy(Proxy.Type.valueOf(StringUtils.upperCase(proxy.getScheme())), proxy.getHost(), proxy.getPort()); } catch(IllegalArgumentException e) { log.warn(String.format("Unsupported scheme for proxy %s", proxy)); } } catch(URISyntaxException e) { log.warn(String.format("Invalid proxy configuration %s", route)); } return Proxy.DIRECT; } @Override Proxy find(final Host target); native String findNative(String target); }### Answer:
@Test public void testFind() { final SystemConfigurationProxy proxy = new SystemConfigurationProxy(); assertEquals(Proxy.Type.DIRECT, proxy.find(new Host(new TestProtocol(), "cyberduck.io")).getType()); }
@Test public void testExcludedLocalHost() { final SystemConfigurationProxy proxy = new SystemConfigurationProxy(); assertEquals(Proxy.Type.DIRECT, proxy.find(new Host(new TestProtocol(), "cyberduck.local")).getType()); }
@Test public void testSimpleExcluded() { final SystemConfigurationProxy proxy = new SystemConfigurationProxy(); assertEquals(Proxy.Type.DIRECT, proxy.find(new Host(new TestProtocol(), "simple")).getType()); }
|
### Question:
LaunchServicesSchemeHandler extends AbstractSchemeHandler { private native void setDefaultHandlerForURLScheme(String scheme, String bundleIdentifier); LaunchServicesSchemeHandler(); LaunchServicesSchemeHandler(final ApplicationFinder applicationFinder); @Override void setDefaultHandler(final Application application, final List<String> schemes); @Override Application getDefaultHandler(final String scheme); @Override List<Application> getAllHandlers(final String scheme); }### Answer:
@Test public void testSetDefaultHandlerForURLScheme() { final SchemeHandler l = new LaunchServicesSchemeHandler(new LaunchServicesApplicationFinder()); l.setDefaultHandler( new Application("none.app", null), Collections.singletonList(Scheme.ftp.name()) ); assertEquals(Application.notfound, l.getDefaultHandler(Scheme.ftp.name())); assertFalse(l.isDefaultHandler(Collections.singletonList(Scheme.ftp.name()), new Application("other.app", null))); l.setDefaultHandler( new Application("ch.sudo.cyberduck", null), Collections.singletonList(Scheme.ftp.name()) ); assertEquals("ch.sudo.cyberduck", l.getDefaultHandler(Scheme.ftp.name()).getIdentifier()); assertNotSame("ch.sudo.cyberduck", l.getDefaultHandler(Scheme.http.name()).getIdentifier()); assertTrue(l.isDefaultHandler(Collections.singletonList(Scheme.ftp.name()), new Application("ch.sudo.cyberduck", null))); }
|
### Question:
Sandbox { public native boolean isSandboxed(); static Sandbox get(); native boolean isSandboxed(); }### Answer:
@Test public void testIsSandboxed() { assertFalse(new Sandbox().isSandboxed()); }
|
### Question:
Updater extends NSObject { public static Updater create(final String useragent) { if(null == CLASS) { return null; } final Updater updater = CLASS.sharedUpdater(); updater.setAutomaticallyChecksForUpdates(false); updater.setUserAgentString(useragent); updater.setSendsSystemProfile(false); return updater; } static Updater create(final String useragent); abstract Updater init(); abstract void setDelegate(ID delegate); abstract void checkForUpdates(ID sender); abstract void checkForUpdatesInBackground(); abstract void setFeedURL(NSURL url); abstract void setUserAgentString(String userAgentString); abstract void setSendsSystemProfile(boolean sendsSystemProfile); abstract void setAutomaticallyChecksForUpdates(boolean automaticallyChecks); abstract void setAutomaticallyDownloadsUpdates(boolean automaticallyDownloadsUpdates); abstract boolean validateMenuItem(NSMenuItem menuItem); abstract boolean updateInProgress(); }### Answer:
@Test public void testCreate() { assertNotNull(Updater.create("None")); }
|
### Question:
SparklePeriodicUpdateChecker extends AbstractPeriodicUpdateChecker { @Override public void check(boolean background) { if(this.hasUpdatePrivileges()) { updater.setFeedURL(NSURL.URLWithString(this.getFeedUrl())); if(background) { updater.checkForUpdatesInBackground(); } else { updater.checkForUpdates(null); } } } SparklePeriodicUpdateChecker(final Controller controller); @Override void check(boolean background); @Override boolean hasUpdatePrivileges(); @Override boolean isUpdateInProgress(final Object item); }### Answer:
@Test public void testCheck() { final SparklePeriodicUpdateChecker updater = new SparklePeriodicUpdateChecker(new ProxyController()); updater.check(false); }
|
### Question:
IOKitSleepPreventer implements SleepPreventer { @Override public void release(final String id) { synchronized(lock) { this.releaseAssertion(id); } } @Override String lock(); @Override void release(final String id); }### Answer:
@Test public void testRelease() { final SleepPreventer s = new IOKitSleepPreventer(); final String lock = s.lock(); Assert.assertNotNull(lock); s.release(lock); }
|
### Question:
QuartzQuickLook implements QuickLook { @Override public void select(final List<Local> files) { if(log.isDebugEnabled()) { log.debug(String.format("Select files for %s", files)); } previews.clear(); for(final Local selected : files) { previews.add(new QLPreviewItem() { @Override public NSURL previewItemURL() { return NSURL.fileURLWithPath(selected.getAbsolute()); } @Override public String previewItemTitle() { return selected.getDisplayName(); } }); } } @Override void select(final List<Local> files); @Override boolean isOpen(); @Override void open(); @Override void close(); }### Answer:
@Test public void testSelect() { QuickLook q = new QuartzQuickLook(); final List<Local> files = new ArrayList<Local>(); files.add(new NullLocal("f")); files.add(new NullLocal("b")); q.select(files); }
|
### Question:
SystemLogAppender extends AppenderSkeleton { @Override protected void append(final LoggingEvent event) { if(null == event.getMessage()) { return; } final StringBuilder buffer = new StringBuilder(); buffer.append(layout.format(event)); if(layout.ignoresThrowable()) { final String[] trace = event.getThrowableStrRep(); if(trace != null) { buffer.append(Layout.LINE_SEP); for(final String t : trace) { buffer.append(t).append(Layout.LINE_SEP); } } } library.NSLog("%@", buffer.toString()); } @Override void close(); @Override boolean requiresLayout(); }### Answer:
@Test public void testAppend() { final SystemLogAppender a = new SystemLogAppender(); a.setLayout(new SimpleLayout()); a.append(new LoggingEvent("f", Logger.getLogger(SystemLogAppender.class), Level.ERROR, "Test", new RuntimeException())); }
|
### Question:
FSEventWatchEditorFactory extends EditorFactory { @Override public List<Application> getConfigured() { return editors; } FSEventWatchEditorFactory(); FSEventWatchEditorFactory(final ApplicationFinder finder); @Override List<Application> getConfigured(); @Override Editor create(final ProgressListener listener, final SessionPool session, final Application application, final Path file); }### Answer:
@Test public void getGetConfigured() { final FSEventWatchEditorFactory f = new FSEventWatchEditorFactory(new LaunchServicesApplicationFinder()); final List<Application> e = f.getConfigured(); assertFalse(e.isEmpty()); }
|
### Question:
FetchBookmarkCollection extends ThirdpartyBookmarkCollection { @Override protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException { NSDictionary serialized = NSDictionary.dictionaryWithContentsOfFile(file.getAbsolute()); if(null == serialized) { throw new LocalAccessDeniedException(String.format("Invalid bookmark file %s", file)); } NSDictionary dict = new PlistDeserializer(serialized).objectForKey("Shortcuts v2"); if(null == dict) { throw new LocalAccessDeniedException(String.format("Invalid bookmark file %s", file)); } dict = new PlistDeserializer(dict).objectForKey("Shortcuts"); if(null == dict) { throw new LocalAccessDeniedException(String.format("Invalid bookmark file %s", file)); } List<NSDictionary> shortcuts = new PlistDeserializer(dict).listForKey("Shortcuts"); for(NSDictionary shortcut : shortcuts) { PlistDeserializer reader = new PlistDeserializer(shortcut); NSDictionary remote = reader.objectForKey("Remote Item"); if(null == remote) { continue; } NSDictionary location = new PlistDeserializer(remote).objectForKey("Location"); if(null == location) { continue; } String url = new PlistDeserializer(location).stringForKey("URL"); if(null == url) { continue; } final Host host; try { host = new HostParser(protocols).get(url); } catch(HostParserException e) { log.warn(e); continue; } host.setNickname(reader.stringForKey("Name")); this.add(host); } } @Override String getBundleIdentifier(); @Override String getName(); @Override Local getFile(); }### Answer:
@Test(expected = AccessDeniedException.class) public void testParseNotFound() throws Exception { new FetchBookmarkCollection().parse(new ProtocolFactory(Collections.emptySet()), new Local(System.getProperty("java.io.tmpdir"), "f")); }
|
### Question:
FetchBookmarkCollection extends ThirdpartyBookmarkCollection { @Override public Local getFile() { return LocalFactory.get(PreferencesFactory.get().getProperty("bookmark.import.fetch.location")); } @Override String getBundleIdentifier(); @Override String getName(); @Override Local getFile(); }### Answer:
@Test public void testGetFile() throws Exception { FetchBookmarkCollection c = new FetchBookmarkCollection(); assertEquals(0, c.size()); c.parse(new ProtocolFactory(new HashSet<>(Arrays.asList(new TestProtocol(Scheme.ftp), new TestProtocol(Scheme.ftps), new TestProtocol(Scheme.sftp)))), new Local("src/test/resources/com.fetchsoftworks.Fetch.Shortcuts.plist")); assertEquals(2, c.size()); }
|
### Question:
Transmit5BookmarkCollection extends ThirdpartyBookmarkCollection { @Override protected void parse(final ProtocolFactory protocols, final Local folder) throws AccessDeniedException { for(Local f : folder.list().filter(new NullFilter<Local>() { @Override public boolean accept(Local file) { if(file.isFile()) { return "favoriteMetadata".equals(file.getExtension()); } return false; } })) { this.read(protocols, f); } } @Override Local getFile(); @Override String getBundleIdentifier(); @Override String getName(); String getConfiguration(); }### Answer:
@Test(expected = AccessDeniedException.class) public void testParseNotFound() throws Exception { new Transmit5BookmarkCollection().parse(new ProtocolFactory(Collections.emptySet()), new Local(System.getProperty("java.io.tmpdir"), "f")); }
@Test public void testParse() throws AccessDeniedException { Transmit5BookmarkCollection c = new Transmit5BookmarkCollection(); assertEquals(0, c.size()); c.parse(new ProtocolFactory(new HashSet<>(Collections.singletonList(new TestProtocol(Scheme.sftp)))), new Local("src/test/resources/")); assertEquals(1, c.size()); }
|
### Question:
FlowBookmarkCollection extends ThirdpartyBookmarkCollection { @Override protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException { NSDictionary serialized = NSDictionary.dictionaryWithContentsOfFile(file.getAbsolute()); if(null == serialized) { throw new LocalAccessDeniedException(String.format("Invalid bookmark file %s", file)); } this.parse(protocols, serialized); } @Override String getBundleIdentifier(); @Override String getName(); @Override Local getFile(); }### Answer:
@Test(expected = AccessDeniedException.class) public void testParseNotFound() throws Exception { new FlowBookmarkCollection().parse(new ProtocolFactory(Collections.emptySet()), new Local(System.getProperty("java.io.tmpdir"), "f")); }
@Test public void testParse() throws AccessDeniedException { FlowBookmarkCollection c = new FlowBookmarkCollection(); assertEquals(0, c.size()); c.parse(new ProtocolFactory(new HashSet<>(Arrays.asList(new TestProtocol(Scheme.ftp), new TestProtocol(Scheme.ftps), new TestProtocol(Scheme.https)))), new Local("src/test/resources/com.fivedetails.Bookmarks.plist")); assertEquals(3, c.size()); }
|
### Question:
SystemConfigurationReachability implements Reachability { @Override public Monitor monitor(final Host bookmark, final Callback callback) { final String url = this.toURL(bookmark); return new Reachability.Monitor() { private final CDReachabilityMonitor monitor = CDReachabilityMonitor.monitorForUrl(url); private final NotificationFilterCallback listener = new NotificationFilterCallback(callback); @Override public Monitor start() { notificationCenter.addObserver(listener.id(), Foundation.selector("notify:"), "kNetworkReachabilityChangedNotification", monitor.id()); monitor.startReachabilityMonitor(); return this; } @Override public Monitor stop() { monitor.stopReachabilityMonitor(); notificationCenter.removeObserver(listener.id()); return this; } }; } SystemConfigurationReachability(); @Override Monitor monitor(final Host bookmark, final Callback callback); @Override boolean isReachable(final Host bookmark); @Override void diagnose(final Host bookmark); }### Answer:
@Test public void testMonitor() { final Reachability r = new SystemConfigurationReachability(); final Reachability.Monitor monitor = r.monitor(new Host(new TestProtocol(), "cyberduck.ch", 80), new Reachability.Callback() { @Override public void change() { } } ).start(); assertSame(monitor, monitor.stop()); }
|
### Question:
WorkspaceApplicationLauncher implements ApplicationLauncher { @Override public boolean open(final Local file) { synchronized(NSWorkspace.class) { if(!workspace.openFile(file.getAbsolute())) { log.warn(String.format("Error opening file %s", file)); return false; } return true; } } void register(final Application application, final ApplicationQuitCallback callback); @Override boolean open(final Local file); @Override boolean open(final Local file, final Application application, final ApplicationQuitCallback callback); @Override boolean open(final Application application, final String args); @Override void bounce(final Local file); }### Answer:
@Test public void testOpen() throws Exception { new WorkspaceApplicationLauncher().open(new NullLocal("t")); final NullLocal file = new NullLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); LocalTouchFactory.get().touch(file); new WorkspaceApplicationLauncher().open(file); file.delete(); }
|
### Question:
WorkspaceApplicationLauncher implements ApplicationLauncher { @Override public void bounce(final Local file) { synchronized(NSWorkspace.class) { NSDistributedNotificationCenter.defaultCenter().postNotification( NSNotification.notificationWithName("com.apple.DownloadFileFinished", file.getAbsolute()) ); } } void register(final Application application, final ApplicationQuitCallback callback); @Override boolean open(final Local file); @Override boolean open(final Local file, final Application application, final ApplicationQuitCallback callback); @Override boolean open(final Application application, final String args); @Override void bounce(final Local file); }### Answer:
@Test public void testBounce() throws Exception { new WorkspaceApplicationLauncher().bounce(new NullLocal("t")); final NullLocal file = new NullLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); LocalTouchFactory.get().touch(file); new WorkspaceApplicationLauncher().bounce(file); file.delete(); }
|
### Question:
LaunchServicesFileDescriptor extends AbstractFileDescriptor { @Override public String getKind(final String filename) { if(StringUtils.isBlank(Path.getExtension(filename))) { final String kind = this.kind(filename); if(StringUtils.isBlank(kind)) { return LocaleFactory.localizedString("Unknown"); } return kind; } final String kind = this.kind(Path.getExtension(filename)); if(StringUtils.isBlank(kind)) { return LocaleFactory.localizedString("Unknown"); } return kind; } @Override String getKind(final String filename); }### Answer:
@Test public void testGetKind() { assertNotNull(new LaunchServicesFileDescriptor().getKind("/tmp/t.txt")); }
@Test public void testGetKindWithoutExtension() { assertNotNull(new LaunchServicesFileDescriptor().getKind("txt")); }
|
### Question:
LaunchServicesApplicationFinder implements ApplicationFinder { @Override public List<Application> findAll(final String filename) { final String extension = Path.getExtension(filename); if(StringUtils.isEmpty(extension)) { return Collections.emptyList(); } if(!defaultApplicationListCache.contains(extension)) { final List<Application> applications = new ArrayList<Application>(); for(String identifier : this.findAllForType(extension)) { applications.add(this.getDescription(identifier)); } final Application defaultApplication = this.find(filename); if(this.isInstalled(defaultApplication)) { if(!applications.contains(defaultApplication)) { applications.add(defaultApplication); } } defaultApplicationListCache.put(extension, applications); } return defaultApplicationListCache.get(extension); } LaunchServicesApplicationFinder(); @Override List<Application> findAll(final String filename); @Override Application find(final String filename); @Override Application getDescription(final String search); @Override boolean isInstalled(final Application application); boolean register(final Local application); }### Answer:
@Test public void testFindAll() { ApplicationFinder f = new LaunchServicesApplicationFinder(); final List<Application> applications = f.findAll("file.txt"); assertFalse(applications.isEmpty()); assertTrue(applications.contains(new Application("com.apple.TextEdit", "T"))); }
|
### Question:
LaunchServicesApplicationFinder implements ApplicationFinder { @Override public Application find(final String filename) { final String extension = Path.getExtension(filename); if(!defaultApplicationCache.contains(extension)) { if(StringUtils.isEmpty(extension)) { return Application.notfound; } final String path = this.findForType(extension); if(StringUtils.isEmpty(path)) { defaultApplicationCache.put(extension, Application.notfound); } else { final NSBundle bundle = NSBundle.bundleWithPath(path); if(null == bundle) { log.error(String.format("Loading bundle %s failed", path)); defaultApplicationCache.put(extension, Application.notfound); } else { defaultApplicationCache.put(extension, this.getDescription(bundle.bundleIdentifier())); } } } return defaultApplicationCache.get(extension); } LaunchServicesApplicationFinder(); @Override List<Application> findAll(final String filename); @Override Application find(final String filename); @Override Application getDescription(final String search); @Override boolean isInstalled(final Application application); boolean register(final Local application); }### Answer:
@Test public void testFindByFilename() { ApplicationFinder f = new LaunchServicesApplicationFinder(); assertEquals(new Application("com.apple.Preview", "Preview"), f.find("file.png")); assertEquals(Application.notfound, f.find("file.txt_")); }
|
### Question:
LaunchServicesApplicationFinder implements ApplicationFinder { @Override public boolean isInstalled(final Application application) { synchronized(NSWorkspace.class) { if(Application.notfound.equals(application)) { return false; } return NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier( application.getIdentifier()) != null; } } LaunchServicesApplicationFinder(); @Override List<Application> findAll(final String filename); @Override Application find(final String filename); @Override Application getDescription(final String search); @Override boolean isInstalled(final Application application); boolean register(final Local application); }### Answer:
@Test public void testInstalled() { ApplicationFinder f = new LaunchServicesApplicationFinder(); assertTrue(f.isInstalled(new Application("com.apple.Preview", "Preview"))); assertFalse(f.isInstalled(new Application("com.apple.Preview_", "Preview"))); assertFalse(f.isInstalled(Application.notfound)); }
|
### Question:
WorkspaceIconService implements IconService { protected boolean update(final Local file, final NSImage icon) { synchronized(NSWorkspace.class) { final NSWorkspace workspace = NSWorkspace.sharedWorkspace(); if(workspace.setIcon_forFile_options(icon, file.getAbsolute(), new NSUInteger(0))) { workspace.noteFileSystemChanged(new NFDNormalizer().normalize(file.getAbsolute()).toString()); return true; } return false; } } @Override boolean set(final Local file, final String image); @Override boolean set(final Local file, final TransferStatus status); @Override boolean remove(final Local file); }### Answer:
@Test public void testSetProgressNoFile() { final WorkspaceIconService s = new WorkspaceIconService(); final Local file = new Local(PreferencesFactory.get().getProperty("tmp.dir"), UUID.randomUUID().toString()); assertFalse(s.update(file, NSImage.imageWithContentsOfFile("../../img/download0.icns"))); }
@Test public void testSetProgressFolder() throws Exception { final WorkspaceIconService s = new WorkspaceIconService(); final Local file = new Local(PreferencesFactory.get().getProperty("tmp.dir"), UUID.randomUUID().toString()); new DefaultLocalDirectoryFeature().mkdir(file); assertTrue(s.update(file, NSImage.imageWithContentsOfFile("../../img/download0.icns"))); }
@Test public void testSetProgress() throws Exception { final WorkspaceIconService s = new WorkspaceIconService(); final Local file = new Local(PreferencesFactory.get().getProperty("tmp.dir"), UUID.randomUUID().toString()); LocalTouchFactory.get().touch(file); assertTrue(s.update(file, NSImage.imageWithContentsOfFile("../../img/download0.icns"))); file.delete(); }
|
### Question:
WorkspaceIconService implements IconService { @Override public boolean remove(final Local file) { return this.update(file, null); } @Override boolean set(final Local file, final String image); @Override boolean set(final Local file, final TransferStatus status); @Override boolean remove(final Local file); }### Answer:
@Test public void testRemove() throws Exception { final WorkspaceIconService s = new WorkspaceIconService(); final Local file = new Local(PreferencesFactory.get().getProperty("tmp.dir"), UUID.randomUUID().toString()); assertFalse(s.remove(file)); LocalTouchFactory.get().touch(file); assertFalse(s.remove(file)); assertTrue(s.update(file, NSImage.imageWithContentsOfFile("../../img/download0.icns"))); assertTrue(s.remove(file)); file.delete(); }
|
### Question:
FinderLocal extends Local { @Override public InputStream getInputStream() throws AccessDeniedException { final NSURL resolved; try { resolved = this.lock(false); if(null == resolved) { return super.getInputStream(); } } catch(LocalAccessDeniedException e) { log.warn(String.format("Failure obtaining lock for %s. %s", this, e)); return super.getInputStream(); } return new LockReleaseProxyInputStream(super.getInputStream(resolved.path()), resolved); } FinderLocal(final Local parent, final String name); FinderLocal(final Local parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String parent, final String name); FinderLocal(final String parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String path); FinderLocal(final String name, final FilesystemBookmarkResolver<NSURL> resolver); @Override T serialize(final Serializer dict); @Override String getDisplayName(); @Override String getAbbreviatedPath(); @Override Local getVolume(); @Override boolean exists(final LinkOption... options); @Override String getBookmark(); @Override void setBookmark(final String data); @Override AttributedList<Local> list(final Filter<String> filter); @Override OutputStream getOutputStream(boolean append); @Override NSURL lock(final boolean interactive); @Override void release(final Object lock); @Override InputStream getInputStream(); @Override FinderLocalAttributes attributes(); }### Answer:
@Test(expected = LocalAccessDeniedException.class) public void testReadNoFile() throws Exception { final String name = UUID.randomUUID().toString(); FinderLocal l = new FinderLocal(System.getProperty("java.io.tmpdir"), name); l.getInputStream(); }
|
### Question:
FinderLocal extends Local { @Override public AttributedList<Local> list(final Filter<String> filter) throws AccessDeniedException { final NSURL resolved; try { resolved = this.lock(true); if(null == resolved) { return super.list(filter); } final AttributedList<Local> list = super.list(resolved.path(), filter); this.release(resolved); return list; } catch(LocalAccessDeniedException e) { log.warn(String.format("Failure obtaining lock for %s. %s", this, e)); return super.list(filter); } } FinderLocal(final Local parent, final String name); FinderLocal(final Local parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String parent, final String name); FinderLocal(final String parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String path); FinderLocal(final String name, final FilesystemBookmarkResolver<NSURL> resolver); @Override T serialize(final Serializer dict); @Override String getDisplayName(); @Override String getAbbreviatedPath(); @Override Local getVolume(); @Override boolean exists(final LinkOption... options); @Override String getBookmark(); @Override void setBookmark(final String data); @Override AttributedList<Local> list(final Filter<String> filter); @Override OutputStream getOutputStream(boolean append); @Override NSURL lock(final boolean interactive); @Override void release(final Object lock); @Override InputStream getInputStream(); @Override FinderLocalAttributes attributes(); }### Answer:
@Test public void testList() throws Exception { assertFalse(new FinderLocal("../../profiles").list().isEmpty()); }
@Test(expected = LocalAccessDeniedException.class) public void testListNotFound() throws Exception { final String name = UUID.randomUUID().toString(); FinderLocal l = new FinderLocal(System.getProperty("java.io.tmpdir"), name); l.list(); }
|
### Question:
FinderLocal extends Local { @Override public String getAbbreviatedPath() { return new TildeExpander().abbreviate(this.getAbsolute()); } FinderLocal(final Local parent, final String name); FinderLocal(final Local parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String parent, final String name); FinderLocal(final String parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String path); FinderLocal(final String name, final FilesystemBookmarkResolver<NSURL> resolver); @Override T serialize(final Serializer dict); @Override String getDisplayName(); @Override String getAbbreviatedPath(); @Override Local getVolume(); @Override boolean exists(final LinkOption... options); @Override String getBookmark(); @Override void setBookmark(final String data); @Override AttributedList<Local> list(final Filter<String> filter); @Override OutputStream getOutputStream(boolean append); @Override NSURL lock(final boolean interactive); @Override void release(final Object lock); @Override InputStream getInputStream(); @Override FinderLocalAttributes attributes(); }### Answer:
@Test public void testTilde() { assertEquals(System.getProperty("user.home") + "/f", new FinderLocal("~/f").getAbsolute()); assertEquals("~/f", new FinderLocal("~/f").getAbbreviatedPath()); }
|
### Question:
FinderLocal extends Local { @Override public String getDisplayName() { return NSFileManager.defaultManager().displayNameAtPath(this.getName()); } FinderLocal(final Local parent, final String name); FinderLocal(final Local parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String parent, final String name); FinderLocal(final String parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String path); FinderLocal(final String name, final FilesystemBookmarkResolver<NSURL> resolver); @Override T serialize(final Serializer dict); @Override String getDisplayName(); @Override String getAbbreviatedPath(); @Override Local getVolume(); @Override boolean exists(final LinkOption... options); @Override String getBookmark(); @Override void setBookmark(final String data); @Override AttributedList<Local> list(final Filter<String> filter); @Override OutputStream getOutputStream(boolean append); @Override NSURL lock(final boolean interactive); @Override void release(final Object lock); @Override InputStream getInputStream(); @Override FinderLocalAttributes attributes(); }### Answer:
@Test public void testDisplayName() { assertEquals("f/a", new FinderLocal(System.getProperty("java.io.tmpdir"), "f:a").getDisplayName()); }
|
### Question:
FinderLocal extends Local { @Override public FinderLocalAttributes attributes() { return new FinderLocalAttributes(this); } FinderLocal(final Local parent, final String name); FinderLocal(final Local parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String parent, final String name); FinderLocal(final String parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String path); FinderLocal(final String name, final FilesystemBookmarkResolver<NSURL> resolver); @Override T serialize(final Serializer dict); @Override String getDisplayName(); @Override String getAbbreviatedPath(); @Override Local getVolume(); @Override boolean exists(final LinkOption... options); @Override String getBookmark(); @Override void setBookmark(final String data); @Override AttributedList<Local> list(final Filter<String> filter); @Override OutputStream getOutputStream(boolean append); @Override NSURL lock(final boolean interactive); @Override void release(final Object lock); @Override InputStream getInputStream(); @Override FinderLocalAttributes attributes(); }### Answer:
@Test public void testWriteUnixPermission() throws Exception { Local l = new FinderLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); new DefaultLocalTouchFeature().touch(l); final Permission permission = new Permission(644); l.attributes().setPermission(permission); assertEquals(permission, l.attributes().getPermission()); l.delete(); }
|
### Question:
FinderLocal extends Local { @Override public String getBookmark() { final String path = this.getAbbreviatedPath(); String bookmark = PreferencesFactory.get().getProperty(String.format("local.bookmark.%s", path)); if(StringUtils.isBlank(bookmark)) { try { bookmark = resolver.create(this); } catch(AccessDeniedException e) { log.warn(String.format("Failure resolving bookmark for %s. %s", this, e)); } } return bookmark; } FinderLocal(final Local parent, final String name); FinderLocal(final Local parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String parent, final String name); FinderLocal(final String parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String path); FinderLocal(final String name, final FilesystemBookmarkResolver<NSURL> resolver); @Override T serialize(final Serializer dict); @Override String getDisplayName(); @Override String getAbbreviatedPath(); @Override Local getVolume(); @Override boolean exists(final LinkOption... options); @Override String getBookmark(); @Override void setBookmark(final String data); @Override AttributedList<Local> list(final Filter<String> filter); @Override OutputStream getOutputStream(boolean append); @Override NSURL lock(final boolean interactive); @Override void release(final Object lock); @Override InputStream getInputStream(); @Override FinderLocalAttributes attributes(); }### Answer:
@Test public void testBookmark() throws Exception { FinderLocal l = new FinderLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString(), new AliasFilesystemBookmarkResolver()); assertNull(l.getBookmark()); new DefaultLocalTouchFeature().touch(l); assertNotNull(l.getBookmark()); assertEquals(l.getBookmark(), l.getBookmark()); l.delete(); }
|
### Question:
FinderLocal extends Local { @Override public NSURL lock(final boolean interactive) throws AccessDeniedException { final NSURL resolved = resolver.resolve(this, interactive); if(null == resolved) { return null; } if(resolved.respondsToSelector(Foundation.selector("startAccessingSecurityScopedResource"))) { if(!resolved.startAccessingSecurityScopedResource()) { throw new LocalAccessDeniedException(String.format("Failure accessing security scoped resource for %s", this)); } } return resolved; } FinderLocal(final Local parent, final String name); FinderLocal(final Local parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String parent, final String name); FinderLocal(final String parent, final String name, final FilesystemBookmarkResolver<NSURL> resolver); FinderLocal(final String path); FinderLocal(final String name, final FilesystemBookmarkResolver<NSURL> resolver); @Override T serialize(final Serializer dict); @Override String getDisplayName(); @Override String getAbbreviatedPath(); @Override Local getVolume(); @Override boolean exists(final LinkOption... options); @Override String getBookmark(); @Override void setBookmark(final String data); @Override AttributedList<Local> list(final Filter<String> filter); @Override OutputStream getOutputStream(boolean append); @Override NSURL lock(final boolean interactive); @Override void release(final Object lock); @Override InputStream getInputStream(); @Override FinderLocalAttributes attributes(); }### Answer:
@Test public void testLockNoSuchFile() throws Exception { FinderLocal l = new FinderLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); assertNull(l.lock(false)); }
|
### Question:
WorkspaceBrowserLauncher implements BrowserLauncher { @Override public boolean open(final String url) { synchronized(NSWorkspace.class) { if(StringUtils.isNotBlank(url)) { if(NSWorkspace.sharedWorkspace().openURL(NSURL.URLWithString(url))) { return true; } log.warn(String.format("Failure opening URL %s with browser", url)); } return false; } } @Override boolean open(final String url); }### Answer:
@Test public void testOpen() { assertFalse(new WorkspaceBrowserLauncher().open("")); assertFalse(new WorkspaceBrowserLauncher().open(null)); }
|
### Question:
WorkspaceSymlinkFeature implements Symlink { @Override public void symlink(final Local file, final String target) throws AccessDeniedException { final ObjCObjectByReference error = new ObjCObjectByReference(); final boolean success = NSFileManager.defaultManager().createSymbolicLinkAtPath_withDestinationPath_error( file.getAbsolute(), target, error); if(!success) { final NSError f = error.getValueAs(NSError.class); if(null == f) { throw new LocalAccessDeniedException(String.format("%s %s", LocaleFactory.localizedString("Cannot create file", "Error"), file.getAbsolute())); } throw new LocalAccessDeniedException(String.format("%s", f.localizedDescription())); } if(log.isDebugEnabled()) { log.debug(String.format("Created symbolic link %s with target %s", file, target)); } } @Override void symlink(final Local file, final String target); }### Answer:
@Test public void testSymlink() throws Exception { final Local target = new Local(PreferencesFactory.get().getProperty("tmp.dir"), UUID.randomUUID().toString()); new DefaultLocalTouchFeature().touch(target); final Local symlink = new Local(PreferencesFactory.get().getProperty("tmp.dir"), UUID.randomUUID().toString()); assertFalse(symlink.exists()); new WorkspaceSymlinkFeature().symlink(symlink, target.getAbsolute()); assertTrue(symlink.exists()); target.delete(); symlink.delete(); }
|
### Question:
WorkspaceApplicationBadgeLabeler implements ApplicationBadgeLabeler { @Override public void badge(final String label) { synchronized(NSWorkspace.class) { NSApplication.sharedApplication().dockTile().setBadgeLabel(label); } } @Override void badge(final String label); }### Answer:
@Test public void testBadge() { new WorkspaceApplicationBadgeLabeler().badge("1"); }
|
### Question:
LaunchServicesQuarantineService implements QuarantineService { @Override public void setQuarantine(final Local file, final String originUrl, final String dataUrl) throws LocalAccessDeniedException { if(StringUtils.isEmpty(originUrl)) { log.warn("No origin url given for quarantine"); return; } if(StringUtils.isEmpty(dataUrl)) { log.warn("No data url given for quarantine"); return; } synchronized(lock) { if(!this.setQuarantine(file.getAbsolute(), originUrl, dataUrl)) { throw new LocalAccessDeniedException(file.getAbsolute()); } } } @Override void setQuarantine(final Local file, final String originUrl, final String dataUrl); @Override void setWhereFrom(final Local file, final String dataUrl); }### Answer:
@Test public void testSetQuarantineEmptyUrl() throws Exception { final QuarantineService q = new LaunchServicesQuarantineService(); q.setQuarantine(new NullLocal("/", "n"), null, null); q.setQuarantine(new NullLocal("/", "n"), StringUtils.EMPTY, StringUtils.EMPTY); }
@Test public void testSetQuarantine() throws Exception { final QuarantineService q = new LaunchServicesQuarantineService(); Callable<Local> c = new Callable<Local>() { @Override public Local call() throws Exception { final NullLocal l = new NullLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); LocalTouchFactory.get().touch(l); q.setQuarantine(l, "http: l.delete(); return l; } }; c.call(); }
|
### Question:
LaunchServicesQuarantineService implements QuarantineService { @Override public void setWhereFrom(final Local file, final String dataUrl) throws LocalAccessDeniedException { synchronized(lock) { if(StringUtils.isBlank(dataUrl)) { log.warn("No data url given"); return; } if(!this.setWhereFrom(file.getAbsolute(), dataUrl)) { throw new LocalAccessDeniedException(file.getAbsolute()); } } } @Override void setQuarantine(final Local file, final String originUrl, final String dataUrl); @Override void setWhereFrom(final Local file, final String dataUrl); }### Answer:
@Test public void testSetWhereEmptyUrl() throws Exception { final QuarantineService q = new LaunchServicesQuarantineService(); q.setWhereFrom(new NullLocal("/", "n"), null); q.setWhereFrom(new NullLocal("/", "n"), StringUtils.EMPTY); }
@Test public void testSetWhereFrom() throws Exception { final QuarantineService q = new LaunchServicesQuarantineService(); Callable<Local> c = new Callable<Local>() { @Override public Local call() throws Exception { final NullLocal l = new NullLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); LocalTouchFactory.get().touch(l); q.setWhereFrom(l, "http: l.delete(); return l; } }; c.call(); }
|
### Question:
WorkspaceRevealService implements RevealService { @Override public boolean reveal(final Local file) { synchronized(NSWorkspace.class) { return NSWorkspace.sharedWorkspace().selectFile(new NFDNormalizer().normalize(file.getAbsolute()).toString(), StringUtils.EMPTY); } } @Override boolean reveal(final Local file); }### Answer:
@Test public void testReveal() { assertTrue(new WorkspaceRevealService().reveal(new Local(System.getProperty("java.io.tmpdir")))); }
|
### Question:
KeychainPasswordStore extends DefaultHostPasswordStore implements PasswordStore { @Override public String getPassword(final Scheme scheme, final int port, final String hostname, final String user) { synchronized(lock) { return this.getInternetPasswordFromKeychain(scheme.name(), port, hostname, user); } } native String getInternetPasswordFromKeychain(String protocol, int port, String serviceName, String user); native String getPasswordFromKeychain(String serviceName, String user); native boolean addPasswordToKeychain(String serviceName, String user, String password); native boolean addInternetPasswordToKeychain(String protocol, int port, String serviceName, String user, String password); @Override String getPassword(final Scheme scheme, final int port, final String hostname, final String user); @Override void addPassword(final Scheme scheme, final int port, final String hostname, final String user, final String password); @Override String getPassword(final String serviceName, final String accountName); @Override void addPassword(final String serviceName, final String accountName, final String password); }### Answer:
@Test public void testFindPassword() { final KeychainPasswordStore k = new KeychainPasswordStore(); assertNull(k.getPassword("cyberduck.ch", "u")); assertNull(k.getPassword(Scheme.http, 80, "cyberduck.ch", "u")); }
|
### Question:
NotificationCenter extends ProxyController implements NotificationService, NSUserNotificationCenter.Delegate { @Override public void notify(final String group, final String identifier, final String title, final String description) { if (filter.shouldSuppress()) { log.debug(String.format("Suppressing notification for %s, %s, %s, %s", group, identifier, title, description)); return; } final NSUserNotification notification = NSUserNotification.notification(); if(StringUtils.isNotBlank(identifier)) { if(notification.respondsToSelector(Foundation.selector("setIdentifier:"))) { notification.setIdentifier(identifier); } if(StringUtils.isNotBlank(Path.getExtension(identifier))) { notification.setContentImage(IconCacheFactory.<NSImage>get().documentIcon(Path.getExtension(identifier), 32)); } } notification.setTitle(LocaleFactory.localizedString(title, "Status")); notification.setInformativeText(description); notification.setHasActionButton(false); center.scheduleNotification(notification); } @Override NotificationService setup(); @Override void unregister(); @Override void addListener(final Listener listener); @Override void notify(final String group, final String identifier, final String title, final String description); @Override void notify(final String group, final String identifier, final String title, final String description, final String action); @Override void userNotificationCenter_didActivateNotification(final NSUserNotificationCenter center, final NSUserNotification notification); @Override boolean userNotificationCenter_shouldPresentNotification(final NSUserNotificationCenter center, final NSUserNotification notification); }### Answer:
@Test public void testNotify() { final NotificationService n = new NotificationCenter(); n.notify(null, null, "title", "test"); }
|
### Question:
CrashReporter extends NSObject { public abstract void checkForCrash(String url); static CrashReporter create(); abstract CrashReporter init(); abstract void checkForCrash(String url); }### Answer:
@Test public void testCheckForCrash() { final CrashReporter reporter = CrashReporter.create(); assertNotNull(reporter); reporter.checkForCrash("https: }
|
### Question:
ServiceManagementApplicationLoginRegistry implements ApplicationLoginRegistry { @Override public boolean register(final Application application) { final Local helper = new FinderLocal(new BundleApplicationResourcesFinder().find().getParent(), String.format("Library/LoginItems/%s.app", application.getName())); if(!finder.register(helper)) { log.warn(String.format("Failed to register %s (%s) with launch services", helper, finder.getDescription(application.getIdentifier()))); } if(!ServiceManagementFunctions.library.SMLoginItemSetEnabled(application.getIdentifier(), true)) { log.warn(String.format("Failed to register %s as login item", application)); return false; } return true; } @Override boolean register(final Application application); @Override boolean unregister(final Application application); }### Answer:
@Test public void testRegister() { assertFalse(new ServiceManagementApplicationLoginRegistry().register( new Application("bundle.helper"))); }
|
### Question:
ServiceManagementApplicationLoginRegistry implements ApplicationLoginRegistry { @Override public boolean unregister(final Application application) { if(!ServiceManagementFunctions.library.SMLoginItemSetEnabled(application.getIdentifier(), false)) { log.warn(String.format("Failed to remove %s as login item", application)); return false; } return true; } @Override boolean register(final Application application); @Override boolean unregister(final Application application); }### Answer:
@Test public void testUnregister() { assertFalse(new ServiceManagementApplicationLoginRegistry().unregister( new Application("bundle.helper"))); }
|
### Question:
ApplicationSupportDirectoryFinder implements SupportDirectoryFinder { @Override public Local find() { final NSArray directories = FoundationKitFunctions.library.NSSearchPathForDirectoriesInDomains( FoundationKitFunctions.NSSearchPathDirectory.NSApplicationSupportDirectory, FoundationKitFunctions.NSSearchPathDomainMask.NSUserDomainMask, true); final String application = preferences.getProperty("application.name"); if(directories.count().intValue() == 0) { log.error("Failed searching for application support directory"); return new FinderLocal("~/Library/Application Support", application); } else { final String directory = directories.objectAtIndex(new NSUInteger(0)).toString(); if(log.isInfoEnabled()) { log.info(String.format("Found application support directory in %s", directory)); } final Local folder = new FinderLocal(directory, application); if(log.isDebugEnabled()) { log.debug(String.format("Use folder %s for application support directory", folder)); } return folder; } } @Override Local find(); }### Answer:
@Test public void testFind() { assertNotNull(new ApplicationSupportDirectoryFinder().find()); assertEquals("~/Library/Application Support/Cyberduck", new ApplicationSupportDirectoryFinder().find().getAbbreviatedPath()); }
|
### Question:
SharedFileListApplicationLoginRegistry implements ApplicationLoginRegistry { @Override public boolean register(final Application application) { try { if(finder.isInstalled(application)) { service.add(new FinderLocal(NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier(application.getIdentifier()))); return true; } return false; } catch(LocalAccessDeniedException e) { return false; } } SharedFileListApplicationLoginRegistry(); SharedFileListApplicationLoginRegistry(final ApplicationFinder finder); @Override boolean register(final Application application); @Override boolean unregister(final Application application); }### Answer:
@Test @Ignore public void testRegister() { final SharedFileListApplicationLoginRegistry registry = new SharedFileListApplicationLoginRegistry(new LaunchServicesApplicationFinder()); final Application application = new Application("ch.sudo.cyberduck"); assertTrue(registry.register(application)); assertTrue(new FinderSidebarService(SidebarService.List.login).contains(new FinderLocal(NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier(application.getIdentifier())))); assertTrue(registry.unregister(application)); }
@Test public void testRegisterNotInstalled() { final SharedFileListApplicationLoginRegistry registry = new SharedFileListApplicationLoginRegistry(new DisabledApplicationFinder()); assertFalse(registry.register(new Application("ch.sudo.cyberduck"))); }
|
### Question:
BundleApplicationResourcesFinder implements ApplicationResourcesFinder { public NSBundle bundle() { if(cached != null) { return cached; } if(log.isInfoEnabled()) { log.info("Loading application bundle resources"); } final NSBundle main = NSBundle.mainBundle(); if(null == main) { cached = null; } else { final Local executable = new FinderLocal(main.executablePath()); cached = this.bundle(main, executable); } return cached; } @Override Local find(); NSBundle bundle(); }### Answer:
@Test public void testBundle() { Assert.assertNotNull(new BundleApplicationResourcesFinder().bundle()); }
@Test public void testSymbolicLink() { final NSBundle bundle = new BundleApplicationResourcesFinder().bundle(NSBundle.bundleWithPath("."), new Local("/usr/bin/java")); Assert.assertNotNull(bundle); Assert.assertEquals(NSBundle.bundleWithPath("/System/Library/Frameworks/JavaVM.framework/Versions/A"), bundle); }
@Test public void testAccessDenied() { final NSBundle bundle = new BundleApplicationResourcesFinder().bundle(NSBundle.bundleWithPath("."), new Local("/usr/bin/java") { @Override public Local getSymlinkTarget() throws NotfoundException { throw new NotfoundException("f"); } }); Assert.assertNotNull(bundle); Assert.assertEquals(NSBundle.bundleWithPath("."), bundle); }
|
### Question:
AutoreleaseActionOperationBatcher implements ActionOperationBatcher { public void operate() { impl.operate(); } void operate(); }### Answer:
@Test public void testOperate() { new AutoreleaseActionOperationBatcher().operate(); }
|
### Question:
DownloadDirectoryFinder implements DirectoryFinder { @Override public Local find(final Host bookmark) { if(null != bookmark.getDownloadFolder()) { if(bookmark.getDownloadFolder().exists()) { return bookmark.getDownloadFolder(); } } final Local directory = LocalFactory.get(preferences.getProperty("queue.download.folder")).withBookmark( preferences.getProperty("queue.download.folder.bookmark")); if(log.isInfoEnabled()) { log.info(String.format("Suggest default download folder %s for bookmark %s", directory, bookmark)); } return directory; } @Override Local find(final Host bookmark); @Override void save(final Host bookmark, final Local directory); }### Answer:
@Test public void testFind() throws Exception { final Host host = new Host(new TestProtocol()); assertNull(host.getDownloadFolder()); final DownloadDirectoryFinder finder = new DownloadDirectoryFinder(); assertEquals(System.getProperty("user.dir"), finder.find(host).getAbsolute()); host.setDownloadFolder(new Local(String.format("/%s", UUID.randomUUID()))); assertEquals(System.getProperty("user.dir"), finder.find(host).getAbsolute()); final Local folder = new Local("~/Documents"); new DefaultLocalDirectoryFeature().mkdir(folder); host.setDownloadFolder(folder); assertEquals(String.format("~%sDocuments", PreferencesFactory.get().getProperty("local.delimiter")), finder.find(host).getAbbreviatedPath()); }
|
### Question:
PathTooltipService implements TooltipService<Path> { @Override public String getTooltip(final Path file) { final StringBuilder tooltip = new StringBuilder(file.getAbsolute()); final Checksum checksum = file.attributes().getChecksum(); if(Checksum.NONE != checksum) { tooltip.append("\n").append(String.format("%s %s", StringUtils.upperCase(checksum.algorithm.name()), checksum.hash)); } if(StringUtils.isNotBlank(file.attributes().getVersionId())) { tooltip.append("\n").append(file.attributes().getVersionId()); } return tooltip.toString(); } @Override String getTooltip(final Path file); }### Answer:
@Test public void testGetTooltip() { final PathTooltipService s = new PathTooltipService(); assertEquals("/p", s.getTooltip(new Path("/p", EnumSet.of(Path.Type.file)))); }
|
### Question:
SizeTooltipService implements TooltipService<Path> { @Override public String getTooltip(final Path file) { return sizeFormatter.format(file.attributes().getSize(), true); } SizeTooltipService(); SizeTooltipService(final SizeFormatter sizeFormatter); @Override String getTooltip(final Path file); }### Answer:
@Test public void testGetTooltip() { final SizeTooltipService s = new SizeTooltipService(); final PathAttributes attr = new PathAttributes(); attr.setSize(-1L); assertEquals("--", s.getTooltip(new Path("/p", EnumSet.of(Path.Type.file), attr))); attr.setSize(0L); assertEquals("0 B", s.getTooltip(new Path("/p", EnumSet.of(Path.Type.file), attr))); attr.setSize(213457865421L); assertEquals("198.8 GiB (213,457,865,421 bytes)", s.getTooltip(new Path("/p", EnumSet.of(Path.Type.file), attr))); }
|
### Question:
DefaultBrowserFilter implements Filter<Path> { @Override public boolean accept(final Path file) { if(pattern.matcher(file.getName()).matches()) { return false; } if(file.getType().contains(Path.Type.upload)) { return false; } if(file.attributes().isDuplicate()) { return false; } if(file.attributes().isHidden()) { return false; } return true; } DefaultBrowserFilter(); DefaultBrowserFilter(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 DefaultBrowserFilter f = new DefaultBrowserFilter(); assertFalse(f.accept(new Path(".f", EnumSet.of(Path.Type.file)))); assertTrue(f.accept(new Path("f.f", EnumSet.of(Path.Type.file)))); final Path d = new Path("f.f", EnumSet.of(Path.Type.file)); d.attributes().setDuplicate(true); assertFalse(f.accept(d)); }
@Test public void testCustomPattern() { final DefaultBrowserFilter f = new DefaultBrowserFilter(Pattern.compile("\\..*|~\\$.*")); assertFalse(f.accept(new Path(".f", EnumSet.of(Path.Type.file)))); assertTrue(f.accept(new Path("f", EnumSet.of(Path.Type.file)))); }
|
### Question:
UploadDirectoryFinder implements DirectoryFinder { @Override public Local find(final Host bookmark) { if(null != bookmark.getUploadFolder()) { if(bookmark.getUploadFolder().exists()) { return bookmark.getUploadFolder(); } } final Local directory = LocalFactory.get(preferences.getProperty("local.user.home")); if(log.isInfoEnabled()) { log.info(String.format("Suggest default upload folder %s for bookmark %s", directory, bookmark)); } return directory; } @Override Local find(final Host bookmark); @Override void save(final Host bookmark, final Local directory); }### Answer:
@Test public void testFind() { final Host host = new Host(new TestProtocol()); assertNull(host.getDownloadFolder()); final UploadDirectoryFinder finder = new UploadDirectoryFinder(); assertEquals(new Local(System.getProperty("user.home")), finder.find(host)); }
|
### Question:
RegionComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { if(StringUtils.isBlank(p1.attributes().getRegion()) && StringUtils.isBlank(p2.attributes().getRegion())) { return 0; } if(StringUtils.isBlank(p1.attributes().getRegion())) { return -1; } if(StringUtils.isBlank(p2.attributes().getRegion())) { return 1; } if(ascending) { return p1.attributes().getRegion().compareToIgnoreCase(p2.attributes().getRegion()); } return -p1.attributes().getRegion().compareToIgnoreCase(p2.attributes().getRegion()); } RegionComparator(boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new RegionComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file)))); }
|
### Question:
FileTypeComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { if((p1.isDirectory() && p2.isDirectory()) || p1.isFile() && p2.isFile()) { if(ascending) { return impl.compare(descriptor.getKind(p1), descriptor.getKind(p2)); } return -impl.compare(descriptor.getKind(p1), descriptor.getKind(p2)); } if(p1.isFile()) { return ascending ? 1 : -1; } return ascending ? -1 : 1; } FileTypeComparator(boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new FileTypeComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/a", EnumSet.of(Path.Type.file)))); assertEquals(0, new FileTypeComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.directory)), new Path("/b", EnumSet.of(Path.Type.directory)))); assertEquals(1, new FileTypeComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.directory)))); assertEquals(-1, new FileTypeComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.directory)), new Path("/b", EnumSet.of(Path.Type.file)))); }
|
### Question:
SizeComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { if(p1.attributes().getSize() > p2.attributes().getSize()) { return ascending ? 1 : -1; } else if(p1.attributes().getSize() < p2.attributes().getSize()) { return ascending ? -1 : 1; } return 0; } SizeComparator(boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new SizeComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file)))); }
|
### Question:
ExtensionComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { if(p1.isDirectory() && p2.isDirectory()) { return 0; } if(p1.isFile() && p2.isFile()) { if(StringUtils.isBlank(p1.getExtension()) && StringUtils.isBlank(p2.getExtension())) { return 0; } if(StringUtils.isBlank(p1.getExtension())) { return -1; } if(StringUtils.isBlank(p2.getExtension())) { return 1; } if(ascending) { return impl.compare(p1.getExtension(), p2.getExtension()); } return -impl.compare(p1.getExtension(), p2.getExtension()); } if(p1.isFile()) { return ascending ? 1 : -1; } return ascending ? -1 : 1; } ExtensionComparator(boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new ExtensionComparator(true).compareFirst(new Path("/a.a", EnumSet.of(Path.Type.directory)), new Path("/b.b", EnumSet.of(Path.Type.directory)))); assertEquals(0, new ExtensionComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file)))); assertEquals(1, new ExtensionComparator(true).compareFirst(new Path("/a.txt", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file)))); assertEquals(0, new ExtensionComparator(true).compareFirst(new Path("/a.txt", EnumSet.of(Path.Type.file)), new Path("/b.txt", EnumSet.of(Path.Type.file)))); assertEquals(-1, new ExtensionComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b.txt", EnumSet.of(Path.Type.file)))); }
|
### Question:
OwnerComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { if(StringUtils.isBlank(p1.attributes().getOwner()) && StringUtils.isBlank(p2.attributes().getOwner())) { return 0; } if(StringUtils.isBlank(p1.attributes().getOwner())) { return -1; } if(StringUtils.isBlank(p2.attributes().getOwner())) { return 1; } if(ascending) { return p1.attributes().getOwner().compareToIgnoreCase(p2.attributes().getOwner()); } return -p1.attributes().getOwner().compareToIgnoreCase(p2.attributes().getOwner()); } OwnerComparator(boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new OwnerComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file)))); final Path p = new Path("/a", EnumSet.of(Path.Type.file)); p.attributes().setOwner("o"); assertEquals(1, new OwnerComparator(true).compareFirst(p, new Path("/b", EnumSet.of(Path.Type.file)))); assertEquals(-1, new OwnerComparator(true).compareFirst(new Path("/b", EnumSet.of(Path.Type.file)), p)); }
|
### Question:
TimestampComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { final long d1 = p1.attributes().getModificationDate(); final long d2 = p2.attributes().getModificationDate(); if(d1 == d2) { return 0; } if(ascending) { return d1 > d2 ? 1 : -1; } return d1 > d2 ? -1 : 1; } TimestampComparator(final boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new TimestampComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file)))); final Path p1 = new Path("/a", EnumSet.of(Path.Type.file)); p1.attributes().setModificationDate(System.currentTimeMillis()); final Path p2 = new Path("/b", EnumSet.of(Path.Type.file)); p2.attributes().setModificationDate(System.currentTimeMillis() - 1000); assertEquals(1, new TimestampComparator(true).compareFirst(p1, p2)); }
|
### Question:
GroupComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { if(StringUtils.isBlank(p1.attributes().getGroup()) && StringUtils.isBlank(p2.attributes().getGroup())) { return 0; } if(StringUtils.isBlank(p1.attributes().getGroup())) { return -1; } if(StringUtils.isBlank(p2.attributes().getGroup())) { return 1; } if(ascending) { return p1.attributes().getGroup().compareToIgnoreCase(p2.attributes().getGroup()); } return -p1.attributes().getGroup().compareToIgnoreCase(p2.attributes().getGroup()); } GroupComparator(boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new GroupComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file)))); final Path p = new Path("/a", EnumSet.of(Path.Type.file)); p.attributes().setGroup("g"); assertEquals(1, new GroupComparator(true).compareFirst(p, new Path("/b", EnumSet.of(Path.Type.file)))); assertEquals(-1, new GroupComparator(true).compareFirst(new Path("/b", EnumSet.of(Path.Type.file)), p)); }
|
### Question:
FilenameComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { if(ascending) { return impl.compare(p1.getName(), p2.getName()); } return -impl.compare(p1.getName(), p2.getName()); } FilenameComparator(boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new FilenameComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/a", EnumSet.of(Path.Type.file)))); assertEquals(0, new FilenameComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/a", EnumSet.of(Path.Type.directory)))); assertEquals(-1, new FilenameComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.directory)))); assertEquals(1, new FilenameComparator(true).compareFirst(new Path("/b", EnumSet.of(Path.Type.file)), new Path("/a", EnumSet.of(Path.Type.directory)))); }
|
### Question:
PermissionsComparator extends BrowserComparator { @Override protected int compareFirst(final Path p1, final Path p2) { if(Permission.EMPTY.equals(p1.attributes().getPermission()) && Permission.EMPTY.equals(p2.attributes().getPermission())) { return 0; } if(Permission.EMPTY.equals(p1.attributes().getPermission())) { return -1; } if(Permission.EMPTY.equals(p2.attributes().getPermission())) { return 1; } Integer perm1 = Integer.valueOf(p1.attributes().getPermission().getMode()); Integer perm2 = Integer.valueOf(p2.attributes().getPermission().getMode()); if(perm1 > perm2) { return ascending ? 1 : -1; } else if(perm1 < perm2) { return ascending ? -1 : 1; } return 0; } PermissionsComparator(boolean ascending); }### Answer:
@Test public void testCompareFirst() { assertEquals(0, new PermissionsComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file)))); }
|
### Question:
S3TouchFeature implements Touch<StorageObject> { @Override public boolean isSupported(final Path workdir, final String filename) { return !workdir.isRoot(); } S3TouchFeature(final S3Session session); @Override Path touch(final Path file, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String filename); @Override Touch<StorageObject> withWriter(final Write<StorageObject> writer); }### Answer:
@Test public void testFile() { final S3Session session = new S3Session(new Host(new S3Protocol(), "h")); assertFalse(new S3TouchFeature(session).isSupported(new Path("/", EnumSet.of(Path.Type.volume)), StringUtils.EMPTY)); assertTrue(new S3TouchFeature(session).isSupported(new Path(new Path("/", EnumSet.of(Path.Type.volume)), "/container", EnumSet.of(Path.Type.volume)), StringUtils.EMPTY)); }
|
### Question:
IconCacheFactory extends Factory<IconCache> { public static synchronized <I> IconCache<I> get() { if(null == cache) { cache = new IconCacheFactory().create(); } return cache; } protected IconCacheFactory(); static synchronized IconCache<I> get(); }### Answer:
@Test public void testGet() { assertSame(IconCacheFactory.get(), IconCacheFactory.get()); }
|
### Question:
MappingMimeTypeService implements MimeTypeService { @Override public String getMime(final String filename) { if(StringUtils.startsWith(filename, "._")) { return DEFAULT_CONTENT_TYPE; } return types.getMimetype(StringUtils.lowerCase(filename)); } @Override String getMime(final String filename); }### Answer:
@Test public void testGetMime() { MappingMimeTypeService s = new MappingMimeTypeService(); assertEquals("text/plain", s.getMime("f.txt")); assertEquals("text/plain", s.getMime("f.TXT")); assertEquals("video/x-f4v", s.getMime("f.f4v")); assertEquals("application/javascript", s.getMime("f.js")); assertEquals("video/mp2t", s.getMime("f.ts")); assertEquals("application/x-mpegurl", s.getMime("f.m3u8")); assertEquals("application/octet-stream", s.getMime("._f.txt")); }
|
### Question:
Navigation { public Path back() { int size = back.size(); if(size > 1) { forward.add(back.get(size - 1)); Path p = back.get(size - 2); back.remove(size - 1); back.remove(size - 2); return p; } else if(1 == size) { forward.add(back.get(size - 1)); return back.get(size - 1); } return null; } void add(final Path p); Path back(); Path forward(); List<Path> getBack(); List<Path> getForward(); void clear(); }### Answer:
@Test public void testBack() { Navigation n = new Navigation(); assertNull(n.back()); n.add(new Path("a", EnumSet.of(Path.Type.directory))); n.add(new Path("b", EnumSet.of(Path.Type.directory))); assertEquals("a", n.back().getName()); assertEquals("b", n.forward().getName()); }
|
### Question:
RegexLocale implements Locale { @Override public String localize(final String key, final String table) { final Key lookup = new Key(table, key); if(!cache.contains(lookup)) { if(!tables.contains(table)) { try { this.load(table); } catch(IOException e) { log.warn(String.format("Failure loading properties from %s.strings. %s", table, e.getMessage())); } finally { tables.add(table); } } } if(cache.contains(lookup)) { return cache.get(lookup); } return key; } RegexLocale(); RegexLocale(final Local resources); @Override void setDefault(final String language); @Override String localize(final String key, final String table); }### Answer:
@Test public void testLocalize() { final RegexLocale locale = new RegexLocale(new Local(new WorkdirPrefixer().normalize("../i18n/src/main/resources"))); assertEquals("Download failed", locale.localize("Download failed", "Status")); locale.setDefault("fr"); assertEquals("Échec du téléchargement", locale.localize("Download failed", "Status")); }
|
### Question:
RemainingPeriodFormatter implements PeriodFormatter { @Override public String format(final long remaining) { StringBuilder b = new StringBuilder(); if(remaining < 0) { return LocaleFactory.localizedString("Unknown"); } if(remaining > 7200) { b.append(MessageFormat.format(LocaleFactory.localizedString("{0} hours remaining", "Status"), new BigDecimal(remaining).divide(new BigDecimal(3600), 1, BigDecimal.ROUND_DOWN).toString()) ); } else if(remaining > 120) { b.append(MessageFormat.format(LocaleFactory.localizedString("{0} minutes remaining", "Status"), String.valueOf((int) (remaining / 60))) ); } else { b.append(MessageFormat.format(LocaleFactory.localizedString("{0} seconds remaining", "Status"), String.valueOf((int) remaining)) ); } return b.toString(); } @Override String format(final long remaining); }### Answer:
@Test public void testFormat() { RemainingPeriodFormatter f = new RemainingPeriodFormatter(); assertEquals("5 seconds remaining", f.format(5L)); assertEquals("5 minutes remaining", f.format(5 * 60)); assertEquals("60 minutes remaining", f.format(60 * 60)); assertEquals("120 minutes remaining", f.format(60 * 60 * 2)); assertEquals("2.0 hours remaining", f.format(60 * 60 * 2 + 1)); assertEquals("2.1 hours remaining", f.format(60 * 60 * 2 + 6 * 60)); }
|
### Question:
LoginOptions { @Override public boolean equals(final Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final LoginOptions that = (LoginOptions) o; return user == that.user && password == that.password && keychain == that.keychain && publickey == that.publickey && anonymous == that.anonymous && Objects.equals(icon, that.icon); } LoginOptions(); LoginOptions(final LoginOptions copy); LoginOptions(final Protocol protocol); LoginOptions configure(final Protocol protocol); LoginOptions user(boolean e); LoginOptions password(boolean e); LoginOptions token(boolean e); LoginOptions oauth(boolean e); LoginOptions keychain(boolean e); LoginOptions publickey(boolean e); LoginOptions anonymous(boolean e); LoginOptions icon(String icon); boolean user(); boolean password(); boolean token(); boolean keychain(); boolean publickey(); boolean certificate(); boolean anonymous(); boolean oauth(); String icon(); LoginOptions usernamePlaceholder(final String usernamePlaceholder); LoginOptions passwordPlaceholder(final String passwordPlaceholder); String getUsernamePlaceholder(); String getPasswordPlaceholder(); @Override boolean equals(final Object o); @Override int hashCode(); public boolean user; public boolean password; public boolean token; public boolean oauth; public boolean keychain; public boolean publickey; public boolean certificate; public boolean anonymous; public String icon; public String usernamePlaceholder; public String passwordPlaceholder; }### Answer:
@Test public void testEquals() { assertEquals(new LoginOptions(), new LoginOptions()); final LoginOptions a = new LoginOptions(); a.keychain = false; final LoginOptions b = new LoginOptions(); b.keychain = true; assertNotEquals(a, b); }
|
### Question:
BackgroundException extends Exception { @Override public String getMessage() { return null == message ? LocaleFactory.localizedString("Unknown") : message; } BackgroundException(); BackgroundException(final Throwable cause); BackgroundException(final String message, final String detail); BackgroundException(final String detail, final Throwable cause); BackgroundException(final String message, final String detail, final Throwable cause); void setMessage(final String title); void setDetail(final String detail); @Override String getMessage(); void setFile(final Path file); BackgroundException withFile(final Path file); Path getFile(); String getHelp(); String getDetail(); String getDetail(boolean help); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testGetMessage() { final BackgroundException e = new BackgroundException(new LoginCanceledException()); e.setMessage("m"); assertEquals("m", e.getMessage()); }
|
### Question:
PathRelativizer { public static String relativize(String root, final String path) { if(StringUtils.isBlank(root)) { return path; } if(!StringUtils.equals(root, String.valueOf(Path.DELIMITER))) { root = root + Path.DELIMITER; } if(StringUtils.contains(path, root)) { return StringUtils.substring(path, path.indexOf(root) + root.length()); } return path; } private PathRelativizer(); static String relativize(String root, final String path); }### Answer:
@Test public void testRelativize() { assertEquals("a", PathRelativizer.relativize("/", "/a")); assertEquals("/b/path", PathRelativizer.relativize("/a", "/b/path")); assertEquals("path", PathRelativizer.relativize("/a", "/a/path")); assertEquals("a/path", PathRelativizer.relativize("public_html", "/home/user/public_html/a/path")); assertEquals("/home/user/public_html/a/path", PathRelativizer.relativize(null, "/home/user/public_html/a/path")); }
|
### Question:
DefaultPathPredicate implements CacheReference<Path> { @Override public String toString() { return reference; } DefaultPathPredicate(final Path file); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override boolean test(final Path test); }### Answer:
@Test public void testUnique() { final Path t_noregion = new Path("/", EnumSet.of(Path.Type.directory)); assertEquals("[directory]-/", new DefaultPathPredicate(t_noregion).toString()); final Path t_region = new Path("/", EnumSet.of(Path.Type.directory)); t_region.attributes().setRegion("r"); assertEquals("[directory]-/", new DefaultPathPredicate(t_region).toString()); assertEquals(new DefaultPathPredicate(t_noregion), new DefaultPathPredicate(t_region)); }
|
### Question:
HttpResponseOutputStream extends StatusOutputStream<T> { @Override public void close() throws IOException { super.close(); try { final T response = this.getStatus(); if(log.isDebugEnabled()) { log.debug(String.format("Closed stream %s with response value %s", this, response)); } } catch(BackgroundException e) { throw new IOException(e.getDetail(), e); } } HttpResponseOutputStream(final OutputStream proxy); abstract T getStatus(); @Override void close(); }### Answer:
@Test(expected = IOException.class) public void testClose() throws Exception { try { new HttpResponseOutputStream<Void>(new NullOutputStream()) { @Override public Void getStatus() throws BackgroundException { throw new InteroperabilityException("d"); } }.close(); } catch(IOException e) { assertEquals("d. Please contact your web hosting service provider for assistance.", e.getMessage()); throw e; } }
|
### Question:
S3LoggingFeature implements Logging { @Override public void setConfiguration(final Path file, final LoggingConfiguration configuration) throws BackgroundException { final Path bucket = containerService.getContainer(file); try { final S3BucketLoggingStatus status = new S3BucketLoggingStatus( StringUtils.isNotBlank(configuration.getLoggingTarget()) ? configuration.getLoggingTarget() : bucket.getName(), null); if(configuration.isEnabled()) { status.setLogfilePrefix(PreferencesFactory.get().getProperty("s3.logging.prefix")); } session.getClient().setBucketLoggingStatus(bucket.getName(), status, true); } catch(ServiceException e) { throw new S3ExceptionMappingService().map("Failure to write attributes of {0}", e, file); } } S3LoggingFeature(final S3Session session); @Override LoggingConfiguration getConfiguration(final Path file); @Override void setConfiguration(final Path file, final LoggingConfiguration configuration); }### Answer:
@Test(expected = NotfoundException.class) public void testWriteNotFound() throws Exception { new S3LoggingFeature(session).setConfiguration( new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)), new LoggingConfiguration(false) ); }
|
### Question:
Distribution { public boolean isDeployed() { return deployed; } Distribution(final URI origin, final Method method, final boolean enabled); Distribution(final Method method, final boolean enabled); String getId(); void setId(final String id); String getEtag(); String getReference(); URI getOrigin(); boolean isEnabled(); void setEnabled(final boolean enabled); boolean isDeployed(); void setDeployed(final boolean deployed); boolean isLogging(); void setLogging(boolean logging); void setLoggingContainer(final String container); String getLoggingContainer(); void setUrl(final URI url); URI getUrl(); void setSslUrl(final URI sslUrl); URI getSslUrl(); void setStreamingUrl(final URI streamingUrl); URI getStreamingUrl(); URI getiOSstreamingUrl(); void setiOSstreamingUrl(URI iOSstreamingUrl); String getStatus(); void setStatus(final String status); String getInvalidationStatus(); void setInvalidationStatus(final String invalidationStatus); List<Path> getContainers(); void setContainers(final List<Path> containers); String getIndexDocument(); void setIndexDocument(final String indexDocument); String getErrorDocument(); void setErrorDocument(String errorDocument); List<Path> getRootDocuments(); void setRootDocuments(final List<Path> rootDocuments); Method getMethod(); void setMethod(Method method); String[] getCNAMEs(); void setCNAMEs(final String[] cnames); void setEtag(final String etag); void setReference(final String reference); @Override String toString(); @Override boolean equals(final Object o); @Override int hashCode(); static final Method WEBSITE; static final Method WEBSITE_CDN; static final Method DOWNLOAD; static final Method CUSTOM; static final Method STREAMING; }### Answer:
@Test public void testDeployed() { assertTrue(new Distribution(Distribution.DOWNLOAD, true).isDeployed()); }
|
### Question:
Distribution { public String[] getCNAMEs() { if(null == cnames) { return new String[]{}; } return cnames; } Distribution(final URI origin, final Method method, final boolean enabled); Distribution(final Method method, final boolean enabled); String getId(); void setId(final String id); String getEtag(); String getReference(); URI getOrigin(); boolean isEnabled(); void setEnabled(final boolean enabled); boolean isDeployed(); void setDeployed(final boolean deployed); boolean isLogging(); void setLogging(boolean logging); void setLoggingContainer(final String container); String getLoggingContainer(); void setUrl(final URI url); URI getUrl(); void setSslUrl(final URI sslUrl); URI getSslUrl(); void setStreamingUrl(final URI streamingUrl); URI getStreamingUrl(); URI getiOSstreamingUrl(); void setiOSstreamingUrl(URI iOSstreamingUrl); String getStatus(); void setStatus(final String status); String getInvalidationStatus(); void setInvalidationStatus(final String invalidationStatus); List<Path> getContainers(); void setContainers(final List<Path> containers); String getIndexDocument(); void setIndexDocument(final String indexDocument); String getErrorDocument(); void setErrorDocument(String errorDocument); List<Path> getRootDocuments(); void setRootDocuments(final List<Path> rootDocuments); Method getMethod(); void setMethod(Method method); String[] getCNAMEs(); void setCNAMEs(final String[] cnames); void setEtag(final String etag); void setReference(final String reference); @Override String toString(); @Override boolean equals(final Object o); @Override int hashCode(); static final Method WEBSITE; static final Method WEBSITE_CDN; static final Method DOWNLOAD; static final Method CUSTOM; static final Method STREAMING; }### Answer:
@Test public void testCnames() { assertNotNull(new Distribution(Distribution.DOWNLOAD, false).getCNAMEs()); }
|
### Question:
DefaultProxyFinder implements ProxyFinder { @Override public Proxy find(final Host target) { if(!preferences.getBoolean("connection.proxy.enable")) { return Proxy.DIRECT; } for(java.net.Proxy proxy : selector.select(URI.create(provider.get(target)))) { switch(proxy.type()) { case DIRECT: { return Proxy.DIRECT; } case HTTP: { if(proxy.address() instanceof InetSocketAddress) { final InetSocketAddress address = (InetSocketAddress) proxy.address(); return new Proxy(Proxy.Type.HTTP, address.getHostName(), address.getPort()); } } case SOCKS: { if(proxy.address() instanceof InetSocketAddress) { final InetSocketAddress address = (InetSocketAddress) proxy.address(); return new Proxy(Proxy.Type.SOCKS, address.getHostName(), address.getPort()); } } } } return Proxy.DIRECT; } @Override Proxy find(final Host target); }### Answer:
@Test public void testFind() { final DefaultProxyFinder proxy = new DefaultProxyFinder(); assertEquals(Proxy.Type.DIRECT, proxy.find(new Host(new TestProtocol(), "cyberduck.io")).getType()); }
@Test public void testExcludedLocalHost() { final DefaultProxyFinder proxy = new DefaultProxyFinder(); assertEquals(Proxy.Type.DIRECT, proxy.find(new Host(new TestProtocol(), "cyberduck.local")).getType()); }
@Test public void testSimpleExcluded() { final DefaultProxyFinder proxy = new DefaultProxyFinder(); assertEquals(Proxy.Type.DIRECT, proxy.find(new Host(new TestProtocol(), "simple")).getType()); }
|
### Question:
CredentialsConfiguratorFactory { public static CredentialsConfigurator get(final Protocol protocol) { return protocol.getCredentialsFinder(); } private CredentialsConfiguratorFactory(); static CredentialsConfigurator get(final Protocol protocol); }### Answer:
@Test public void testGet() { final Host host = new Host(new TestProtocol()); final Credentials credentials = host.getCredentials(); assertSame(credentials, CredentialsConfiguratorFactory.get(new TestProtocol()).configure(host)); }
|
### Question:
PasswordStoreFactory extends Factory<HostPasswordStore> { public static synchronized HostPasswordStore get() { try { return new PasswordStoreFactory().create(); } catch(FactoryException e) { return new DisabledPasswordStore(); } } protected PasswordStoreFactory(); static synchronized HostPasswordStore get(); }### Answer:
@Test public void testGet() { assertNotSame(PasswordStoreFactory.get(), PasswordStoreFactory.get()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.