method2testcases
stringlengths 118
3.08k
|
---|
### Question:
LinuxTerminalPreferences extends TerminalPreferences { @Override protected void setDefaults() { super.setDefaults(); try { final Process echo = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "echo ~"}); this.setDefault("local.user.home", StringUtils.strip(IOUtils.toString(echo.getInputStream(), Charset.defaultCharset()))); } catch(IOException e) { log.warn("Failure determining user home with `echo ~`"); } this.setDefault("ssh.authentication.agent.enable", String.valueOf(false)); this.setDefault("bookmarks.folder.name", "bookmarks"); this.setDefault("profiles.folder.name", "profiles"); this.setDefault("connection.ssl.securerandom.algorithm", "NativePRNGNonBlocking"); } LinuxTerminalPreferences(); }### Answer:
@Test public void setDefaults() { final LinuxTerminalPreferences prefs = new LinuxTerminalPreferences(); prefs.load(); prefs.setLogging(); prefs.setFactories(); prefs.setDefaults(); assertEquals("NativePRNGNonBlocking", prefs.getProperty("connection.ssl.securerandom.algorithm")); assertEquals(UnsecureHostPasswordStore.class.getName(), prefs.getProperty("factory.passwordstore.class")); }
|
### Question:
TerminalHelpPrinter { public static void print(final Options options) { print(options, new TerminalHelpFormatter()); } private TerminalHelpPrinter(); static void print(final Options options); static void print(final Options options, final HelpFormatter formatter); }### Answer:
@Test public void testPrintWidth100() { TerminalHelpPrinter.print(TerminalOptionsBuilder.options(), new TerminalHelpFormatter(100)); }
@Test @Ignore public void testPrintWidth20DefaultFormatter() { final HelpFormatter f = new TerminalHelpFormatter(); f.setWidth(20); TerminalHelpPrinter.print(TerminalOptionsBuilder.options(), f); }
@Test public void testPrintWidth20() { TerminalHelpPrinter.print(TerminalOptionsBuilder.options(), new TerminalHelpFormatter(40)); }
|
### Question:
TerminalHelpPrinter { protected static String getScheme(final Protocol protocol) { if(new BundledProtocolPredicate().test(protocol)) { for(String scheme : protocol.getSchemes()) { return scheme; } return protocol.getIdentifier(); } final Protocol standard = ProtocolFactory.get().forName(protocol.getIdentifier()); if(Arrays.equals(protocol.getSchemes(), standard.getSchemes())) { return protocol.getProvider(); } for(String scheme : protocol.getSchemes()) { return scheme; } return protocol.getProvider(); } private TerminalHelpPrinter(); static void print(final Options options); static void print(final Options options, final HelpFormatter formatter); }### Answer:
@Test public void testScheme() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new AzureProtocol()))); final ProfilePlistReader reader = new ProfilePlistReader(factory, new DeserializerFactory()); final Profile profile = reader.read( this.getClass().getResourceAsStream("/Azure.cyberduckprofile") ); assertEquals("azure", TerminalHelpPrinter.getScheme(profile)); }
|
### Question:
TerminalAlertCallback implements AlertCallback { @Override public boolean alert(final Host host, final BackgroundException failure, final StringBuilder transcript) { switch(new DefaultFailureDiagnostics().determine(failure)) { case cancel: return false; default: final StringAppender appender = new StringAppender(); appender.append(failure.getMessage()); appender.append(failure.getDetail()); console.printf("%n%s%n", appender.toString()); } return false; } @Override boolean alert(final Host host, final BackgroundException failure, final StringBuilder transcript); }### Answer:
@Test public void testAlert() { assertFalse(new TerminalAlertCallback().alert(new Host(new TestProtocol()), new BackgroundException(), new StringBuilder())); }
|
### Question:
ApplicationTerminalPreferences extends TerminalPreferences { @Override protected void setDefaults() { super.setDefaults(); this.setDefault("connection.ssl.keystore.type", "KeychainStore"); this.setDefault("connection.ssl.keystore.provider", "Apple"); this.setDefault("keychain.secure", String.valueOf(true)); } ApplicationTerminalPreferences(); }### Answer:
@Test public void setDefaults() { final ApplicationTerminalPreferences prefs = new ApplicationTerminalPreferences(); prefs.load(); prefs.setFactories(); prefs.setDefaults(); assertEquals("NativePRNG", prefs.getProperty("connection.ssl.securerandom.algorithm")); assertEquals(KeychainPasswordStore.class.getName(), prefs.getProperty("factory.passwordstore.class")); }
|
### Question:
GraphExceptionMappingService extends AbstractExceptionMappingService<OneDriveAPIException> { @Override public BackgroundException map(final OneDriveAPIException failure) { if(failure.getResponseCode() > 0) { final StringAppender buffer = new StringAppender(); buffer.append(failure.getMessage()); buffer.append(failure.getErrorMessage()); return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(failure.getResponseCode(), buffer.toString())); } if(ExceptionUtils.getRootCause(failure) != failure && ExceptionUtils.getRootCause(failure) instanceof IOException) { return new DefaultIOExceptionMappingService().map((IOException) ExceptionUtils.getRootCause(failure)); } return new InteroperabilityException(failure.getMessage(), failure); } @Override BackgroundException map(final OneDriveAPIException failure); }### Answer:
@Test public void map() { assertTrue(new GraphExceptionMappingService().map( new OneDriveAPIException("The OneDrive API responded with too many redirects.")) instanceof InteroperabilityException); assertTrue(new GraphExceptionMappingService().map( new OneDriveAPIException("m", 404)) instanceof NotfoundException); assertTrue(new GraphExceptionMappingService().map( new OneDriveAPIException("Couldn't connect to the OneDrive API due to a network error.", new SocketException())) instanceof ConnectionRefusedException); }
|
### Question:
OneDriveSharingLinkUrlProvider implements PromptUrlProvider { @Override public DescriptiveUrl toDownloadUrl(final Path file, final Object o, final PasswordCallback callback) throws BackgroundException { try { final OneDriveItem item = session.toItem(file); if(null == item) { throw new NotfoundException(file.getAbsolute()); } if(log.isDebugEnabled()) { log.debug(String.format("Create shared link for %s", file)); } return new DescriptiveUrl(URI.create(item.createSharedLink(OneDriveSharingLink.Type.VIEW).getLink().getWebUrl()), DescriptiveUrl.Type.signed, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), LocaleFactory.localizedString("Pre-Signed", "S3"))); } catch(OneDriveAPIException e) { throw new GraphExceptionMappingService().map(e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } OneDriveSharingLinkUrlProvider(final OneDriveSession session); @Override boolean isSupported(final Path file, final Type type); @Override DescriptiveUrl toDownloadUrl(final Path file, final Object o, final PasswordCallback callback); @Override DescriptiveUrl toUploadUrl(final Path file, final Object o, final PasswordCallback callback); }### Answer:
@Test public void toUrl() throws Exception { final Path file = new Path(new OneDriveHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new GraphTouchFeature(session).touch(file, new TransferStatus().withMime("x-application/cyberduck")); assertNotEquals(DescriptiveUrl.EMPTY, new OneDriveSharingLinkUrlProvider(session).toDownloadUrl(file, null, new DisabledPasswordCallback())); new GraphDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
OneDriveListService implements ListService { @Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(directory.isRoot()) { final AttributedList<Path> list = new AttributedList<>(); list.add(MYFILES_NAME); list.add(SHARED_NAME); listener.chunk(directory, list); return list; } else if(SHARED_NAME.equals(directory)) { return new OneDriveSharedWithMeListService(session).list(directory, listener); } else { return new GraphItemListService(session).list(directory, listener); } } OneDriveListService(final GraphSession session); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); static final Path MYFILES_NAME; static final Path SHARED_NAME; }### Answer:
@Test public void testListDrives() throws Exception { final AttributedList<Path> list = new OneDriveListService(session).list(new Path("/", EnumSet.of(Path.Type.directory)), new DisabledListProgressListener()); assertFalse(list.isEmpty()); for(Path f : list) { assertEquals(new Path("/", EnumSet.of(Path.Type.directory)), f.getParent()); } assertTrue(list.contains(new OneDriveHomeFinderService(session).find())); }
|
### Question:
OneDriveProtocol extends GraphProtocol { @Override public String getPrefix() { return String.format("%s.%s", OneDriveProtocol.class.getPackage().getName(), "OneDrive"); } @Override String getIdentifier(); @Override String getDescription(); @Override String getName(); @Override String getPrefix(); @Override DirectoryTimestamp getDirectoryTimestamp(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.onedrive.OneDrive", new OneDriveProtocol().getPrefix()); }
|
### Question:
DropboxLockFeature implements Lock<String> { @Override public void unlock(final Path file, final String token) throws BackgroundException { try { for(LockFileResultEntry result : new DbxUserFilesRequests(session.getClient(file)).unlockFileBatch(Collections.singletonList( new UnlockFileArg(containerService.getKey(file)))).getEntries()) { if(result.isFailure()) { throw failure(result); } if(log.isDebugEnabled()) { log.debug(String.format("Unlocked file %s with result %s", file, result.getSuccessValue())); } } } catch(DbxException e) { throw new DropboxExceptionMappingService().map("Failure to write attributes of {0}", e, file); } } DropboxLockFeature(final DropboxSession session); @Override String lock(final Path file); @Override void unlock(final Path file, final String token); }### Answer:
@Test public void testLockNotfound() throws Exception { final DropboxTouchFeature touch = new DropboxTouchFeature(session); final Path file = touch.touch(new Path(new Path(new DropboxHomeFinderFeature(session).find(), "Projects", EnumSet.of(Path.Type.directory, Path.Type.shared)).withAttributes(new PathAttributes().withVersionId("7581509952")), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); final DropboxLockFeature f = new DropboxLockFeature(session); f.unlock(file, "l"); new DropboxDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DropboxReadFeature implements Read { @Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final DownloadBuilder builder = new DbxUserFilesRequests(session.getClient(file)).downloadBuilder(containerService.getKey(file)); if(status.isAppend()) { final HttpRange range = HttpRange.withStatus(status); builder.range(range.getStart()); } final DbxDownloader<FileMetadata> downloader = builder.start(); return downloader.getInputStream(); } catch(DbxException e) { throw new DropboxExceptionMappingService().map("Download {0} failed", e, file); } } DropboxReadFeature(final DropboxSession session); @Override InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback); @Override boolean offset(Path file); }### Answer:
@Test public void testReadInterrupt() throws Exception { final DropboxWriteFeature write = new DropboxWriteFeature(session); final TransferStatus writeStatus = new TransferStatus(); final byte[] content = RandomUtils.nextBytes(66800); writeStatus.setLength(content.length); final Path test = new Path(new DropboxHomeFinderFeature(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final OutputStream out = write.write(test, writeStatus, new DisabledConnectionCallback()); assertNotNull(out); new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out); final TransferStatus readStatus = new TransferStatus(); { final InputStream in = new DropboxReadFeature(session).read(test, readStatus, new DisabledConnectionCallback()); assertNotNull(in.read()); in.close(); } { final InputStream in = new DropboxReadFeature(session).read(test, readStatus, new DisabledConnectionCallback()); assertNotNull(in); in.close(); } new DropboxDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DropboxRootListService implements ListService { @Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { if(directory.isRoot()) { final FullAccount account = new DbxUserUsersRequests(session.getClient()).getCurrentAccount(); switch(account.getAccountType()) { case BUSINESS: return new DropboxListService(session).list( directory.withAttributes(new PathAttributes().withVersionId(account.getRootInfo().getRootNamespaceId())), new HomeNamespaceListProgressListener(listener, account)); } } return new DropboxListService(session).list(directory, listener); } catch(DbxException e) { throw new DropboxExceptionMappingService().map("Listing directory {0} failed", e, directory); } } DropboxRootListService(final DropboxSession session); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); }### Answer:
@Test public void testList() throws Exception { final AttributedList<Path> list = new DropboxRootListService(session).list(new DropboxHomeFinderFeature(session).find(), new DisabledListProgressListener()); assertNotNull(list); assertFalse(list.isEmpty()); }
|
### Question:
DropboxSharedFoldersListService implements ListService { @Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> children = new AttributedList<>(); ListFoldersResult listFoldersResult; this.parse(directory, listener, children, listFoldersResult = new DbxUserSharingRequests(session.getClient()).listFolders()); while(listFoldersResult.getCursor() != null) { this.parse(directory, listener, children, listFoldersResult = new DbxUserSharingRequests(session.getClient()) .listMountableFoldersContinue(listFoldersResult.getCursor())); } return children; } catch(DbxException e) { throw new DropboxExceptionMappingService().map("Listing directory {0} failed", e, directory); } } DropboxSharedFoldersListService(final DropboxSession session); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); }### Answer:
@Test public void testList() throws Exception { final AttributedList<Path> list = new DropboxSharedFoldersListService(session).list( new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)), new DisabledListProgressListener()); assertNotNull(list); assertFalse(list.isEmpty()); }
|
### Question:
DropboxProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", this.getClass().getPackage().getName(), "Dropbox"); } @Override String getIdentifier(); @Override String getName(); @Override String getDescription(); @Override String getPrefix(); @Override boolean isHostnameConfigurable(); @Override boolean isPasswordConfigurable(); @Override boolean isPortConfigurable(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override Scheme getScheme(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.dropbox.Dropbox", new DropboxProtocol().getPrefix()); }
|
### Question:
DropboxProtocol extends AbstractProtocol { @Override public boolean isPasswordConfigurable() { return false; } @Override String getIdentifier(); @Override String getName(); @Override String getDescription(); @Override String getPrefix(); @Override boolean isHostnameConfigurable(); @Override boolean isPasswordConfigurable(); @Override boolean isPortConfigurable(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override Scheme getScheme(); }### Answer:
@Test public void testPassword() { assertFalse(new DropboxProtocol().isPasswordConfigurable()); }
|
### Question:
DropboxTouchFeature extends DefaultTouchFeature<String> { @Override public boolean isSupported(final Path workdir, final String filename) { if(StringUtils.startsWith(filename, "~$")) { return false; } if(StringUtils.startsWith(filename, "~") && StringUtils.endsWith(filename, ".tmp")) { return false; } return true; } DropboxTouchFeature(final DropboxSession session); @Override boolean isSupported(final Path workdir, final String filename); }### Answer:
@Test(expected = AccessDeniedException.class) public void testDisallowedName() throws Exception { final DropboxTouchFeature touch = new DropboxTouchFeature(session); final Path file = new Path(new DropboxHomeFinderFeature(session).find(), String.format("~%s.tmp", UUID.randomUUID().toString()), EnumSet.of(Path.Type.file)); assertFalse(touch.isSupported(new DropboxHomeFinderFeature(session).find(), file.getName())); touch.touch(file, new TransferStatus()); }
|
### Question:
DropboxDeleteFeature implements Delete { @Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path file : files.keySet()) { try { callback.delete(file); if(containerService.isContainer(file)) { new DbxUserFilesRequests(session.getClient(file.getParent())).deleteV2(file.getAbsolute()); } else { new DbxUserFilesRequests(session.getClient(file)).deleteV2(containerService.getKey(file)); } } catch(DbxException e) { throw new DropboxExceptionMappingService().map("Cannot delete {0}", e, file); } } } DropboxDeleteFeature(final DropboxSession session); @Override void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback); @Override boolean isRecursive(); }### Answer:
@Test(expected = NotfoundException.class) public void testDeleteNotFound() throws Exception { final Path test = new Path(new DropboxHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new DropboxDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Test public void testDeleteFile() throws Exception { final Path file = new DropboxTouchFeature(session).touch( new Path(new DropboxHomeFinderFeature(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); new DropboxDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Test public void testDeleteDirectory() throws Exception { final Path file = new DropboxDirectoryFeature(session).mkdir( new Path(new DropboxHomeFinderFeature(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.volume, Path.Type.directory)), null, new TransferStatus()); new DropboxDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DropboxQuotaFeature implements Quota { @Override public Space get() throws BackgroundException { try { final SpaceUsage usage = new DbxUserUsersRequests(session.getClient()).getSpaceUsage(); final SpaceAllocation allocation = usage.getAllocation(); if(allocation.isIndividual()) { return new Space(usage.getUsed(), allocation.getIndividualValue().getAllocated()); } else if(allocation.isTeam()) { return new Space(usage.getUsed(), allocation.getTeamValue().getAllocated()); } return new Space(0L, Long.MAX_VALUE); } catch(DbxException e) { throw new DropboxExceptionMappingService().map("Failure to read attributes of {0}", e, new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory))); } } DropboxQuotaFeature(final DropboxSession session); @Override Space get(); }### Answer:
@Test public void testGet() throws Exception { final Quota.Space quota = new DropboxQuotaFeature(session).get(); assertNotNull(quota); assertNotEquals(-1, quota.available, 0L); assertNotEquals(-1, quota.used, 0L); }
|
### Question:
DropboxTemporaryUrlProvider implements PromptUrlProvider<Void, Void> { @Override public DescriptiveUrl toDownloadUrl(final Path file, final Void options, final PasswordCallback callback) throws BackgroundException { try { if(log.isDebugEnabled()) { log.debug(String.format("Create temporary link for %s", file)); } final String link = new DbxUserFilesRequests(session.getClient(file)).getTemporaryLink(containerService.getKey(file)).getLink(); final Calendar expiry = Calendar.getInstance(TimeZone.getTimeZone("UTC")); expiry.add(Calendar.HOUR, 4); return new DescriptiveUrl(URI.create(link), DescriptiveUrl.Type.signed, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), LocaleFactory.localizedString("Temporary", "S3")) + " (" + MessageFormat.format(LocaleFactory.localizedString("Expires {0}", "S3") + ")", UserDateFormatterFactory.get().getMediumFormat(expiry.getTimeInMillis())) ); } catch(DbxException e) { throw new DropboxExceptionMappingService().map(e); } } DropboxTemporaryUrlProvider(final DropboxSession session); @Override DescriptiveUrl toDownloadUrl(final Path file, final Void options, final PasswordCallback callback); @Override DescriptiveUrl toUploadUrl(final Path file, final Void options, final PasswordCallback callback); @Override boolean isSupported(final Path file, final Type type); }### Answer:
@Test public void testToUrl() throws Exception { final DropboxTemporaryUrlProvider provider = new DropboxTemporaryUrlProvider(session); final Path file = new Path(new DropboxHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new DropboxTouchFeature(session).touch(file, new TransferStatus()); assertNotNull(provider.toDownloadUrl(file, null, new DisabledPasswordCallback()).getUrl()); new DropboxDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DropboxDirectoryFeature implements Directory<String> { @Override public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException { try { final CreateFolderResult result = new DbxUserFilesRequests(session.getClient(folder.getParent())).createFolderV2(containerService.getKey(folder), false); return new Path(folder.getParent(), folder.getName(), folder.getType(), new DropboxAttributesFinderFeature(session).toAttributes(result.getMetadata())); } catch(DbxException e) { throw new DropboxExceptionMappingService().map(e); } } DropboxDirectoryFeature(final DropboxSession session); @Override Path mkdir(final Path folder, final String region, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String name); @Override DropboxDirectoryFeature withWriter(final Write<String> writer); }### Answer:
@Test public void testDirectory() throws Exception { final Path home = new DropboxHomeFinderFeature(session).find(); final Path level1 = new DropboxDirectoryFeature(session).mkdir(new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), null, null); assertTrue(new DefaultFindFeature(session).find(level1)); assertTrue(new DropboxFindFeature(session).find(level1)); final Path level2 = new DropboxDirectoryFeature(session).mkdir(new Path(level1, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), null, null); assertTrue(new DefaultFindFeature(session).find(level2)); assertTrue(new DropboxFindFeature(session).find(level2)); new DropboxDeleteFeature(session).delete(Arrays.asList(level1), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DropboxFindFeature implements Find { @Override public boolean find(final Path file) throws BackgroundException { if(file.isRoot()) { return true; } try { return new DropboxAttributesFinderFeature(session).find(file) != PathAttributes.EMPTY; } catch(NotfoundException e) { return false; } } DropboxFindFeature(final DropboxSession session); @Override boolean find(final Path file); }### Answer:
@Test public void testFindNotFound() throws Exception { assertFalse(new DropboxFindFeature(session).find(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)))); }
@Test public void testFindHome() throws Exception { assertTrue(new DropboxFindFeature(session).find(new DropboxHomeFinderFeature(session).find())); }
@Test public void testFindDirectory() throws Exception { final Path folder = new DropboxDirectoryFeature(session).mkdir( new Path(new DropboxHomeFinderFeature(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), null, new TransferStatus()); assertTrue(new DropboxFindFeature(session).find(folder)); new DropboxDeleteFeature(session).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Test public void testFindFile() throws Exception { final Path file = new Path(new DropboxHomeFinderFeature(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new DropboxTouchFeature(session).touch(file, new TransferStatus()); assertTrue(new DropboxFindFeature(session).find(file)); new DropboxDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
S3EncryptionFeature implements Encryption { @Override public Set<Algorithm> getKeys(final Path file, final LoginCallback prompt) throws BackgroundException { return new HashSet<>(Arrays.asList(Algorithm.NONE, SSE_AES256)); } S3EncryptionFeature(final S3Session session); @Override Set<Algorithm> getKeys(final Path file, final LoginCallback prompt); @Override Algorithm getDefault(final Path file); @Override Algorithm getEncryption(final Path file); @Override void setEncryption(final Path file, final Algorithm setting); static final Algorithm SSE_AES256; }### Answer:
@Test public void testGetAlgorithms() throws Exception { assertEquals(2, new S3EncryptionFeature(null).getKeys( new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume)), new DisabledLoginCallback()).size()); }
|
### Question:
S3AccessControlListFeature extends DefaultAclFeature implements AclPermission { @Override public void setPermission(final Path file, final Acl acl) throws BackgroundException { try { final Path container = containerService.getContainer(file); if(null == acl.getOwner()) { acl.setOwner(file.attributes().getAcl().getOwner()); } if(null == acl.getOwner()) { final Acl permission = this.getPermission(container); acl.setOwner(permission.getOwner()); } if(containerService.isContainer(file)) { session.getClient().putBucketAcl(container.getName(), this.convert(acl)); } else { if(file.isFile() || file.isPlaceholder()) { session.getClient().putObjectAcl(container.getName(), containerService.getKey(file), this.convert(acl)); } } } catch(ServiceException e) { final BackgroundException failure = new S3ExceptionMappingService().map("Cannot change permissions of {0}", e, file); if(file.isPlaceholder()) { if(failure instanceof NotfoundException) { return; } } throw failure; } } S3AccessControlListFeature(final S3Session session); @Override Acl getPermission(final Path file); @Override void setPermission(final Path file, final Acl acl); @Override List<Acl.Role> getAvailableAclRoles(final List<Path> files); @Override List<Acl.User> getAvailableAclUsers(); }### Answer:
@Test(expected = NotfoundException.class) public void testWriteNotFound() throws Exception { final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final S3AccessControlListFeature f = new S3AccessControlListFeature(session); final Acl acl = new Acl(); acl.addAll(new Acl.GroupUser(Acl.GroupUser.EVERYONE), new Acl.Role(Acl.Role.READ)); f.setPermission(test, acl); }
|
### Question:
S3AccessControlListFeature extends DefaultAclFeature implements AclPermission { @Override public List<Acl.User> getAvailableAclUsers() { return new ArrayList<>(Arrays.asList( new Acl.CanonicalUser(), new Acl.GroupUser(Acl.GroupUser.EVERYONE, false), new Acl.EmailUser() { @Override public String getPlaceholder() { return LocaleFactory.localizedString("Amazon Customer Email Address", "S3"); } }) ); } S3AccessControlListFeature(final S3Session session); @Override Acl getPermission(final Path file); @Override void setPermission(final Path file, final Acl acl); @Override List<Acl.Role> getAvailableAclRoles(final List<Path> files); @Override List<Acl.User> getAvailableAclUsers(); }### Answer:
@Test public void testRoles() { final S3AccessControlListFeature f = new S3AccessControlListFeature(session); assertTrue(f.getAvailableAclUsers().contains(new Acl.CanonicalUser())); assertTrue(f.getAvailableAclUsers().contains(new Acl.EmailUser())); }
|
### Question:
WebsiteCloudFrontDistributionConfiguration extends CloudFrontDistributionConfiguration { @Override public String getName(final Distribution.Method method) { if(method.equals(Distribution.WEBSITE)) { return method.toString(); } return super.getName(method); } WebsiteCloudFrontDistributionConfiguration(final S3Session session, final X509TrustManager trust, final X509KeyManager key,
final Map<Path, Distribution> distributions); @Override List<Distribution.Method> getMethods(final Path container); @Override String getName(final Distribution.Method method); @Override Distribution read(final Path container, final Distribution.Method method, final LoginCallback prompt); @Override void write(final Path container, final Distribution distribution, final LoginCallback prompt); @Override @SuppressWarnings("unchecked") T getFeature(final Class<T> type, final Distribution.Method method); }### Answer:
@Test public void testGetName() { final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname())); final CloudFrontDistributionConfiguration configuration = new WebsiteCloudFrontDistributionConfiguration( session, new DisabledX509TrustManager(), new DefaultX509KeyManager(), Collections.emptyMap() ); assertEquals("Amazon CloudFront", configuration.getName()); assertEquals("Amazon CloudFront", configuration.getName(Distribution.DOWNLOAD)); assertEquals("Amazon CloudFront", configuration.getName(Distribution.STREAMING)); assertEquals("Amazon CloudFront", configuration.getName(Distribution.WEBSITE_CDN)); assertEquals("Website Configuration (HTTP)", configuration.getName(Distribution.WEBSITE)); }
|
### Question:
CloudFrontDistributionConfiguration implements DistributionConfiguration, Purge, Index, DistributionLogging, Cname { @Override public List<Distribution.Method> getMethods(final Path container) { return Arrays.asList(Distribution.DOWNLOAD, Distribution.STREAMING); } CloudFrontDistributionConfiguration(final S3Session session, final X509TrustManager trust, final X509KeyManager key,
final Map<Path, Distribution> distributions); @Override String getName(); @Override String getName(final Distribution.Method method); @Override String getHostname(); @Override DescriptiveUrlBag toUrl(final Path file); @Override List<Distribution.Method> getMethods(final Path container); @Override Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt); @Override void write(final Path file, final Distribution distribution, final LoginCallback prompt); @Override @SuppressWarnings("unchecked") T getFeature(final Class<T> type, final Distribution.Method method); @Override void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt); }### Answer:
@Test public void testGetMethods() { final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname())); assertEquals(Arrays.asList(Distribution.DOWNLOAD, Distribution.STREAMING), new CloudFrontDistributionConfiguration(session, new DisabledX509TrustManager(), new DefaultX509KeyManager(), Collections.emptyMap()).getMethods(new Path("/bbb", EnumSet.of(Path.Type.directory, Path.Type.volume)))); }
|
### Question:
CloudFrontDistributionConfiguration implements DistributionConfiguration, Purge, Index, DistributionLogging, Cname { @Override public String getName() { return LocaleFactory.localizedString("Amazon CloudFront", "S3"); } CloudFrontDistributionConfiguration(final S3Session session, final X509TrustManager trust, final X509KeyManager key,
final Map<Path, Distribution> distributions); @Override String getName(); @Override String getName(final Distribution.Method method); @Override String getHostname(); @Override DescriptiveUrlBag toUrl(final Path file); @Override List<Distribution.Method> getMethods(final Path container); @Override Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt); @Override void write(final Path file, final Distribution distribution, final LoginCallback prompt); @Override @SuppressWarnings("unchecked") T getFeature(final Class<T> type, final Distribution.Method method); @Override void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt); }### Answer:
@Test public void testGetName() { final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname())); final DistributionConfiguration configuration = new CloudFrontDistributionConfiguration( session, new DisabledX509TrustManager(), new DefaultX509KeyManager(), Collections.emptyMap()); assertEquals("Amazon CloudFront", configuration.getName()); assertEquals("Amazon CloudFront", configuration.getName(Distribution.CUSTOM)); }
|
### Question:
CloudFrontDistributionConfiguration implements DistributionConfiguration, Purge, Index, DistributionLogging, Cname { protected URI getOrigin(final Path container, final Distribution.Method method) { return URI.create(String.format("http: } CloudFrontDistributionConfiguration(final S3Session session, final X509TrustManager trust, final X509KeyManager key,
final Map<Path, Distribution> distributions); @Override String getName(); @Override String getName(final Distribution.Method method); @Override String getHostname(); @Override DescriptiveUrlBag toUrl(final Path file); @Override List<Distribution.Method> getMethods(final Path container); @Override Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt); @Override void write(final Path file, final Distribution distribution, final LoginCallback prompt); @Override @SuppressWarnings("unchecked") T getFeature(final Class<T> type, final Distribution.Method method); @Override void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt); }### Answer:
@Test public void testGetOrigin() { final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname())); final CloudFrontDistributionConfiguration configuration = new CloudFrontDistributionConfiguration(session, new DisabledX509TrustManager(), new DefaultX509KeyManager(), Collections.emptyMap()); assertEquals("bbb.s3.amazonaws.com", configuration.getOrigin(new Path("/bbb", EnumSet.of(Path.Type.directory, Path.Type.volume)), Distribution.DOWNLOAD).getHost()); }
|
### Question:
UDTSocket extends NetSocketUDT { @Override public void connect(final SocketAddress endpoint, final int timeout) throws IOException { final CountDownLatch signal = new CountDownLatch(1); final Thread t = threadFactory.newThread(new Runnable() { @Override public void run() { try { connect(endpoint); } catch(IOException e) { exception = e; } finally { signal.countDown(); } } }); t.start(); try { if(!signal.await(timeout, TimeUnit.MILLISECONDS)) { throw new SocketTimeoutException(); } } catch(InterruptedException e) { final SocketTimeoutException s = new SocketTimeoutException(e.getMessage()); s.initCause(e); throw s; } if(exception != null) { throw exception; } } UDTSocket(); @Override void connect(final SocketAddress endpoint, final int timeout); @Override void setSoLinger(final boolean on, final int linger); }### Answer:
@Test(expected = SocketTimeoutException.class) public void testConnect() throws Exception { new UDTSocket().connect(new InetSocketAddress("localhost", 11111), 1000); }
|
### Question:
CloudFrontDistributionConfiguration implements DistributionConfiguration, Purge, Index, DistributionLogging, Cname { @Override public String getHostname() { return "cloudfront.amazonaws.com"; } CloudFrontDistributionConfiguration(final S3Session session, final X509TrustManager trust, final X509KeyManager key,
final Map<Path, Distribution> distributions); @Override String getName(); @Override String getName(final Distribution.Method method); @Override String getHostname(); @Override DescriptiveUrlBag toUrl(final Path file); @Override List<Distribution.Method> getMethods(final Path container); @Override Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt); @Override void write(final Path file, final Distribution distribution, final LoginCallback prompt); @Override @SuppressWarnings("unchecked") T getFeature(final Class<T> type, final Distribution.Method method); @Override void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt); }### Answer:
@Test public void testProtocol() { assertEquals("cloudfront.amazonaws.com", new CloudFrontDistributionConfiguration( new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname())), new DisabledX509TrustManager(), new DefaultX509KeyManager(), Collections.emptyMap()).getHostname()); }
|
### Question:
CustomOriginCloudFrontDistributionConfiguration extends CloudFrontDistributionConfiguration { @Override public List<Distribution.Method> getMethods(final Path container) { return Collections.singletonList(Distribution.CUSTOM); } CustomOriginCloudFrontDistributionConfiguration(final Host origin,
final X509TrustManager trust,
final X509KeyManager key); @Override Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt); @Override void write(final Path file, final Distribution distribution, final LoginCallback prompt); @Override List<Distribution.Method> getMethods(final Path container); @Override DescriptiveUrlBag toUrl(final Path file); }### Answer:
@Test public void testGetMethods() { assertEquals(Collections.singletonList(Distribution.CUSTOM), new CustomOriginCloudFrontDistributionConfiguration(new Host(new TestProtocol()), new DefaultX509TrustManager(), new DefaultX509KeyManager()).getMethods( new Path("/bbb", EnumSet.of(Path.Type.directory, Path.Type.volume)))); }
|
### Question:
AWSSessionCredentialsRetriever { public Credentials get() throws BackgroundException { final Host address = new HostParser(factory).get(url); final Path access = new Path(PathNormalizer.normalize(address.getDefaultPath()), EnumSet.of(Path.Type.file)); address.setDefaultPath(String.valueOf(Path.DELIMITER)); final DAVSession connection = new DAVSession(address, trust, key); connection.withListener(transcript).open(ProxyFactory.get().find(address), new DisabledHostKeyCallback(), new DisabledLoginCallback()); final InputStream in = new DAVReadFeature(connection).read(access, new TransferStatus(), new DisabledConnectionCallback()); try { final Credentials credentials = this.parse(in); connection.close(); return credentials; } finally { connection.removeListener(transcript); } } AWSSessionCredentialsRetriever(final X509TrustManager trust, final X509KeyManager key, final TranscriptListener transcript, final String url); AWSSessionCredentialsRetriever(final X509TrustManager trust, final X509KeyManager key, final ProtocolFactory factory, final TranscriptListener transcript, final String url); Credentials get(); String getUrl(); }### Answer:
@Test(expected = ConnectionTimeoutException.class) @Ignore public void testGet() throws Exception { new AWSSessionCredentialsRetriever(new DisabledX509TrustManager(), new DefaultX509KeyManager(), new ProtocolFactory(Collections.singleton(new DAVProtocol())), new DisabledTranscriptListener(), "http: .get(); }
|
### Question:
AmazonServiceExceptionMappingService extends AbstractExceptionMappingService<AmazonClientException> { @Override public BackgroundException map(final AmazonClientException e) { final StringBuilder buffer = new StringBuilder(); if(e instanceof AmazonServiceException) { final AmazonServiceException failure = (AmazonServiceException) e; this.append(buffer, failure.getErrorMessage()); switch(failure.getStatusCode()) { case HttpStatus.SC_BAD_REQUEST: switch(failure.getErrorCode()) { case "Throttling": return new RetriableAccessDeniedException(buffer.toString(), e); case "AccessDeniedException": return new AccessDeniedException(buffer.toString(), e); case "UnrecognizedClientException": return new LoginFailureException(buffer.toString(), e); } case HttpStatus.SC_FORBIDDEN: switch(failure.getErrorCode()) { case "SignatureDoesNotMatch": return new LoginFailureException(buffer.toString(), e); case "InvalidAccessKeyId": return new LoginFailureException(buffer.toString(), e); case "InvalidClientTokenId": return new LoginFailureException(buffer.toString(), e); case "InvalidSecurity": return new LoginFailureException(buffer.toString(), e); case "MissingClientTokenId": return new LoginFailureException(buffer.toString(), e); case "MissingAuthenticationToken": return new LoginFailureException(buffer.toString(), e); } } return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(failure.getStatusCode(), buffer.toString())); } this.append(buffer, e.getMessage()); return this.wrap(e, buffer); } @Override BackgroundException map(final AmazonClientException e); }### Answer:
@Test public void testLoginFailure() { final AmazonServiceException f = new AmazonServiceException("message", null); f.setStatusCode(401); assertTrue(new AmazonServiceExceptionMappingService().map(f) instanceof LoginFailureException); }
@Test public void testAccessFailure() { final AmazonServiceException f = new AmazonServiceException("message", null); f.setStatusCode(403); f.setErrorCode("AccessDenied"); assertTrue(new AmazonServiceExceptionMappingService().map(f) instanceof AccessDeniedException); f.setErrorCode("SignatureDoesNotMatch"); assertTrue(new AmazonServiceExceptionMappingService().map(f) instanceof LoginFailureException); }
|
### Question:
FTPWorkdirService extends DefaultHomeFinderService { @Override public Path find() throws BackgroundException { final Path home = super.find(); if(home == DEFAULT_HOME) { final String directory; try { directory = session.getClient().printWorkingDirectory(); if(null == directory) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } return new Path(PathNormalizer.normalize(directory), directory.equals(String.valueOf(Path.DELIMITER)) ? EnumSet.of(Path.Type.volume, Path.Type.directory) : EnumSet.of(Path.Type.directory)); } catch(IOException e) { throw new FTPExceptionMappingService().map(e); } } return home; } FTPWorkdirService(final FTPSession session); @Override Path find(); }### Answer:
@Test public void testDefaultPath() throws Exception { assertEquals("/", new FTPWorkdirService(session).find().getAbsolute()); }
|
### Question:
FTPStatListService implements ListService { @Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final int response = session.getClient().stat(directory.getAbsolute()); if(FTPReply.isPositiveCompletion(response)) { return reader.read(directory, this.parse(response, session.getClient().getReplyStrings()), listener); } else { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } } catch(IOException e) { throw new FTPExceptionMappingService().map("Listing directory {0} failed", e, directory); } } FTPStatListService(final FTPSession session, final FTPFileEntryParser parser); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); }### Answer:
@Test public void testList() throws Exception { final ListService service = new FTPStatListService(session, new CompositeFileEntryParser(Collections.singletonList(new UnixFTPEntryParser()))); final Path directory = new FTPWorkdirService(session).find(); final Path file = new Path(directory, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new FTPTouchFeature(session).touch(file, new TransferStatus()); final AttributedList<Path> list = service.list(directory, new DisabledListProgressListener()); assertTrue(list.contains(file)); }
|
### Question:
FTPMlsdListService implements ListService { @Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { if(!session.getClient().changeWorkingDirectory(directory.getAbsolute())) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } if(!session.getClient().setFileType(FTPClient.ASCII_FILE_TYPE)) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } final List<String> list = new DataConnectionActionExecutor(session).data(new DataConnectionAction<List<String>>() { @Override public List<String> execute() throws BackgroundException { try { return session.getClient().list(FTPCmd.MLSD); } catch(IOException e) { throw new FTPExceptionMappingService().map(e); } } }, listener); return reader.read(directory, list, listener); } catch(IOException e) { throw new FTPExceptionMappingService().map("Listing directory {0} failed", e, directory); } } FTPMlsdListService(final FTPSession session); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); }### Answer:
@Test public void testList() throws Exception { final ListService list = new FTPMlsdListService(session); final Path directory = new FTPWorkdirService(session).find(); assertFalse(list.list(directory, new DisabledListProgressListener()).isEmpty()); }
|
### Question:
FTPMlsdListResponseReader implements FTPDataResponseReader { protected long parseTimestamp(final String timestamp) { if(null == timestamp) { return -1; } try { final Date parsed = new MDTMSecondsDateFormatter().parse(timestamp); return parsed.getTime(); } catch(InvalidDateException e) { log.warn("Failed to parse timestamp:" + e.getMessage()); try { final Date parsed = new MDTMMillisecondsDateFormatter().parse(timestamp); return parsed.getTime(); } catch(InvalidDateException f) { log.warn("Failed to parse timestamp:" + f.getMessage()); } } log.error(String.format("Failed to parse timestamp %s", timestamp)); return -1; } FTPMlsdListResponseReader(); @Override AttributedList<Path> read(final Path directory, final List<String> replies, final ListProgressListener listener); }### Answer:
@Test public void testParseTimestamp() { final long time = new FTPMlsdListResponseReader().parseTimestamp("20130709111201"); assertEquals(1373368321000L, time); }
@Test public void testParseTimestampInvalid() { final long time = new FTPMlsdListResponseReader().parseTimestamp("2013"); assertEquals(-1L, time); }
|
### Question:
FTPUnixPermissionFeature extends DefaultUnixPermissionFeature implements UnixPermission { @Override public void setUnixPermission(final Path file, final Permission permission) throws BackgroundException { if(failure != null) { if(log.isDebugEnabled()) { log.debug(String.format("Skip setting permission for %s due to previous failure %s", file, failure.getMessage())); } throw failure; } try { if(!session.getClient().sendSiteCommand(String.format("CHMOD %s %s", permission.getMode(), file.getAbsolute()))) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } } catch(IOException e) { throw failure = new FTPExceptionMappingService().map("Cannot change permissions of {0}", e, file); } } FTPUnixPermissionFeature(final FTPSession session); @Override void setUnixOwner(final Path file, final String owner); @Override void setUnixGroup(final Path file, final String group); @Override Permission getUnixPermission(final Path file); @Override void setUnixPermission(final Path file, final Permission permission); }### Answer:
@Test(expected = InteroperabilityException.class) public void testSetUnixPermission() throws Exception { final FTPWorkdirService workdir = new FTPWorkdirService(session); final Path home = workdir.find(); final Path test = new Path(workdir.find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new FTPTouchFeature(session).touch(test, new TransferStatus()); new FTPUnixPermissionFeature(session).setUnixPermission(test, new Permission(666)); assertEquals("666", new FTPListService(session, null, TimeZone.getDefault()).list(home, new DisabledListProgressListener()).get(test).attributes().getPermission().getMode()); new FTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
FTPAttributesFinderFeature implements AttributesFinder { @Override public PathAttributes find(final Path file) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(session.getClient().hasFeature(FTPCmd.MLST.getCommand())) { if(!FTPReply.isPositiveCompletion(session.getClient().sendCommand(FTPCmd.MLST, file.getAbsolute()))) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } final FTPDataResponseReader reader = new FTPMlsdListResponseReader(); final AttributedList<Path> attributes = reader.read(file.getParent(), Arrays.asList(session.getClient().getReplyStrings()), new DisabledListProgressListener()); if(attributes.contains(file)) { return attributes.get(attributes.indexOf(file)).attributes(); } } throw new InteroperabilityException("No support for MLST in reply to FEAT"); } catch(IOException e) { throw new FTPExceptionMappingService().map("Failure to read attributes of {0}", e, file); } } FTPAttributesFinderFeature(FTPSession session); @Override PathAttributes find(final Path file); }### Answer:
@Test public void testAttributesWrongFiletype() throws Exception { final FTPAttributesFinderFeature f = new FTPAttributesFinderFeature(session); final Path file = new FTPTouchFeature(session).touch(new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)), new TransferStatus()); final Attributes attributes = f.find(file); assertEquals(0L, attributes.getSize()); try { f.find(new Path(new FTPWorkdirService(session).find(), "test", EnumSet.of(Path.Type.directory))); fail(); } catch(NotfoundException | InteroperabilityException e) { } }
|
### Question:
FTPCommandFeature implements Command { @Override public void send(final String command, final ProgressListener progress, final TranscriptListener transcript) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("Send command %s", command)); } progress.message(command); final ProtocolCommandListener listener = new LoggingProtocolCommandListener(transcript); try { session.getClient().addProtocolCommandListener(listener); session.getClient().sendSiteCommand(command); } catch(IOException e) { throw new FTPExceptionMappingService().map(e); } finally { session.getClient().removeProtocolCommandListener(listener); } } FTPCommandFeature(final FTPSession session); @Override void send(final String command, final ProgressListener progress, final TranscriptListener transcript); }### Answer:
@Test public void testSend() throws Exception { final StringBuilder t = new StringBuilder(); new FTPCommandFeature(session).send("HELP", new ProgressListener() { @Override public void message(final String message) { assertEquals("HELP", message); } }, new TranscriptListener() { @Override public void log(final Type request, final String message) { switch(request) { case response: t.append(message); } } }); assertNotNull(t.toString()); }
|
### Question:
FTPDeleteFeature implements Delete { @Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path file : files.keySet()) { callback.delete(file); try { if(file.isFile() || file.isSymbolicLink()) { if(!session.getClient().deleteFile(file.getAbsolute())) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } } else if(file.isDirectory()) { if(!session.getClient().changeWorkingDirectory(file.getParent().getAbsolute())) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } if(!session.getClient().removeDirectory(file.getAbsolute())) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } } } catch(IOException e) { throw new FTPExceptionMappingService().map("Cannot delete {0}", e, file); } } } FTPDeleteFeature(final FTPSession session); @Override void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback); @Override boolean isSupported(final Path file); }### Answer:
@Test public void testDeleteNotFound() throws Exception { final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); try { new FTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); fail(); } catch(NotfoundException | AccessDeniedException e) { } }
@Test public void testDeleteDirectory() throws Exception { final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); new FTPDirectoryFeature(session).mkdir(test, null, new TransferStatus()); new FTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
FTPDirectoryFeature implements Directory<Integer> { @Override public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException { try { if(!session.getClient().makeDirectory(folder.getAbsolute())) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } } catch(IOException e) { throw new FTPExceptionMappingService().map("Cannot create folder {0}", e, folder); } return new Path(folder.getParent(), folder.getName(), folder.getType(), new DefaultAttributesFinderFeature(session).find(folder)); } FTPDirectoryFeature(final FTPSession session); @Override Path mkdir(final Path folder, final String region, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String name); @Override FTPDirectoryFeature withWriter(final Write writer); }### Answer:
@Test public void testMakeDirectory() throws Exception { final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); new FTPDirectoryFeature(session).mkdir(test, null, new TransferStatus()); assertTrue(session.getFeature(Find.class).find(test)); new FTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(session.getFeature(Find.class).find(test)); }
|
### Question:
FTPMFMTTimestampFeature extends DefaultTimestampFeature implements Timestamp { @Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { if(failure != null) { if(log.isDebugEnabled()) { log.debug(String.format("Skip setting timestamp for %s due to previous failure %s", file, failure.getMessage())); } throw new FTPExceptionMappingService().map("Cannot change timestamp of {0}", failure, file); } try { final MDTMSecondsDateFormatter formatter = new MDTMSecondsDateFormatter(); if(!session.getClient().setModificationTime(file.getAbsolute(), formatter.format(status.getTimestamp(), TimeZone.getTimeZone("UTC")))) { throw failure = new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } } catch(IOException e) { throw new FTPExceptionMappingService().map("Cannot change timestamp of {0}", e, file); } } FTPMFMTTimestampFeature(final FTPSession session); @Override void setTimestamp(final Path file, final TransferStatus status); }### Answer:
@Test public void testSetTimestamp() throws Exception { final Path home = new FTPWorkdirService(session).find(); final long modified = System.currentTimeMillis(); final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new FTPTouchFeature(session).touch(test, new TransferStatus()); new FTPMFMTTimestampFeature(session).setTimestamp(test, modified); assertEquals(modified / 1000 * 1000, new FTPListService(session, null, TimeZone.getDefault()).list(home, new DisabledListProgressListener()).get(test).attributes().getModificationDate()); new FTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
FTPExceptionMappingService extends AbstractExceptionMappingService<IOException> { @Override public BackgroundException map(final IOException e) { final StringBuilder buffer = new StringBuilder(); this.append(buffer, e.getMessage()); if(e instanceof FTPConnectionClosedException) { return new ConnectionRefusedException(buffer.toString(), e); } if(e instanceof FTPException) { return this.handle((FTPException) e, buffer); } if(e instanceof MalformedServerReplyException) { return new InteroperabilityException(buffer.toString(), e); } return new DefaultIOExceptionMappingService().map(e); } @Override BackgroundException map(final IOException e); }### Answer:
@Test public void testMap() { assertEquals(ConnectionRefusedException.class, new FTPExceptionMappingService().map(new SocketException("Software caused connection abort")).getClass()); assertEquals(ConnectionRefusedException.class, new FTPExceptionMappingService().map(new SocketException("Socket closed")).getClass()); }
@Test public void testQuota() { assertTrue(new FTPExceptionMappingService().map(new FTPException(452, "")) instanceof QuotaException); }
@Test public void testLogin() { assertTrue(new FTPExceptionMappingService().map(new FTPException(530, "")) instanceof LoginFailureException); }
@Test public void testFile() { assertTrue(new FTPExceptionMappingService().map(new FTPException(550, "")) instanceof NotfoundException); }
@Test public void testTrim() { assertEquals("M. Please contact your web hosting service provider for assistance.", new FTPExceptionMappingService().map(new FTPException(500, "m\n")).getDetail()); }
@Test public void testSocketTimeout() { assertEquals(ConnectionTimeoutException.class, new FTPExceptionMappingService() .map(new SocketTimeoutException()).getClass()); assertEquals(ConnectionTimeoutException.class, new FTPExceptionMappingService() .map("message", new SocketTimeoutException()).getClass()); assertEquals(ConnectionTimeoutException.class, new FTPExceptionMappingService() .map("message", new SocketTimeoutException(), new Path("/f", EnumSet.of(Path.Type.file))).getClass()); }
|
### Question:
FTPParserSelector { public CompositeFileEntryParser getParser(final String system) { return this.getParser(system, null); } CompositeFileEntryParser getParser(final String system); CompositeFileEntryParser getParser(final String system, final TimeZone zone); }### Answer:
@Test public void testGetParser() { assertNotNull(new FTPParserSelector().getParser(null)); }
@Test public void testGetMVS() { final CompositeFileEntryParser parser = new FTPParserSelector().getParser("MVS is the operating system of this server. FTP Server is running on z/OS."); final String line = "drwxr-xr-x 6 START2 SYS1 8192 Oct 28 2008 ADCD"; parser.preParse(Arrays.asList("total 66", line)); assertNotNull(parser.parseFTPEntry(line)); }
|
### Question:
FTPUTIMETimestampFeature extends DefaultTimestampFeature implements Timestamp { @Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { if(failure != null) { if(log.isDebugEnabled()) { log.debug(String.format("Skip setting timestamp for %s due to previous failure %s", file, failure.getMessage())); } throw new FTPExceptionMappingService().map("Cannot change timestamp of {0}", failure, file); } try { final MDTMSecondsDateFormatter formatter = new MDTMSecondsDateFormatter(); if(!session.getClient().sendSiteCommand(String.format("UTIME %s %s %s %s UTC", file.getAbsolute(), formatter.format(new Date(System.currentTimeMillis()), TimeZone.getTimeZone("UTC")), formatter.format(new Date(status.getTimestamp()), TimeZone.getTimeZone("UTC")), formatter.format(new Date(status.getTimestamp()), TimeZone.getTimeZone("UTC"))))) { throw failure = new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } } catch(IOException e) { throw new FTPExceptionMappingService().map("Cannot change timestamp of {0}", e, file); } } FTPUTIMETimestampFeature(final FTPSession session); @Override void setTimestamp(final Path file, final TransferStatus status); }### Answer:
@Test(expected = BackgroundException.class) public void testSetTimestamp() throws Exception { final FTPWorkdirService workdir = new FTPWorkdirService(session); final Path home = workdir.find(); final long modified = System.currentTimeMillis(); final Path test = new Path(workdir.find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new FTPTouchFeature(session).touch(test, new TransferStatus()); new FTPUTIMETimestampFeature(session).setTimestamp(test, modified); new FTPDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
AzureProtocol extends AbstractProtocol { @Override public boolean validate(final Credentials credentials, final LoginOptions options) { if(super.validate(credentials, options)) { if(options.password) { return Base64.validateIsBase64String(credentials.getPassword()); } return true; } return false; } @Override String getName(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override boolean isHostnameConfigurable(); @Override boolean isPortConfigurable(); @Override String getIdentifier(); @Override String getDescription(); @Override Scheme getScheme(); @Override boolean validate(final Credentials credentials, final LoginOptions options); @Override DirectoryTimestamp getDirectoryTimestamp(); @Override Comparator<String> getListComparator(); }### Answer:
@Test public void testValidateCredentials() { assertFalse(new AzureProtocol().validate(new Credentials("u"), new LoginOptions(new AzureProtocol()))); assertFalse(new AzureProtocol().validate(new Credentials("u", "abc"), new LoginOptions(new AzureProtocol()))); assertTrue(new AzureProtocol().validate(new Credentials("u", Base64.encodeBase64String("abc".getBytes())), new LoginOptions(new AzureProtocol()))); }
|
### Question:
AzureMoveFeature implements Move { @Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { final Path copy = new AzureCopyFeature(session, context).copy(file, renamed, new TransferStatus().length(file.attributes().getSize()), connectionCallback); delete.delete(Collections.singletonList(file), connectionCallback, callback); return copy; } AzureMoveFeature(final AzureSession session, final OperationContext context); @Override boolean isSupported(final Path source, final Path target); @Override Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback); }### Answer:
@Test public void testMove() throws Exception { final Host host = new Host(new AzureProtocol(), "kahy9boj3eib.blob.core.windows.net", new Credentials( System.getProperties().getProperty("azure.account"), System.getProperties().getProperty("azure.key") )); final AzureSession session = new AzureSession(host); new LoginConnectionService(new DisabledLoginCallback(), new DisabledHostKeyCallback(), new DisabledPasswordStore(), new DisabledProgressListener()).connect(session, PathCache.empty(), new DisabledCancelCallback()); final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new AzureTouchFeature(session, null).touch(test, new TransferStatus()); assertTrue(new AzureFindFeature(session, null).find(test)); final Path target = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new AzureMoveFeature(session, null).move(test, target, new TransferStatus(), new Delete.DisabledCallback(), new DisabledConnectionCallback()); assertFalse(new AzureFindFeature(session, null).find(test)); assertTrue(new AzureFindFeature(session, null).find(target)); new AzureDeleteFeature(session, null).delete(Collections.<Path>singletonList(target), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
AzureMoveFeature implements Move { @Override public boolean isSupported(final Path source, final Path target) { return !containerService.isContainer(source); } AzureMoveFeature(final AzureSession session, final OperationContext context); @Override boolean isSupported(final Path source, final Path target); @Override Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback); }### Answer:
@Test public void testSupport() { final Path c = new Path("/c", EnumSet.of(Path.Type.directory)); assertFalse(new AzureMoveFeature(null, null).isSupported(c, c)); final Path cf = new Path("/c/f", EnumSet.of(Path.Type.directory)); assertTrue(new AzureMoveFeature(null, null).isSupported(cf, cf)); }
|
### Question:
AzureTouchFeature implements Touch<Void> { @Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { status.setChecksum(writer.checksum(file, status).compute(new NullInputStream(0L), status)); new DefaultStreamCloser().close(writer.write(file, status, new DisabledConnectionCallback())); return new Path(file.getParent(), file.getName(), file.getType(), new AzureAttributesFinderFeature(session, context).find(file)); } AzureTouchFeature(final AzureSession session, final OperationContext context); @Override boolean isSupported(final Path workdir, final String filename); @Override Path touch(final Path file, final TransferStatus status); @Override AzureTouchFeature withWriter(final Write<Void> writer); }### Answer:
@Test public void testTouchFileStartWithDot() throws Exception { final Host host = new Host(new AzureProtocol(), "kahy9boj3eib.blob.core.windows.net", new Credentials( System.getProperties().getProperty("azure.account"), System.getProperties().getProperty("azure.key") )); final AzureSession session = new AzureSession(host); new LoginConnectionService(new DisabledLoginCallback(), new DisabledHostKeyCallback(), new DisabledPasswordStore(), new DisabledProgressListener()).connect(session, PathCache.empty(), new DisabledCancelCallback()); final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, String.format(".%s.", UUID.randomUUID().toString()), EnumSet.of(Path.Type.file)); new AzureTouchFeature(session, null).touch(test, new TransferStatus()); new AzureDeleteFeature(session, null).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
AzureLoggingFeature implements Logging { @Override public void setConfiguration(final Path container, final LoggingConfiguration configuration) throws BackgroundException { try { final ServiceProperties properties = session.getClient().downloadServiceProperties(null, context); final LoggingProperties l = new LoggingProperties(); if(configuration.isEnabled()) { l.setLogOperationTypes(EnumSet.allOf(LoggingOperations.class)); } else { l.setLogOperationTypes(EnumSet.noneOf(LoggingOperations.class)); } properties.setLogging(l); session.getClient().uploadServiceProperties(properties, null, context); } catch(StorageException e) { throw new AzureExceptionMappingService().map("Failure to write attributes of {0}", e, container); } } AzureLoggingFeature(final AzureSession session, final OperationContext context); @Override LoggingConfiguration getConfiguration(final Path container); @Override void setConfiguration(final Path container, final LoggingConfiguration configuration); }### Answer:
@Test public void testSetConfiguration() throws Exception { final Host host = new Host(new AzureProtocol(), "kahy9boj3eib.blob.core.windows.net", new Credentials( System.getProperties().getProperty("azure.account"), System.getProperties().getProperty("azure.key") )); final AzureSession session = new AzureSession(host); new LoginConnectionService(new DisabledLoginCallback(), new DisabledHostKeyCallback(), new DisabledPasswordStore(), new DisabledProgressListener()).connect(session, PathCache.empty(), new DisabledCancelCallback()); final Path container = new Path("/cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final AzureLoggingFeature feature = new AzureLoggingFeature(session, null); feature.setConfiguration(container, new LoggingConfiguration(false)); assertFalse(feature.getConfiguration(container).isEnabled()); feature.setConfiguration(container, new LoggingConfiguration(true)); assertTrue(feature.getConfiguration(container).isEnabled()); session.close(); }
|
### Question:
LocalSession extends Session<FileSystem> { public java.nio.file.Path toPath(final Path file) throws LocalAccessDeniedException { return this.toPath(file.getAbsolute()); } LocalSession(final Host h); LocalSession(final Host h, final X509TrustManager trust, final X509KeyManager key); java.nio.file.Path toPath(final Path file); java.nio.file.Path toPath(final String path); @Override void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel); @Override @SuppressWarnings("unchecked") T _getFeature(final Class<T> type); }### Answer:
@Test public void toPath() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); assertNotNull(session.toPath("/Users/username")); assertNotNull(session.toPath("/C:\\Users\\Administrator")); assertEquals("C:\\Users\\Administrator", "/C:\\Users\\Administrator".replaceFirst("^/(.:[/\\\\])", "$1")); assertEquals("C:/Users/Administrator", "/C:/Users/Administrator".replaceFirst("^/(.:[/\\\\])", "$1")); session.close(); }
|
### Question:
S3SingleUploadService extends HttpUploadFeature<StorageObject, MessageDigest> { @Override protected InputStream decorate(final InputStream in, final MessageDigest digest) throws IOException { if(null == digest) { log.warn("MD5 calculation disabled"); return super.decorate(in, null); } else { return new DigestInputStream(super.decorate(in, digest), digest); } } S3SingleUploadService(final S3Session session, final Write<StorageObject> writer); @Override StorageObject upload(final Path file, final Local local, final BandwidthThrottle throttle,
final StreamListener listener, final TransferStatus status, final ConnectionCallback callback); @Override Upload<StorageObject> withWriter(final Write<StorageObject> writer); }### Answer:
@Test public void testDecorate() throws Exception { final NullInputStream n = new NullInputStream(1L); final S3Session session = new S3Session(new Host(new S3Protocol())); assertSame(NullInputStream.class, new S3SingleUploadService(session, new S3WriteFeature(session, new S3DisabledMultipartService())).decorate(n, null).getClass()); }
|
### Question:
LocalDeleteFeature implements Delete { @Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path file : files.keySet()) { if(file.isFile() || file.isSymbolicLink()) { callback.delete(file); try { Files.delete(session.toPath(file)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Cannot delete {0}", e, file); } } } for(Path file : files.keySet()) { if(file.isDirectory() && !file.isSymbolicLink()) { callback.delete(file); try { Files.delete(session.toPath(file)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Cannot delete {0}", e, file); } } } } LocalDeleteFeature(final LocalSession session); @Override void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback); }### Answer:
@Test public void testDelete() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); final Path file = new Path(new LocalHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new LocalTouchFeature(session).touch(file, new TransferStatus()); final Path folder = new Path(new LocalHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); new LocalDirectoryFeature(session).mkdir(folder, null, new TransferStatus()); new LocalDeleteFeature(session).delete(new ArrayList<>(Arrays.asList(file, folder)), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(Files.exists(session.toPath(file))); assertFalse(Files.exists(session.toPath(folder.getAbsolute()))); }
|
### Question:
LocalSymlinkFeature implements Symlink { @Override public void symlink(final Path file, final String target) throws BackgroundException { try { Files.createSymbolicLink(session.toPath(file), session.toPath(target)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Cannot create file {0}", e, file); } } LocalSymlinkFeature(final LocalSession session); @Override void symlink(final Path file, final String target); }### Answer:
@Test public void testSymlink() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); assumeTrue(session.isPosixFilesystem()); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); final Path workdir = new LocalHomeFinderFeature(session).find(); final Path target = new Path(workdir, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new LocalTouchFeature(session).touch(target, new TransferStatus()); final Path link = new Path(workdir, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file, AbstractPath.Type.symboliclink)); new LocalSymlinkFeature(session).symlink(link, target.getName()); assertTrue(new LocalFindFeature(session).find(link)); assertEquals(EnumSet.of(Path.Type.file, AbstractPath.Type.symboliclink), new LocalListService(session).list(workdir, new DisabledListProgressListener()).get(link).getType()); new LocalDeleteFeature(session).delete(Collections.singletonList(link), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new LocalFindFeature(session).find(link)); assertTrue(new LocalFindFeature(session).find(target)); new LocalDeleteFeature(session).delete(Collections.singletonList(target), new DisabledLoginCallback(), new Delete.DisabledCallback()); session.close(); }
|
### Question:
LocalTouchFeature implements Touch { @Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { if(file.isFile()) { try { Files.createFile(session.toPath(file)); } catch(FileAlreadyExistsException e) { } catch(IOException e) { throw new LocalExceptionMappingService().map("Cannot create file {0}", e, file); } } return new Path(file.getParent(), file.getName(), file.getType(), new LocalAttributesFinderFeature(session).find(file)); } LocalTouchFeature(final LocalSession session); @Override Path touch(final Path file, final TransferStatus status); @Override Touch withWriter(final Write writer); }### Answer:
@Test public void testTouch() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); assertNotNull(session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback())); assertTrue(session.isConnected()); assertNotNull(session.getClient()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); final Path workdir = new LocalHomeFinderFeature(session).find(); final Path test = new Path(workdir, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new LocalTouchFeature(session).touch(test, new TransferStatus()); new LocalTouchFeature(session).touch(test, new TransferStatus()); assertTrue(new LocalFindFeature(session).find(test)); final AttributedList<Path> list = new LocalListService(session).list(workdir, new DisabledListProgressListener()); assertTrue(list.contains(test)); new LocalDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); session.close(); }
|
### Question:
LocalQuotaFeature implements Quota { @Override public Space get() throws BackgroundException { final Path home = new DefaultHomeFinderService(session).find(); try { final FileStore store = Files.getFileStore(session.toPath(home)); return new Space(store.getTotalSpace() - store.getUnallocatedSpace(), store.getUnallocatedSpace()); } catch(IOException e) { throw new LocalExceptionMappingService().map("Failure to read attributes of {0}", e, home); } } LocalQuotaFeature(final LocalSession session); @Override Space get(); }### Answer:
@Test public void get() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); final Path home = new LocalHomeFinderFeature(session).find(); final Quota.Space quota = new LocalQuotaFeature(session).get(); assertNotNull(quota.used); assertNotNull(quota.available); }
|
### Question:
LocalHomeFinderFeature extends DefaultHomeFinderService { @Override public Path find() throws BackgroundException { final Path directory = super.find(); if(directory == DEFAULT_HOME) { final String home = LocalFactory.get().getAbsolute(); return this.toPath(home); } return directory; } LocalHomeFinderFeature(final LocalSession session); @Override Path find(); }### Answer:
@Test public void testFind() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); assertTrue(new LocalHomeFinderFeature(session).find().getAbsolute().endsWith( System.getProperty("user.home").replaceAll("\\\\", "/"))); session.close(); }
|
### Question:
LocalHomeFinderFeature extends DefaultHomeFinderService { protected Path toPath(final String home) { return new Path(StringUtils.replace(home, "\\", "/"), EnumSet.of(Path.Type.directory)); } LocalHomeFinderFeature(final LocalSession session); @Override Path find(); }### Answer:
@Test public void testWindowsHome() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); assertEquals("/C:/Users/Default", new LocalHomeFinderFeature(session).toPath("C:\\Users\\Default").getAbsolute()); session.close(); }
|
### Question:
DriveDeleteFeature implements Delete { @Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path file : files.keySet()) { if(file.getType().contains(Path.Type.placeholder)) { continue; } callback.delete(file); try { if(DriveHomeFinderService.TEAM_DRIVES_NAME.equals(file.getParent())) { session.getClient().teamdrives().delete(fileid.getFileid(file, new DisabledListProgressListener())).execute(); } else { if(PreferencesFactory.get().getBoolean("googledrive.delete.trash")) { final File properties = new File(); properties.setTrashed(true); session.getClient().files().update(fileid.getFileid(file, new DisabledListProgressListener()), properties) .setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute(); } else { session.getClient().files().delete(fileid.getFileid(file, new DisabledListProgressListener())) .setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute(); } } } catch(IOException e) { throw new DriveExceptionMappingService().map("Cannot delete {0}", e, file); } } } DriveDeleteFeature(final DriveSession session, final DriveFileidProvider fileid); @Override void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback); @Override boolean isSupported(final Path file); @Override boolean isRecursive(); }### Answer:
@Test(expected = NotfoundException.class) public void testDeleteNotFound() throws Exception { final Path test = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); test.attributes().setVersionId("n"); new DriveDeleteFeature(session, new DriveFileidProvider(session).withCache(cache)).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DriveProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", DriveProtocol.class.getPackage().getName(), "Drive"); } @Override String getIdentifier(); @Override String getDescription(); @Override String getName(); @Override String getPrefix(); @Override boolean isHostnameConfigurable(); @Override boolean isPasswordConfigurable(); @Override boolean isPortConfigurable(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override Scheme getScheme(); @Override DirectoryTimestamp getDirectoryTimestamp(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.googledrive.Drive", new DriveProtocol().getPrefix()); }
|
### Question:
DriveProtocol extends AbstractProtocol { @Override public boolean isPasswordConfigurable() { return false; } @Override String getIdentifier(); @Override String getDescription(); @Override String getName(); @Override String getPrefix(); @Override boolean isHostnameConfigurable(); @Override boolean isPasswordConfigurable(); @Override boolean isPortConfigurable(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override Scheme getScheme(); @Override DirectoryTimestamp getDirectoryTimestamp(); }### Answer:
@Test public void testPassword() { assertFalse(new DriveProtocol().isPasswordConfigurable()); }
|
### Question:
DriveUrlProvider implements UrlProvider { @Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DescriptiveUrlBag(); if(file.attributes().getLink() != DescriptiveUrl.EMPTY) { list.add(file.attributes().getLink()); } return list; } @Override DescriptiveUrlBag toUrl(final Path file); }### Answer:
@Test public void testToUrl() throws Exception { final DriveUrlProvider provider = new DriveUrlProvider(); final Path test = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); assertNotNull(provider.toUrl(test)); assertTrue(provider.toUrl(test).isEmpty()); new DriveTouchFeature(session, new DriveFileidProvider(session).withCache(cache)).touch(test, new TransferStatus()); new DriveDeleteFeature(session, new DriveFileidProvider(session).withCache(cache)).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DriveFindFeature implements Find { @Override public boolean find(final Path file) throws BackgroundException { try { fileid.getFileid(file, new DisabledListProgressListener()); return true; } catch(NotfoundException e) { return false; } } DriveFindFeature(final DriveSession session, final DriveFileidProvider fileid); @Override boolean find(final Path file); @Override Find withCache(final Cache<Path> cache); }### Answer:
@Test public void testFind() throws Exception { final Path file = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final DriveFileidProvider fileid = new DriveFileidProvider(session).withCache(cache); new DriveTouchFeature(session, fileid).touch(file, new TransferStatus()); assertTrue(new DriveFindFeature(session, fileid).find(file)); new DriveDeleteFeature(session, fileid).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DriveTeamDrivesListService implements ListService { @Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> children = new AttributedList<>(); String page = null; do { final TeamDriveList list = session.getClient().teamdrives().list() .setPageToken(page) .setPageSize(pagesize) .execute(); for(TeamDrive f : list.getTeamDrives()) { final Path child = new Path(directory, f.getName(), EnumSet.of(Path.Type.directory, Path.Type.volume), new PathAttributes().withVersionId(f.getId())); children.add(child); } listener.chunk(directory, children); page = list.getNextPageToken(); if(log.isDebugEnabled()) { log.debug(String.format("Continue with next page token %s", page)); } } while(page != null); return children; } catch(IOException e) { throw new DriveExceptionMappingService().map("Listing directory failed", e, directory); } } DriveTeamDrivesListService(final DriveSession session); DriveTeamDrivesListService(final DriveSession session, final int pagesize); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); }### Answer:
@Test public void list() throws Exception { final AttributedList<Path> list = new DriveTeamDrivesListService(session).list(new Path("/", EnumSet.of(Path.Type.directory)), new DisabledListProgressListener()); assertTrue(list.isEmpty()); }
|
### Question:
DriveReadFeature implements Read { @Override public boolean offset(Path file) { return true; } DriveReadFeature(final DriveSession session, final DriveFileidProvider fileid); @Override boolean offset(Path file); @Override InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback); }### Answer:
@Test public void testAppend() { assertTrue(new DriveReadFeature(null, new DriveFileidProvider(session).withCache(cache)).offset(new Path("/", EnumSet.of(Path.Type.file)))); }
|
### Question:
DriveAttributesFinderFeature implements AttributesFinder { @Override public PathAttributes find(final Path file) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } if(new PathContainerService().isContainer(file)) { return PathAttributes.EMPTY; } final Path query; if(file.getType().contains(Path.Type.placeholder)) { query = new Path(file.getParent(), FilenameUtils.removeExtension(file.getName()), file.getType(), file.attributes()); } else { query = file; } final AttributedList<Path> list = new FileidDriveListService(session, fileid, query).list(file.getParent(), new DisabledListProgressListener()); final Path found = list.find(new DriveFileidProvider.IgnoreTrashedPathPredicate(file)); if(null == found) { throw new NotfoundException(file.getAbsolute()); } return found.attributes(); } DriveAttributesFinderFeature(final DriveSession session, final DriveFileidProvider fileid); @Override PathAttributes find(final Path file); @Override AttributesFinder withCache(final Cache<Path> cache); }### Answer:
@Test public void testFind() throws Exception { final Path test = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, UUID.randomUUID().toString() + ".txt", EnumSet.of(Path.Type.file)); final DriveFileidProvider fileid = new DriveFileidProvider(session).withCache(cache); new DriveTouchFeature(session, fileid).touch(test, new TransferStatus()); final DriveAttributesFinderFeature f = new DriveAttributesFinderFeature(session, fileid); final PathAttributes attributes = f.find(test); assertEquals(0L, attributes.getSize()); assertNotNull(attributes.getVersionId()); new DriveDeleteFeature(session, fileid).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); session.close(); }
|
### Question:
DriveQuotaFeature implements Quota { @Override public Space get() throws BackgroundException { if (new DriveHomeFinderService(session).find().isChild(DriveHomeFinderService.TEAM_DRIVES_NAME)) { return new Space(0L, Long.MAX_VALUE); } try { final About about = session.getClient().about().get().setFields("user, storageQuota").execute(); final Long used = null == about.getStorageQuota().getUsageInDrive() ? 0L : about.getStorageQuota().getUsageInDrive(); final Long available = (null == about.getStorageQuota().getLimit() ? Long.MAX_VALUE : about.getStorageQuota().getLimit()) - used; return new Space(used, available); } catch(IOException e) { throw new DriveExceptionMappingService().map("Failure to read attributes of {0}", e, new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory))); } } DriveQuotaFeature(final DriveSession session); @Override Space get(); }### Answer:
@Test public void testGet() throws Exception { final Quota.Space quota = new DriveQuotaFeature(session).get(); assertNotNull(quota.available); assertNotNull(quota.used); assertNotEquals(0L, quota.available, 0L); assertNotEquals(0L, quota.used, 0L); }
|
### Question:
DriveMetadataFeature implements Metadata { @Override public void setMetadata(final Path file, final TransferStatus status) throws BackgroundException { try { final String fileid = this.fileid.getFileid(file, new DisabledListProgressListener()); final File body = new File(); body.setProperties(status.getMetadata()); session.getClient().files().update(fileid, body).setFields("properties"). setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute(); } catch(IOException e) { throw new DriveExceptionMappingService().map("Failure to write attributes of {0}", e, file); } } DriveMetadataFeature(final DriveSession session, final DriveFileidProvider fileid); @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 setMetadata() throws Exception { final Path home = DriveHomeFinderService.MYDRIVE_FOLDER; final Path test = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final DriveFileidProvider fileid = new DriveFileidProvider(session).withCache(cache); new DriveTouchFeature(session, fileid).touch(test, new TransferStatus()); assertEquals(Collections.emptyMap(), new DriveMetadataFeature(session, fileid).getMetadata(test)); new DriveMetadataFeature(session, fileid).setMetadata(test, Collections.singletonMap("test", "t")); assertEquals(Collections.singletonMap("test", "t"), new DriveMetadataFeature(session, fileid).getMetadata(test)); new DriveDeleteFeature(session, fileid).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
DriveTouchFeature implements Touch<VersionId> { @Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { try { final Drive.Files.Create insert = session.getClient().files().create(new File() .setName(file.getName()) .setMimeType(status.getMime()) .setParents(Collections.singletonList(fileid.getFileid(file.getParent(), new DisabledListProgressListener())))); final File execute = insert.setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute(); return new Path(file.getParent(), file.getName(), file.getType(), new DriveAttributesFinderFeature(session, fileid).toAttributes(execute)); } catch(IOException e) { throw new DriveExceptionMappingService().map("Cannot create file {0}", e, file); } } DriveTouchFeature(final DriveSession session, final DriveFileidProvider fileid); @Override Path touch(final Path file, final TransferStatus status); @Override DriveTouchFeature withWriter(final Write<VersionId> writer); @Override boolean isSupported(final Path workdir, final String filename); }### Answer:
@Test public void testTouch() throws Exception { final DriveFileidProvider fileid = new DriveFileidProvider(session).withCache(cache); final Path test = new DriveTouchFeature(session, fileid).touch( new Path(DriveHomeFinderService.MYDRIVE_FOLDER, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)), new TransferStatus().withMime("x-application/cyberduck")); assertNotNull(test.attributes().getVersionId()); assertEquals(test.attributes().getVersionId(), new DriveAttributesFinderFeature(session, fileid).find(test).getVersionId()); new DriveDeleteFeature(session, fileid).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
StoregateDirectoryFeature implements Directory<VersionId> { @Override public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException { try { final FilesApi files = new FilesApi(session.getClient()); final CreateFolderRequest request = new CreateFolderRequest(); request.setName(folder.getName()); request.setParentID(fileid.getFileid(folder.getParent(), new DisabledListProgressListener())); final File f = files.filesCreateFolder(request); return new Path(folder.getParent(), folder.getName(), folder.getType(), new StoregateAttributesFinderFeature(session, fileid).toAttributes(f)); } catch(ApiException e) { throw new StoregateExceptionMappingService().map("Cannot create folder {0}", e, folder); } } StoregateDirectoryFeature(final StoregateSession session, final StoregateIdProvider fileid); @Override Path mkdir(final Path folder, final String region, final TransferStatus status); @Override Directory<VersionId> withWriter(final Write<VersionId> writer); @Override boolean isSupported(final Path workdir, final String name); }### Answer:
@Test public void testCreateDirectory() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session).withCache(cache); final Path folder = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.directory)), null, new TransferStatus()); assertTrue(new DefaultFindFeature(session).find(folder)); new StoregateDeleteFeature(session, nodeid).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new DefaultFindFeature(session).find(folder)); }
|
### Question:
StoregateShareFeature implements PromptUrlProvider<Void, Void> { @Override public DescriptiveUrl toUploadUrl(final Path file, final Void options, final PasswordCallback callback) throws BackgroundException { try { final Host bookmark = session.getHost(); final CreateFileShareRequest request = new CreateFileShareRequest() .fileId(fileid.getFileid(file, new DisabledListProgressListener())) .allowUpload(true); try { request.setPassword(callback.prompt(bookmark, LocaleFactory.localizedString("Passphrase", "Cryptomator"), MessageFormat.format(LocaleFactory.localizedString("Create a passphrase required to access {0}", "Credentials"), file.getName()), new LoginOptions().keychain(false).icon(bookmark.getProtocol().disk())).getPassword()); } catch(LoginCanceledException e) { } return new DescriptiveUrl(URI.create( new FileSharesApi(session.getClient()).fileSharesPost(request).getUrl()), DescriptiveUrl.Type.signed); } catch(ApiException e) { throw new StoregateExceptionMappingService().map(e); } } StoregateShareFeature(final StoregateSession session, final StoregateIdProvider fileid); @Override boolean isSupported(final Path file, final Type type); @Override DescriptiveUrl toDownloadUrl(final Path file, final Void options, final PasswordCallback callback); @Override DescriptiveUrl toUploadUrl(final Path file, final Void options, final PasswordCallback callback); }### Answer:
@Test public void toUploadUrl() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session).withCache(cache); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus()); assertNotNull(new StoregateShareFeature(session, nodeid).toUploadUrl(room, null, new DisabledPasswordCallback()).getUrl()); new StoregateDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledPasswordCallback(), new Delete.DisabledCallback()); }
|
### Question:
StoregateAttributesFinderFeature implements AttributesFinder { @Override public PathAttributes find(final Path file) throws BackgroundException { try { final FilesApi files = new FilesApi(session.getClient()); return this.toAttributes(files.filesGet_1(URIEncoder.encode(fileid.getPrefixedPath(file)))); } catch(ApiException e) { throw new StoregateExceptionMappingService().map("Failure to read attributes of {0}", e, file); } } StoregateAttributesFinderFeature(final StoregateSession session, final StoregateIdProvider fileid); @Override PathAttributes find(final Path file); PathAttributes toAttributes(final File f); }### Answer:
@Test public void testFind() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session).withCache(cache); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus()); assertTrue(room.attributes().getPermission().isExecutable()); final Path test = new StoregateTouchFeature(session, nodeid).touch( new Path(room, String.format("%s", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.file)), new TransferStatus()); final PathAttributes attr = new StoregateAttributesFinderFeature(session, nodeid).find(test); assertNotEquals(0L, attr.getModificationDate()); assertEquals(Checksum.NONE, attr.getChecksum()); assertNull(attr.getETag()); assertNull(attr.getVersionId()); assertFalse(attr.getPermission().isExecutable()); assertTrue(attr.getPermission().isReadable()); assertTrue(attr.getPermission().isWritable()); new StoregateDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledPasswordCallback(), new Delete.DisabledCallback()); }
|
### Question:
StoregateExceptionMappingService extends AbstractExceptionMappingService<ApiException> { @Override public BackgroundException map(final ApiException failure) { for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(cause instanceof SocketException) { return new DefaultSocketExceptionMappingService().map((SocketException) cause); } if(cause instanceof HttpResponseException) { return new DefaultHttpResponseExceptionMappingService().map((HttpResponseException) cause); } if(cause instanceof IOException) { return new DefaultIOExceptionMappingService().map((IOException) cause); } if(cause instanceof IllegalStateException) { return new ConnectionCanceledException(cause); } } return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(failure.getCode(), failure.getMessage())); } @Override BackgroundException map(final ApiException failure); }### Answer:
@Test public void testDisconnect() { final StoregateExceptionMappingService service = new StoregateExceptionMappingService(); assertEquals(ConnectionRefusedException.class, service.map( new ApiException(new ProcessingException(new SSLException(new SocketException("Operation timed out (Read failed)"))))).getClass()); }
|
### Question:
MantaWriteFeature implements Write<Void> { @Override public HttpResponseOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) { final OutputStream putStream = session.getClient().putAsOutputStream(file.getAbsolute()); return new HttpResponseOutputStream<Void>(putStream) { @Override public Void getStatus() { return null; } }; } MantaWriteFeature(final MantaSession session); MantaWriteFeature(final MantaSession session, final Find finder, final AttributesFinder attributes); @Override HttpResponseOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback); @Override Append append(final Path file, final Long length, final Cache<Path> cache); @Override boolean temporary(); @Override boolean random(); }### Answer:
@Test public void testWrite() throws Exception { final MantaWriteFeature feature = new MantaWriteFeature(session); final Path container = new MantaDirectoryFeature(session).mkdir(randomDirectory(), "", new TransferStatus()); final byte[] content = RandomUtils.nextBytes(5 * 1024 * 1024); final TransferStatus status = new TransferStatus(); status.setLength(content.length); final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback()); final ByteArrayInputStream in = new ByteArrayInputStream(content); final byte[] buffer = new byte[32 * 1024]; assertEquals(content.length, IOUtils.copyLarge(in, out, buffer)); in.close(); out.close(); assertNull(out.getStatus()); assertTrue(new DefaultFindFeature(session).find(file)); final byte[] compare = new byte[content.length]; final InputStream stream = new MantaReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback()); IOUtils.readFully(stream, compare); stream.close(); assertArrayEquals(content, compare); new MantaDeleteFeature(session).delete(Collections.singletonList(container), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
MantaHomeFinderFeature extends DefaultHomeFinderService { @Override public Path find() throws BackgroundException { final Path home = super.find(); if(home == DEFAULT_HOME) { return new MantaAccountHomeInfo(session.getHost().getCredentials().getUsername(), session.getHost().getDefaultPath()).getNormalizedHomePath(); } return home; } MantaHomeFinderFeature(final MantaSession session); @Override Path find(); }### Answer:
@Test public void testHomeFeature() throws BackgroundException { final Path drive = new MantaHomeFinderFeature(session).find(); assertNotNull(drive); assertFalse(drive.isRoot()); assertTrue(drive.isPlaceholder()); assertNotEquals("null", drive.getName()); assertFalse(StringUtils.isEmpty(drive.getName())); }
|
### Question:
MantaProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", MantaProtocol.class.getPackage().getName(), "Manta"); } @Override String getIdentifier(); @Override String getDescription(); @Override String getName(); @Override Type getType(); @Override String getPrefix(); @Override Scheme getScheme(); @Override String disk(); @Override boolean isUsernameConfigurable(); @Override boolean isHostnameConfigurable(); @Override boolean isPasswordConfigurable(); @Override boolean isPrivateKeyConfigurable(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.manta.Manta", new MantaProtocol().getPrefix()); }
|
### Question:
MantaAttributesFinderFeature implements AttributesFinder { @Override public PathAttributes find(final Path file) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { return new MantaObjectAttributeAdapter(session) .convert(session.getClient().head(file.getAbsolute())); } catch(MantaException e) { throw new MantaExceptionMappingService().map("Failure to read attributes of {0}", e, file); } catch(MantaClientHttpResponseException e) { throw new MantaHttpExceptionMappingService().map("Failure to read attributes of {0}", e, file); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Failure to read attributes of {0}", e, file); } } MantaAttributesFinderFeature(final MantaSession session); @Override PathAttributes find(final Path file); }### Answer:
@Test(expected = NotfoundException.class) public void testFindNotFound() throws Exception { try { new MantaAttributesFinderFeature(session).find(randomFile()); } catch(NotfoundException e) { assertEquals("Not Found. Please contact your web hosting service provider for assistance.", e.getDetail()); throw e; } }
@Test public void testFindFile() throws Exception { final Path file = randomFile(); new MantaTouchFeature(session).touch(file, new TransferStatus().withMime("x-application/cyberduck")); final PathAttributes attributes = new MantaAttributesFinderFeature(session).find(file); assertNotNull(attributes); assertEquals(-1L, attributes.getCreationDate()); assertNotEquals(-1L, attributes.getModificationDate()); assertNotNull(attributes.getETag()); new MantaDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
MantaTouchFeature implements Touch { @Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { try { if(!session.getClient().existsAndIsAccessible(file.getParent().getAbsolute())) { session.getClient().putDirectory(file.getParent().getAbsolute()); } session.getClient().put(file.getAbsolute(), new byte[0]); } catch(MantaException e) { throw new MantaExceptionMappingService().map("Cannot create file {0}", e, file); } catch(MantaClientHttpResponseException e) { throw new MantaHttpExceptionMappingService().map("Cannot create file {0}", e, file); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Cannot create file {0}", e, file); } return file; } MantaTouchFeature(final MantaSession session); @Override Path touch(final Path file, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String filename); @Override Touch withWriter(final Write writer); }### Answer:
@Test public void testTouch() throws Exception { final Path file = new Path( testPathPrefix, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new MantaTouchFeature(session).touch(file, new TransferStatus().withMime("x-application/cyberduck")); assertNotNull(new MantaAttributesFinderFeature(session).find(file)); new MantaDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Test public void testWhitespaceTouch() throws Exception { final RandomStringService randomStringService = new AlphanumericRandomStringService(); final Path file = new Path( testPathPrefix, String.format("%s %s", randomStringService.random(), randomStringService.random()), EnumSet.of(Path.Type.file)); new MantaTouchFeature(session).touch(file, new TransferStatus().withMime("x-application/cyberduck")); assertNotNull(new MantaAttributesFinderFeature(session).find(file)); new MantaDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
MantaDirectoryFeature implements Directory { @Override public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException { try { session.getClient().putDirectory(folder.getAbsolute()); } catch(MantaException e) { throw new MantaExceptionMappingService().map("Cannot create folder {0}", e, folder); } catch(MantaClientHttpResponseException e) { throw new MantaHttpExceptionMappingService().map("Cannot create folder {0}", e, folder); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Cannot create folder {0}", e, folder); } return new Path(folder.getParent(), folder.getName(), folder.getType(), new MantaAttributesFinderFeature(session).find(folder)); } MantaDirectoryFeature(MantaSession session); @Override Path mkdir(final Path folder, final String region, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String name); @Override Directory withWriter(final Write writer); }### Answer:
@Test public void testMkdir() throws Exception { final Path target = new MantaDirectoryFeature(session).mkdir(randomDirectory(), null, null); final PathAttributes found = new MantaAttributesFinderFeature(session).find(target); assertNotEquals(Permission.EMPTY, found.getPermission()); new MantaDeleteFeature(session).delete(Collections.singletonList(target), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Test public void testWhitespaceMkdir() throws Exception { final RandomStringService randomStringService = new AlphanumericRandomStringService(); final Path target = new MantaDirectoryFeature(session) .mkdir( new Path( testPathPrefix, String.format("%s %s", randomStringService.random(), randomStringService.random()), EnumSet.of(Path.Type.directory) ), null, null); final Attributes found = new MantaAttributesFinderFeature(session).find(target); assertNull(found.getOwner()); assertNotEquals(Permission.EMPTY, found.getPermission()); new MantaDeleteFeature(session).delete(Collections.singletonList(target), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
MantaFindFeature implements Find { @Override public boolean find(final Path file) { return session.getClient().existsAndIsAccessible(file.getAbsolute()); } MantaFindFeature(final MantaSession session); @Override boolean find(final Path file); }### Answer:
@Test public void testFindFileNotFound() { final MantaFindFeature f = new MantaFindFeature(session); assertFalse(f.find(new Path( new MantaAccountHomeInfo(session.getHost().getCredentials().getUsername(), session.getHost().getDefaultPath()).getAccountPrivateRoot(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)))); }
@Test public void testFindPrivate() { final MantaFindFeature f = new MantaFindFeature(session); assertTrue(f.find(new Path( new MantaAccountHomeInfo(session.getHost().getCredentials().getUsername(), session.getHost().getDefaultPath()).getAccountRoot(), MantaAccountHomeInfo.HOME_PATH_PRIVATE, EnumSet.of(Path.Type.directory)))); }
@Test public void testFindPublic() { final MantaFindFeature f = new MantaFindFeature(session); assertTrue(f.find(new Path( new MantaAccountHomeInfo(session.getHost().getCredentials().getUsername(), session.getHost().getDefaultPath()).getAccountRoot(), MantaAccountHomeInfo.HOME_PATH_PUBLIC, EnumSet.of(Path.Type.directory)))); }
|
### Question:
MantaSession extends HttpSession<MantaClient> { protected boolean userIsOwner() { final MantaAccountHomeInfo account = new MantaAccountHomeInfo(host.getCredentials().getUsername(), host.getDefaultPath()); return StringUtils.equals(host.getCredentials().getUsername(), account.getAccountOwner()); } MantaSession(final Host host, final X509TrustManager trust, final X509KeyManager key); @Override void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel); @Override @SuppressWarnings("unchecked") T _getFeature(final Class<T> type); }### Answer:
@Test public void testUserOwnerIdentification() { final MantaSession ownerSession = new MantaSession( new Host( new MantaProtocol(), null, 443, new Credentials("theOwner")), new DisabledX509TrustManager(), new DefaultX509KeyManager()); assertTrue(ownerSession.userIsOwner()); final MantaSession subuserSession = new MantaSession( new Host( new MantaProtocol(), null, 443, new Credentials("theOwner/theSubUser")), new DisabledX509TrustManager(), new DefaultX509KeyManager()); assertFalse(subuserSession.userIsOwner()); }
|
### Question:
UserDefaultsDateFormatter extends AbstractUserDateFormatter implements UserDateFormatter { @Override public String getShortFormat(final long milliseconds, boolean natural) { synchronized(shortDateFormatter) { if(-1 == milliseconds) { return LocaleFactory.localizedString("Unknown"); } shortDateNaturalFormatter.setTimeZone(NSTimeZone.timeZoneWithName(timezone)); if(natural) { return shortDateNaturalFormatter.stringFromDate(toDate(milliseconds)); } return shortDateFormatter.stringFromDate(toDate(milliseconds)); } } UserDefaultsDateFormatter(final String timezone); @Override String getShortFormat(final long milliseconds, boolean natural); @Override String getMediumFormat(final long milliseconds, boolean natural); @Override String getLongFormat(final long milliseconds, boolean natural); }### Answer:
@Test public void testGetShortFormat() { final UserDateFormatter f = new UserDefaultsDateFormatter(TimeZone.getDefault().getID()); assertNotNull(f.getShortFormat(System.currentTimeMillis(), false)); assertNotNull(f.getShortFormat(System.currentTimeMillis(), true)); }
|
### Question:
UserDefaultsDateFormatter extends AbstractUserDateFormatter implements UserDateFormatter { @Override public String getMediumFormat(final long milliseconds, boolean natural) { synchronized(mediumDateFormatter) { if(-1 == milliseconds) { return LocaleFactory.localizedString("Unknown"); } mediumDateNaturalFormatter.setTimeZone(NSTimeZone.timeZoneWithName(timezone)); if(natural) { return mediumDateNaturalFormatter.stringFromDate(toDate(milliseconds)); } return mediumDateFormatter.stringFromDate(toDate(milliseconds)); } } UserDefaultsDateFormatter(final String timezone); @Override String getShortFormat(final long milliseconds, boolean natural); @Override String getMediumFormat(final long milliseconds, boolean natural); @Override String getLongFormat(final long milliseconds, boolean natural); }### Answer:
@Test public void testGetMediumFormat() { final UserDateFormatter f = new UserDefaultsDateFormatter(TimeZone.getDefault().getID()); assertNotNull(f.getMediumFormat(System.currentTimeMillis(), false)); assertNotNull(f.getMediumFormat(System.currentTimeMillis(), true)); }
|
### Question:
UserDefaultsDateFormatter extends AbstractUserDateFormatter implements UserDateFormatter { @Override public String getLongFormat(final long milliseconds, boolean natural) { synchronized(longDateFormatter) { if(-1 == milliseconds) { return LocaleFactory.localizedString("Unknown"); } longDateFormatter.setTimeZone(NSTimeZone.timeZoneWithName(timezone)); if(natural) { return longDateNaturalFormatter.stringFromDate(toDate(milliseconds)); } return longDateFormatter.stringFromDate(toDate(milliseconds)); } } UserDefaultsDateFormatter(final String timezone); @Override String getShortFormat(final long milliseconds, boolean natural); @Override String getMediumFormat(final long milliseconds, boolean natural); @Override String getLongFormat(final long milliseconds, boolean natural); }### Answer:
@Test public void testGetLongFormat() { final UserDateFormatter f = new UserDefaultsDateFormatter(TimeZone.getDefault().getID()); assertNotNull(f.getLongFormat(System.currentTimeMillis(), false)); assertNotNull(f.getLongFormat(System.currentTimeMillis(), true)); }
|
### Question:
SDSFindFeature implements Find { @Override public boolean find(final Path file) throws BackgroundException { try { nodeid.getFileid(file, new DisabledListProgressListener()); return true; } catch(NotfoundException e) { return false; } } SDSFindFeature(final SDSNodeIdProvider nodeid); @Override boolean find(final Path file); @Override Find withCache(final Cache<Path> cache); }### Answer:
@Test public void testFind() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session).withCache(cache); assertTrue(new SDSFindFeature(nodeid).find(new DefaultHomeFinderService(session).find())); assertFalse(new SDSFindFeature(nodeid).find( new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)) )); assertFalse(new SDSFindFeature(nodeid).find( new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)) )); }
|
### Question:
SDSNodeIdProvider implements IdProvider { @Override public SDSNodeIdProvider withCache(final Cache<Path> cache) { this.cache = cache; return this; } SDSNodeIdProvider(final SDSSession session); @Override String getFileid(final Path file, final ListProgressListener listener); boolean isEncrypted(final Path file); ByteBuffer getFileKey(); ByteBuffer toBuffer(final FileKey fileKey); @Override SDSNodeIdProvider withCache(final Cache<Path> cache); }### Answer:
@Test public void withCache() { assertNotNull(new SDSNodeIdProvider(session).withCache(cache).withCache(PathCache.empty())); }
|
### Question:
SDSDelegatingMoveFeature implements Move { @Override public boolean isSupported(final Path source, final Path target) { if(nodeid.isEncrypted(source) ^ nodeid.isEncrypted(target)) { return session.getFeature(Copy.class).isSupported(source, target); } return proxy.isSupported(source, target); } SDSDelegatingMoveFeature(final SDSSession session, final SDSNodeIdProvider nodeid, final SDSMoveFeature proxy); @Override Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback,
final ConnectionCallback connectionCallback); @Override boolean isRecursive(final Path source, final Path target); @Override boolean isSupported(final Path source, final Path target); @Override String toString(); }### Answer:
@Test public void testMoveRoomToDirectory() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session).withCache(cache); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume, Path.Type.triplecrypt)), null, new TransferStatus()); final Path target = new Path(room, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); final Path test = new SDSDirectoryFeature(session, nodeid).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume, Path.Type.triplecrypt)), null, new TransferStatus()); final SDSMoveFeature move = new SDSMoveFeature(session, nodeid); assertFalse(move.isSupported(test, target)); }
|
### Question:
TripleCryptConverter { public static FileKey toSwaggerFileKey(final EncryptedFileKey k) { return new FileKey().key(k.getKey()).iv(k.getIv()).tag(k.getTag()).version(k.getVersion()); } static FileKey toSwaggerFileKey(final EncryptedFileKey k); static FileKey toSwaggerFileKey(final PlainFileKey k); static UserKeyPairContainer toSwaggerUserKeyPairContainer(final UserKeyPair pair); static UserPublicKey toCryptoUserPublicKey(final PublicKeyContainer c); static PlainFileKey toCryptoPlainFileKey(final FileKey key); static EncryptedFileKey toCryptoEncryptedFileKey(final FileKeyContainer key); static EncryptedFileKey toCryptoEncryptedFileKey(final FileKey k); }### Answer:
@Test public void testFileKey() throws Exception { final JSON json = new JSON(); final FileKey fileKey = TripleCryptConverter.toSwaggerFileKey(Crypto.generateFileKey()); assertNotNull(fileKey.getIv()); assertNotNull(fileKey.getKey()); assertNull(fileKey.getTag()); assertNotNull(fileKey.getVersion()); final ObjectWriter writer = json.getContext(null).writerFor(FileKey.class); final ByteArrayOutputStream out = new ByteArrayOutputStream(); writer.writeValue(out, fileKey); final ByteBuffer buffer = ByteBuffer.wrap(out.toByteArray()); final ObjectReader reader = json.getContext(null).readerFor(FileKey.class); assertEquals(fileKey, reader.readValue(buffer.array())); }
|
### Question:
SDSTouchFeature implements Touch<VersionId> { @Override public boolean isSupported(final Path workdir, final String filename) { if(workdir.isRoot()) { return false; } if(!this.validate(filename)) { log.warn(String.format("Validation failed for target name %s", filename)); return false; } return new SDSPermissionsFeature(session, nodeid).containsRole(workdir, SDSPermissionsFeature.CREATE_ROLE); } SDSTouchFeature(final SDSSession session, final SDSNodeIdProvider nodeid); @Override Path touch(final Path file, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String filename); boolean validate(final String filename); @Override Touch<VersionId> withWriter(final Write<VersionId> writer); }### Answer:
@Test public void testSupported() { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session).withCache(cache); assertTrue(new SDSTouchFeature(session, nodeid).isSupported(new Path(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), StringUtils.EMPTY)); assertTrue(new SDSTouchFeature(session, nodeid).isSupported(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), StringUtils.EMPTY)); assertFalse(new SDSTouchFeature(session, nodeid).isSupported(new Path("/", EnumSet.of(Path.Type.directory)), StringUtils.EMPTY)); }
|
### Question:
DAVDirectoryFeature implements Directory<String> { @Override public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException { try { session.getClient().createDirectory(new DAVPathEncoder().encode(folder)); } catch(SardineException e) { throw new DAVExceptionMappingService().map("Cannot create folder {0}", e, folder); } catch(IOException e) { throw new HttpExceptionMappingService().map(e, folder); } return new Path(folder.getParent(), folder.getName(), folder.getType(), new DAVAttributesFinderFeature(session).find(folder)); } DAVDirectoryFeature(final DAVSession session); @Override Path mkdir(final Path folder, final String region, final TransferStatus status); @Override DAVDirectoryFeature withWriter(final Write<String> writer); }### Answer:
@Test public void testMakeDirectory() throws Exception { final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); new DAVDirectoryFeature(session).mkdir(test, null, new TransferStatus()); assertTrue(session.getFeature(Find.class).find(test)); new DAVDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(session.getFeature(Find.class).find(test)); }
|
### Question:
DAVProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", DAVProtocol.class.getPackage().getName(), StringUtils.upperCase(this.getType().name())); } @Override String getName(); @Override String getDescription(); @Override String getIdentifier(); @Override String getPrefix(); @Override Scheme getScheme(); @Override String[] getSchemes(); @Override String disk(); @Override boolean isAnonymousConfigurable(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.dav.DAV", new DAVProtocol().getPrefix()); }
|
### Question:
DAVProtocol extends AbstractProtocol { @Override public String[] getSchemes() { return new String[]{Scheme.dav.name(), Scheme.http.name()}; } @Override String getName(); @Override String getDescription(); @Override String getIdentifier(); @Override String getPrefix(); @Override Scheme getScheme(); @Override String[] getSchemes(); @Override String disk(); @Override boolean isAnonymousConfigurable(); }### Answer:
@Test public void testSchemes() { assertTrue(Arrays.asList(new DAVProtocol().getSchemes()).contains(Scheme.http.name())); }
|
### Question:
DAVLockFeature implements Lock<String> { @Override public String lock(final Path file) throws BackgroundException { try { return session.getClient().lock(new DAVPathEncoder().encode(file)); } catch(SardineException e) { throw new DAVExceptionMappingService().map("Failure to write attributes of {0}", e, file); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e, file); } } DAVLockFeature(final DAVSession session); @Override String lock(final Path file); @Override void unlock(final Path file, final String token); }### Answer:
@Test(expected = InteroperabilityException.class) public void testLockNotSupported() throws Exception { final TransferStatus status = new TransferStatus(); final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final byte[] content = "test".getBytes(StandardCharsets.UTF_8); final OutputStream out = local.getOutputStream(false); IOUtils.write(content, out); out.close(); status.setLength(content.length); final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final HttpUploadFeature upload = new DAVUploadFeature(new DAVWriteFeature(session)); upload.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), status, new DisabledConnectionCallback()); new DAVLockFeature(session).lock(test); }
|
### Question:
DAVExceptionMappingService extends HttpResponseExceptionMappingService<SardineException> { @Override public BackgroundException map(final SardineException failure) { final StringBuilder buffer = new StringBuilder(); switch(failure.getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_MULTI_STATUS: this.append(buffer, failure.getMessage()); return new InteroperabilityException(buffer.toString(), failure); } this.append(buffer, String.format("%s (%d %s)", failure.getReasonPhrase(), failure.getStatusCode(), failure.getResponsePhrase())); return super.map(failure, buffer, failure.getStatusCode()); } @Override BackgroundException map(final SardineException failure); }### Answer:
@Test public void testMap() { Assert.assertEquals(LoginFailureException.class, new DAVExceptionMappingService().map(new SardineException("m", 401, "r")).getClass()); assertEquals(AccessDeniedException.class, new DAVExceptionMappingService().map(new SardineException("m", 403, "r")).getClass()); assertEquals(NotfoundException.class, new DAVExceptionMappingService().map(new SardineException("m", 404, "r")).getClass()); }
|
### Question:
DAVSSLProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", DAVSSLProtocol.class.getPackage().getName(), StringUtils.upperCase(this.getType().name())); } @Override String getName(); @Override String getDescription(); @Override String getPrefix(); @Override String getIdentifier(); @Override Type getType(); @Override Scheme getScheme(); @Override String[] getSchemes(); @Override String disk(); @Override boolean isCertificateConfigurable(); @Override boolean isAnonymousConfigurable(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.dav.DAV", new DAVSSLProtocol().getPrefix()); }
|
### Question:
DAVSSLProtocol extends AbstractProtocol { @Override public String[] getSchemes() { return new String[]{Scheme.davs.name(), Scheme.https.name()}; } @Override String getName(); @Override String getDescription(); @Override String getPrefix(); @Override String getIdentifier(); @Override Type getType(); @Override Scheme getScheme(); @Override String[] getSchemes(); @Override String disk(); @Override boolean isCertificateConfigurable(); @Override boolean isAnonymousConfigurable(); }### Answer:
@Test public void testSchemes() { assertTrue(Arrays.asList(new DAVSSLProtocol().getSchemes()).contains(Scheme.https.name())); }
|
### Question:
DAVPathEncoder { public String encode(final Path file) { final String encoded = URIEncoder.encode(file.getAbsolute()); if(file.isDirectory()) { if(file.isRoot()) { return encoded; } return String.format("%s/", encoded); } return encoded; } String encode(final Path file); }### Answer:
@Test public void testEncode() { assertEquals("/", new DAVPathEncoder().encode(new Path("/", EnumSet.of(Path.Type.directory)))); assertEquals("/dav/", new DAVPathEncoder().encode(new Path("/dav", EnumSet.of(Path.Type.directory)))); assertEquals("/dav", new DAVPathEncoder().encode(new Path("/dav", EnumSet.of(Path.Type.file)))); assertEquals("/dav/file%20path", new DAVPathEncoder().encode(new Path("/dav/file path", EnumSet.of(Path.Type.file)))); }
|
### Question:
DAVQuotaFeature implements Quota { @Override public Space get() throws BackgroundException { final Path home = new DefaultHomeFinderService(session).find(); try { final DavQuota quota = session.getClient().getQuota(new DAVPathEncoder().encode(home)); return new Space( quota.getQuotaUsedBytes() > 0 ? quota.getQuotaUsedBytes() : 0, quota.getQuotaAvailableBytes() >= 0 ? quota.getQuotaAvailableBytes() : Long.MAX_VALUE ); } catch(SardineException e) { throw new DAVExceptionMappingService().map("Failure to read attributes of {0}", e, home); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e, home); } catch(NumberFormatException e) { throw new DefaultExceptionMappingService().map(e); } } DAVQuotaFeature(final DAVSession session); @Override Space get(); }### Answer:
@Test public void testGet() throws Exception { final Quota.Space quota = new DAVQuotaFeature(session).get(); assertNotNull(quota); assertEquals(Long.MAX_VALUE, quota.available, 0L); assertEquals(0L, quota.used, 0L); }
@Test public void testGetRepository() throws Exception { final Host host = new Host(new DAVSSLProtocol(), "svn.cyberduck.ch", new Credentials( PreferencesFactory.get().getProperty("connection.login.anon.name"), null )); final DAVSession session = new DAVSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager()); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); final Quota.Space quota = new DAVQuotaFeature(session).get(); assertNotNull(quota); assertEquals(Long.MAX_VALUE, quota.available, 0L); assertEquals(0L, quota.used, 0L); }
|
### Question:
DAVTimestampFeature extends DefaultTimestampFeature implements Timestamp { @Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { try { final List<DavResource> resources = session.getClient().propfind(new DAVPathEncoder().encode(file), 0, Collections.singleton(SardineUtil.createQNameWithDefaultNamespace("getlastmodified"))); for(DavResource resource : resources) { session.getClient().patch(new DAVPathEncoder().encode(file), this.getCustomProperties(resource, status.getTimestamp()), Collections.emptyList(), this.getCustomHeaders(file, status)); break; } } catch(SardineException e) { throw new DAVExceptionMappingService().map("Failure to write attributes of {0}", e, file); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e, file); } } DAVTimestampFeature(final DAVSession session); @Override void setTimestamp(final Path file, final TransferStatus status); static final QName LAST_MODIFIED_DEFAULT_NAMESPACE; static final QName LAST_MODIFIED_CUSTOM_NAMESPACE; static final QName LAST_MODIFIED_SERVER_CUSTOM_NAMESPACE; }### Answer:
@Test @Ignore public void testSetTimestamp() throws Exception { final Path file = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); session.getFeature(Touch.class).touch(file, new TransferStatus()); new DAVTimestampFeature(session).setTimestamp(file, 5000L); assertEquals(5000L, new DAVAttributesFinderFeature(session).find(file).getModificationDate()); assertEquals(5000L, new DefaultAttributesFinderFeature(session).find(file).getModificationDate()); new DAVDeleteFeature(session).delete(Collections.<Path>singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.