method2testcases
stringlengths 118
3.08k
|
---|
### Question:
Credentials implements Comparable<Credentials> { public String getPassword() { if(StringUtils.isEmpty(password)) { if(this.isAnonymousLogin()) { return PreferencesFactory.get().getProperty("connection.login.anon.pass"); } } return password; } Credentials(); Credentials(final Credentials copy); Credentials(final String user); Credentials(final String user, final String password); Credentials(final String user, final String password, final String token); String getUsername(); void setUsername(final String user); Credentials withUsername(final String user); String getPassword(); void setPassword(final String password); Credentials withPassword(final String password); String getToken(); void setToken(final String token); Credentials withToken(final String token); OAuthTokens getOauth(); void setOauth(final OAuthTokens oauth); Credentials withOauth(final OAuthTokens oauth); boolean isSaved(); void setSaved(final boolean saved); Credentials withSaved(final boolean saved); boolean isPassed(); void setPassed(final boolean passed); boolean isAnonymousLogin(); boolean isPasswordAuthentication(); boolean isTokenAuthentication(); boolean isOAuthAuthentication(); boolean isPublicKeyAuthentication(); Credentials withIdentity(final Local file); Local getIdentity(); void setIdentity(final Local file); String getIdentityPassphrase(); void setIdentityPassphrase(final String identityPassphrase); Credentials withIdentityPassphrase(final String identityPassphrase); String getCertificate(); void setCertificate(final String certificate); boolean isCertificateAuthentication(); boolean validate(final Protocol protocol, final LoginOptions options); void reset(); @Override int compareTo(final Credentials o); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testAnonymous() { Credentials c = new Credentials("anonymous", ""); assertEquals("[email protected]", c.getPassword()); }
|
### Question:
Native { public static boolean load(final String library) { synchronized(lock) { final String path = Native.getPath(library); try { System.load(path); return true; } catch(UnsatisfiedLinkError e) { log.warn(String.format("Failed to load %s:%s", path, e.getMessage()), e); try { System.loadLibrary(library); return true; } catch(UnsatisfiedLinkError f) { log.warn(String.format("Failed to load %s:%s", library, e.getMessage()), e); return false; } } } } private Native(); static boolean load(final String library); }### Answer:
@Test public void testLoad() { assertFalse(Native.load("notfound")); }
|
### Question:
ProtocolFactory { public List<Protocol> find() { return this.find(Protocol::isEnabled); } ProtocolFactory(); ProtocolFactory(final Set<Protocol> protocols); ProtocolFactory(final Local bundle, final Set<Protocol> protocols); static ProtocolFactory get(); void register(Protocol... protocols); void loadDefaultProfiles(); void register(final Protocol protocol); List<Protocol> find(); List<Protocol> find(final Predicate<Protocol> search); Protocol forName(final String identifier); Protocol forName(final String identifier, final String provider); Protocol forName(final List<Protocol> enabled, final String identifier, final String provider); Protocol forType(final Protocol.Type type); Protocol forScheme(final Scheme scheme); Protocol forScheme(final String scheme, final Protocol fallback); @Override String toString(); }### Answer:
@Test public void testGetProtocols() { final TestProtocol defaultProtocol = new TestProtocol(Scheme.ftp); final TestProtocol providerProtocol = new TestProtocol(Scheme.ftp) { @Override public String getProvider() { return "c"; } }; final TestProtocol disabledProtocol = new TestProtocol(Scheme.sftp) { @Override public boolean isEnabled() { return false; } }; final ProtocolFactory f = new ProtocolFactory(new HashSet<>( Arrays.asList(defaultProtocol, providerProtocol, disabledProtocol))); final List<Protocol> protocols = f.find(); assertTrue(protocols.contains(defaultProtocol)); assertTrue(protocols.contains(providerProtocol)); assertFalse(protocols.contains(disabledProtocol)); }
|
### Question:
BackgroundActionRegistry extends Collection<BackgroundAction> implements BackgroundActionListener { public static BackgroundActionRegistry global() { synchronized(lock) { if(null == global) { global = new BackgroundActionRegistry(); } return global; } } BackgroundActionRegistry(); static BackgroundActionRegistry global(); synchronized BackgroundAction getCurrent(); @Override synchronized void start(final BackgroundAction action); @Override synchronized void stop(final BackgroundAction action); @Override synchronized void cancel(final BackgroundAction action); @Override synchronized boolean add(final BackgroundAction action); @Override synchronized boolean remove(final Object action); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testGlobal() { assertSame(BackgroundActionRegistry.global(), BackgroundActionRegistry.global()); }
|
### Question:
BackgroundActionRegistry extends Collection<BackgroundAction> implements BackgroundActionListener { public synchronized BackgroundAction getCurrent() { final Iterator<BackgroundAction> iter = running.iterator(); if(iter.hasNext()) { return iter.next(); } return null; } BackgroundActionRegistry(); static BackgroundActionRegistry global(); synchronized BackgroundAction getCurrent(); @Override synchronized void start(final BackgroundAction action); @Override synchronized void stop(final BackgroundAction action); @Override synchronized void cancel(final BackgroundAction action); @Override synchronized boolean add(final BackgroundAction action); @Override synchronized boolean remove(final Object action); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testGetCurrent() throws Exception { BackgroundActionRegistry r = new BackgroundActionRegistry(); final CountDownLatch lock = new CountDownLatch(1); final AbstractBackgroundAction action = new AbstractBackgroundAction() { @Override public Object run() { return null; } @Override public void finish() { super.finish(); lock.countDown(); } }; assertTrue(r.add(action)); action.finish(); lock.await(1, TimeUnit.SECONDS); r.remove(action); assertFalse(r.contains(action)); assertNull(r.getCurrent()); }
|
### Question:
BackgroundActionRegistry extends Collection<BackgroundAction> implements BackgroundActionListener { @Override public synchronized void cancel(final BackgroundAction action) { if(action.isRunning()) { log.debug(String.format("Skip removing action %s currently running", action)); } else { this.remove(action); } } BackgroundActionRegistry(); static BackgroundActionRegistry global(); synchronized BackgroundAction getCurrent(); @Override synchronized void start(final BackgroundAction action); @Override synchronized void stop(final BackgroundAction action); @Override synchronized void cancel(final BackgroundAction action); @Override synchronized boolean add(final BackgroundAction action); @Override synchronized boolean remove(final Object action); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testCancel() { BackgroundActionRegistry r = new BackgroundActionRegistry(); final AbstractBackgroundAction action = new AbstractBackgroundAction() { @Override public Object run() { return null; } }; assertTrue(r.add(action)); action.cancel(); r.remove(action); assertFalse(r.contains(action)); assertNull(r.getCurrent()); }
|
### Question:
DefaultFailureDiagnostics implements FailureDiagnostics<BackgroundException> { @Override public Type determine(final BackgroundException failure) { if(log.isDebugEnabled()) { log.debug(String.format("Determine cause for failure %s", failure)); } for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(failure instanceof UnsupportedException) { return Type.unsupported; } if(failure instanceof LoginFailureException) { return Type.login; } if(cause instanceof ResolveFailedException) { return Type.network; } if(failure instanceof ConnectionCanceledException) { return Type.cancel; } if(cause instanceof ConnectionTimeoutException) { return Type.network; } if(cause instanceof ConnectionRefusedException) { return Type.network; } if(cause instanceof SSLNegotiateException) { return Type.application; } if(cause instanceof SSLHandshakeException) { return Type.application; } if(cause instanceof SSLException) { return Type.network; } if(cause instanceof NoHttpResponseException) { return Type.network; } if(cause instanceof ConnectTimeoutException) { return Type.network; } if(cause instanceof SocketException || cause instanceof IOResumeException || cause instanceof TimeoutException || cause instanceof SocketTimeoutException || cause instanceof UnknownHostException) { return Type.network; } } return Type.application; } @Override Type determine(final BackgroundException failure); }### Answer:
@Test public void testDetermine() { assertEquals(FailureDiagnostics.Type.network, new DefaultFailureDiagnostics().determine(new ResolveFailedException("d", null))); assertEquals(FailureDiagnostics.Type.cancel, new DefaultFailureDiagnostics().determine(new ResolveCanceledException())); assertEquals(FailureDiagnostics.Type.login, new DefaultFailureDiagnostics().determine(new LoginFailureException("d"))); assertEquals(FailureDiagnostics.Type.cancel, new DefaultFailureDiagnostics().determine(new ConnectionCanceledException())); }
|
### Question:
BackgroundCallable implements Callable<T> { @Override public T call() { if(log.isDebugEnabled()) { log.debug(String.format("Running background action %s", action)); } final ActionOperationBatcher autorelease = ActionOperationBatcherFactory.get(); if(action.isCanceled()) { return null; } if(log.isDebugEnabled()) { log.debug(String.format("Prepare background action %s", action)); } action.prepare(); try { final T result = this.run(); if(log.isDebugEnabled()) { log.debug(String.format("Return result %s from background action %s", result, action)); } return result; } finally { action.finish(); if(log.isDebugEnabled()) { log.debug(String.format("Invoke cleanup for background action %s", action)); } controller.invoke(new ControllerMainAction(controller) { @Override public void run() { try { action.cleanup(); } catch(Exception e) { log.error(String.format("Exception %s running cleanup task", e), e); } } }); if(log.isDebugEnabled()) { log.debug(String.format("Releasing lock for background runnable %s", action)); } autorelease.operate(); } } BackgroundCallable(final BackgroundAction<T> action, final Controller controller); @Override T call(); }### Answer:
@Test public void testCallReturnValueFailureRetry() { final Object expected = new Object(); final AbstractBackgroundAction<Object> action = new AbstractBackgroundAction<Object>() { final AtomicBoolean exception = new AtomicBoolean(); @Override public Object run() throws BackgroundException { try { if(!exception.get()) { throw new BackgroundException(); } } finally { exception.set(true); } return expected; } @Override public boolean alert(final BackgroundException e) { return true; } }; final BackgroundCallable<Object> c = new BackgroundCallable<>(action, new AbstractController() { @Override public void invoke(final MainAction runnable, final boolean wait) { } }); assertSame(expected, c.call()); assertFalse(action.isRunning()); assertFalse(action.isCanceled()); }
|
### Question:
DefaultMainAction extends MainAction { @Override public Object lock() { return lock; } @Override boolean isValid(); @Override Object lock(); }### Answer:
@Test public void testLock() { assertNotSame(new DefaultMainAction() { @Override public void run() { } }.lock(), new DefaultMainAction() { @Override public void run() { } }.lock()); }
|
### Question:
ControllerMainAction extends MainAction { @Override public Object lock() { return controller; } ControllerMainAction(Controller c); @Override boolean isValid(); @Override Object lock(); }### Answer:
@Test public void testLock() { final AbstractController c = new AbstractController() { @Override public void invoke(final MainAction runnable, final boolean wait) { } }; assertEquals(c, new ControllerMainAction(c) { @Override public void run() { } }.lock()); }
|
### Question:
BackgroundActionPauser { public void await() { if(0 == delay) { log.info("No pause between retry"); return; } final Timer wakeup = new Timer(); final CyclicBarrier wait = new CyclicBarrier(2); wakeup.scheduleAtFixedRate(new PauserTimerTask(wait), 0, 1000); try { wait.await(); } catch(InterruptedException | BrokenBarrierException e) { log.error(e.getMessage(), e); } } BackgroundActionPauser(final Callback callback); BackgroundActionPauser(final Callback callback, final Integer delay); void await(); }### Answer:
@Test public void testAwait() { final AbstractBackgroundAction action = new AbstractBackgroundAction() { @Override public Object run() throws BackgroundException { throw new BackgroundException(new RuntimeException("f")); } }; try { action.call(); fail(); } catch(BackgroundException e) { } new BackgroundActionPauser(new BackgroundActionPauser.Callback() { @Override public void validate() throws ConnectionCanceledException { if(action.isCanceled()) { throw new ConnectionCanceledException(); } } @Override public void progress(final Integer delay) { } }).await(); }
|
### Question:
URIEncoder { public static String encode(final String input) { try { final StringBuilder b = new StringBuilder(); final StringTokenizer t = new StringTokenizer(input, "/"); if(!t.hasMoreTokens()) { return input; } if(StringUtils.startsWith(input, String.valueOf(Path.DELIMITER))) { b.append(Path.DELIMITER); } while(t.hasMoreTokens()) { b.append(URLEncoder.encode(t.nextToken(), StandardCharsets.UTF_8.name())); if(t.hasMoreTokens()) { b.append(Path.DELIMITER); } } if(StringUtils.endsWith(input, String.valueOf(Path.DELIMITER))) { b.append(Path.DELIMITER); } return StringUtils.replaceEach(b.toString(), new String[]{"+", "*", "%7E", "%40"}, new String[]{"%20", "%2A", "~", "@"}); } catch(UnsupportedEncodingException e) { log.warn(String.format("Failure %s encoding input %s", e, input)); return input; } } private URIEncoder(); static String encode(final String input); static String decode(final String input); }### Answer:
@Test public void testEncode() { assertEquals("/p", URIEncoder.encode("/p")); assertEquals("/p%20d", URIEncoder.encode("/p d")); }
@Test public void testEncodeHash() { assertEquals("file%23", URIEncoder.encode("file#")); }
@Test public void testEncodeTrailingDelimiter() { assertEquals("/a/p/", URIEncoder.encode("/a/p/")); assertEquals("/p%20d/", URIEncoder.encode("/p d/")); }
@Test public void testEncodeRelativeUri() { assertEquals("a/p", URIEncoder.encode("a/p")); assertEquals("a/p/", URIEncoder.encode("a/p/")); }
|
### Question:
Permission implements Serializable { @Override public <T> T serialize(final Serializer dict) { dict.setStringForKey(this.getSymbol(), "Mask"); return dict.getSerialized(); } Permission(); Permission(final String mode); Permission(final Action u, final Action g, final Action o); Permission(final Action u, final Action g, final Action o,
final boolean stickybit, final boolean setuid, final boolean setgid); Permission(final int mode); Permission(final Permission other); @Override T serialize(final Serializer dict); Action getUser(); void setUser(final Action user); Action getGroup(); void setGroup(final Action group); Action getOther(); void setOther(final Action other); boolean isSetuid(); void setSetuid(final boolean setuid); boolean isSetgid(); void setSetgid(final boolean setgid); boolean isSticky(); void setSticky(final boolean sticky); String getSymbol(); String getMode(); @Override String toString(); boolean isExecutable(); boolean isReadable(); boolean isWritable(); @Override boolean equals(final Object o); int hashCode(); static final Permission EMPTY; }### Answer:
@Test public void testGetAsDictionary() { assertEquals(new Permission(777), new PermissionDictionary().deserialize(new Permission(777).serialize(SerializerFactory.get()))); assertEquals(new Permission(700), new PermissionDictionary().deserialize(new Permission(700).serialize(SerializerFactory.get()))); assertEquals(new Permission(400), new PermissionDictionary().deserialize(new Permission(400).serialize(SerializerFactory.get()))); }
|
### Question:
Permission implements Serializable { public void setSticky(final boolean sticky) { this.sticky = sticky; } Permission(); Permission(final String mode); Permission(final Action u, final Action g, final Action o); Permission(final Action u, final Action g, final Action o,
final boolean stickybit, final boolean setuid, final boolean setgid); Permission(final int mode); Permission(final Permission other); @Override T serialize(final Serializer dict); Action getUser(); void setUser(final Action user); Action getGroup(); void setGroup(final Action group); Action getOther(); void setOther(final Action other); boolean isSetuid(); void setSetuid(final boolean setuid); boolean isSetgid(); void setSetgid(final boolean setgid); boolean isSticky(); void setSticky(final boolean sticky); String getSymbol(); String getMode(); @Override String toString(); boolean isExecutable(); boolean isReadable(); boolean isWritable(); @Override boolean equals(final Object o); int hashCode(); static final Permission EMPTY; }### Answer:
@Test public void testSetSticky() { assertTrue(new Permission(1755).isSticky()); assertTrue(new Permission(3755).isSticky()); assertTrue(new Permission(5755).isSticky()); assertFalse(new Permission(2755).isSticky()); assertFalse(new Permission(6755).isSticky()); assertEquals("1000", new Permission(1000).getMode()); assertEquals("--------T", new Permission(1000).getSymbol()); }
|
### Question:
Permission implements Serializable { public String getMode() { return Integer.toString(toInteger(), 8); } Permission(); Permission(final String mode); Permission(final Action u, final Action g, final Action o); Permission(final Action u, final Action g, final Action o,
final boolean stickybit, final boolean setuid, final boolean setgid); Permission(final int mode); Permission(final Permission other); @Override T serialize(final Serializer dict); Action getUser(); void setUser(final Action user); Action getGroup(); void setGroup(final Action group); Action getOther(); void setOther(final Action other); boolean isSetuid(); void setSetuid(final boolean setuid); boolean isSetgid(); void setSetgid(final boolean setgid); boolean isSticky(); void setSticky(final boolean sticky); String getSymbol(); String getMode(); @Override String toString(); boolean isExecutable(); boolean isReadable(); boolean isWritable(); @Override boolean equals(final Object o); int hashCode(); static final Permission EMPTY; }### Answer:
@Test public void testToMode() { final Permission permission = new Permission(Permission.Action.read, Permission.Action.none, Permission.Action.none); assertEquals("400", permission.getMode()); }
@Test public void testModeStickyBit() { final Permission permission = new Permission(Permission.Action.read, Permission.Action.none, Permission.Action.none, true, false, false); assertEquals("1400", permission.getMode()); }
|
### Question:
AbstractController implements Controller { @Override public <T> Future<T> background(final BackgroundAction<T> action) { if(registry.contains(action)) { log.warn(String.format("Skip duplicate background action %s found in registry", action)); return ConcurrentUtils.constantFuture(null); } return DefaultBackgroundExecutor.get().execute(this, registry, action); } @Override void invoke(final MainAction runnable); @Override BackgroundActionRegistry getRegistry(); @Override Future<T> background(final BackgroundAction<T> action); @Override void start(final BackgroundAction action); @Override void cancel(final BackgroundAction action); @Override void stop(final BackgroundAction action); @Override void message(final String message); @Override void log(final Type request, final String message); }### Answer:
@Test public void testBackground() throws Exception { final AbstractController controller = new AbstractController() { @Override public void invoke(final MainAction runnable, final boolean wait) { runnable.run(); } }; final AbstractBackgroundAction<Object> action = new RegistryBackgroundAction<Object>(controller, SessionPool.DISCONNECTED) { @Override public void init() { assertEquals("main", Thread.currentThread().getName()); } @Override public Object run(final Session<?> session) { return null; } @Override public void cleanup() { super.cleanup(); assertFalse(controller.getRegistry().contains(this)); } }; controller.background(action).get(); }
|
### Question:
AbstractController implements Controller { @Override public void invoke(final MainAction runnable) { this.invoke(runnable, false); } @Override void invoke(final MainAction runnable); @Override BackgroundActionRegistry getRegistry(); @Override Future<T> background(final BackgroundAction<T> action); @Override void start(final BackgroundAction action); @Override void cancel(final BackgroundAction action); @Override void stop(final BackgroundAction action); @Override void message(final String message); @Override void log(final Type request, final String message); }### Answer:
@Test public void testInvoke() throws Exception { final CountDownLatch entry = new CountDownLatch(1); final AbstractController controller = new AbstractController() { @Override public void invoke(final MainAction runnable, final boolean wait) { assertFalse(wait); entry.countDown(); } }; new Thread(() -> controller.invoke(new DefaultMainAction() { @Override public void run() { } })).start(); entry.await(1, TimeUnit.SECONDS); }
|
### Question:
DescriptiveUrlBag extends LinkedHashSet<DescriptiveUrl> { public DescriptiveUrlBag filter(final DescriptiveUrl.Type... types) { final DescriptiveUrlBag filtered = new DescriptiveUrlBag(this); filtered.removeIf(url -> !Arrays.asList(types).contains(url.getType())); return filtered; } DescriptiveUrlBag(); DescriptiveUrlBag(final java.util.Collection<? extends DescriptiveUrl> c); static DescriptiveUrlBag empty(); @Override boolean add(final DescriptiveUrl url); DescriptiveUrlBag filter(final DescriptiveUrl.Type... types); DescriptiveUrl find(DescriptiveUrl.Type type); }### Answer:
@Test public void testFilter() { final DescriptiveUrlBag list = new DescriptiveUrlBag(); final DescriptiveUrl url = new DescriptiveUrl(URI.create("http: list.add(url); assertTrue(list.filter(DescriptiveUrl.Type.provider).isEmpty()); assertTrue(list.filter(DescriptiveUrl.Type.cdn).isEmpty()); assertFalse(list.filter(DescriptiveUrl.Type.http).isEmpty()); assertFalse(list.filter(DescriptiveUrl.Type.provider, DescriptiveUrl.Type.http).isEmpty()); assertEquals(DescriptiveUrl.EMPTY, list.find(DescriptiveUrl.Type.provider)); assertEquals(url, list.find(DescriptiveUrl.Type.http)); }
|
### Question:
DescriptiveUrlBag extends LinkedHashSet<DescriptiveUrl> { public DescriptiveUrl find(DescriptiveUrl.Type type) { for(DescriptiveUrl url : this) { if(url.getType().equals(type)) { return url; } } return DescriptiveUrl.EMPTY; } DescriptiveUrlBag(); DescriptiveUrlBag(final java.util.Collection<? extends DescriptiveUrl> c); static DescriptiveUrlBag empty(); @Override boolean add(final DescriptiveUrl url); DescriptiveUrlBag filter(final DescriptiveUrl.Type... types); DescriptiveUrl find(DescriptiveUrl.Type type); }### Answer:
@Test public void testFind() { final DescriptiveUrlBag list = new DescriptiveUrlBag(); final DescriptiveUrl url = new DescriptiveUrl(URI.create("http: list.add(url); assertEquals(DescriptiveUrl.EMPTY, list.find(DescriptiveUrl.Type.provider)); assertEquals(url, list.find(DescriptiveUrl.Type.http)); }
|
### Question:
AlphanumericRandomStringService implements RandomStringService { @Override public String random() { return new RandomStringGenerator.Builder().withinRange('0', 'z').filteredBy(new CharacterPredicate() { @Override public boolean test(final int codePoint) { return Character.isAlphabetic(codePoint) || Character.isDigit(codePoint); } }).build().generate(8); } @Override String random(); }### Answer:
@Test public void random() { assertNotNull(new AlphanumericRandomStringService().random()); }
|
### Question:
TildePathExpander { public Path expand(final Path remote) { return this.expand(remote, PREFIX); } TildePathExpander(final Path workdir); Path expand(final Path remote); static final String PREFIX; }### Answer:
@Test public void testExpand() throws Exception { final Path expanded = new TildePathExpander(new Path("/home/jenkins", EnumSet.of(Path.Type.directory))) .expand(new Path("~/f", EnumSet.of(Path.Type.file))); assertEquals(new Path("/home/jenkins/f", EnumSet.of(Path.Type.file)), expanded); assertEquals(new Path("/home/jenkins", EnumSet.of(Path.Type.directory)), expanded.getParent()); }
@Test public void testExpandPathWithDirectory() throws Exception { final Path expanded = new TildePathExpander(new Path("/home/jenkins", EnumSet.of(Path.Type.directory))) .expand(new Path("/~/f/s", EnumSet.of(Path.Type.file))); assertEquals(new Path("/home/jenkins/f/s", EnumSet.of(Path.Type.file)), expanded); assertEquals(new Path("/home/jenkins/f", EnumSet.of(Path.Type.directory)), expanded.getParent()); }
@Test public void testNoExpand() throws Exception { final Path f = new Path("/f", EnumSet.of(Path.Type.file)); assertSame(f, new TildePathExpander(new Path("/home/jenkins", EnumSet.of(Path.Type.directory))).expand(f)); }
|
### Question:
GoogleStorageUrlProvider implements UrlProvider { @Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DefaultUrlProvider(session.getHost()).toUrl(file); if(file.isFile()) { list.add(new DescriptiveUrl(URI.create(String.format("https: URIEncoder.encode(file.getAbsolute()))), DescriptiveUrl.Type.authenticated, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), LocaleFactory.localizedString("Authenticated")))); } return list; } GoogleStorageUrlProvider(final GoogleStorageSession session); @Override DescriptiveUrlBag toUrl(final Path file); }### Answer:
@Test public void testGet() { assertEquals("https: new Path("/c/f", EnumSet.of(Path.Type.file))).find(DescriptiveUrl.Type.authenticated).getUrl()); }
@Test public void testGetEncoded() { assertEquals("https: new Path("/container/Screen Shot 2013-07-18 at 23.55.10.png", EnumSet.of(Path.Type.file))).find(DescriptiveUrl.Type.authenticated).getUrl()); }
|
### Question:
GoogleStorageLoggingFeature implements Logging, DistributionLogging { @Override public void setConfiguration(final Path container, final LoggingConfiguration configuration) throws BackgroundException { try { session.getClient().buckets().patch(container.getName(), new Bucket().setLogging(new Bucket.Logging() .setLogObjectPrefix(configuration.isEnabled() ? PreferencesFactory.get().getProperty("google.logging.prefix") : null) .setLogBucket(StringUtils.isNotBlank(configuration.getLoggingTarget()) ? configuration.getLoggingTarget() : container.getName())) ).execute(); } catch(IOException e) { throw new GoogleStorageExceptionMappingService().map("Failure to write attributes of {0}", e, container); } } GoogleStorageLoggingFeature(final GoogleStorageSession session); @Override LoggingConfiguration getConfiguration(final Path file); @Override void setConfiguration(final Path container, final LoggingConfiguration configuration); }### Answer:
@Test(expected = NotfoundException.class) public void testWriteNotFound() throws Exception { new GoogleStorageLoggingFeature(session).setConfiguration( new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)), new LoggingConfiguration(false) ); }
|
### Question:
GoogleStorageMoveFeature implements Move { @Override public boolean isSupported(final Path source, final Path target) { return !containerService.isContainer(source); } GoogleStorageMoveFeature(final GoogleStorageSession session); @Override Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback); @Override boolean isSupported(final Path source, final Path target); }### Answer:
@Test public void testSupport() { final Path c = new Path("/c", EnumSet.of(Path.Type.directory)); assertFalse(new GoogleStorageMoveFeature(null).isSupported(c, c)); final Path cf = new Path("/c/f", EnumSet.of(Path.Type.directory)); assertTrue(new GoogleStorageMoveFeature(null).isSupported(cf, cf)); }
|
### Question:
S3LifecycleConfiguration implements Lifecycle { @Override public LifecycleConfiguration getConfiguration(final Path file) throws BackgroundException { final Path container = containerService.getContainer(file); if(container.isRoot()) { return LifecycleConfiguration.empty(); } if(file.getType().contains(Path.Type.upload)) { return LifecycleConfiguration.empty(); } try { final LifecycleConfig status = session.getClient().getLifecycleConfig(container.getName()); if(null != status) { Integer transition = null; Integer expiration = null; String storageClass = null; for(LifecycleConfig.Rule rule : status.getRules()) { if(rule.getTransition() != null) { storageClass = rule.getTransition().getStorageClass(); transition = rule.getTransition().getDays(); } if(rule.getExpiration() != null) { expiration = rule.getExpiration().getDays(); } } return new LifecycleConfiguration(transition, storageClass, expiration); } return LifecycleConfiguration.empty(); } catch(ServiceException e) { try { throw new S3ExceptionMappingService().map("Failure to read attributes of {0}", e, container); } catch(AccessDeniedException | InteroperabilityException l) { log.warn(String.format("Missing permission to read lifecycle configuration for %s %s", container, e.getMessage())); return LifecycleConfiguration.empty(); } } } S3LifecycleConfiguration(final S3Session session); @Override void setConfiguration(final Path file, final LifecycleConfiguration configuration); @Override LifecycleConfiguration getConfiguration(final Path file); }### Answer:
@Test public void testGetConfiguration() throws Exception { final LifecycleConfiguration configuration = new S3LifecycleConfiguration(session).getConfiguration( new Path("test-lifecycle-us-east-1-cyberduck", EnumSet.of(Path.Type.directory)) ); assertEquals(30, configuration.getExpiration(), 0L); assertEquals(1, configuration.getTransition(), 0L); }
@Test public void testGetConfigurationAccessDenied() throws Exception { assertEquals(LifecycleConfiguration.empty(), new S3LifecycleConfiguration(session).getConfiguration( new Path("bucket", EnumSet.of(Path.Type.directory)) )); }
|
### Question:
GoogleStorageMetadataFeature implements Headers { @Override public Map<String, String> getMetadata(final Path file) throws BackgroundException { if(file.isFile() || file.isPlaceholder()) { try { return new GoogleStorageAttributesFinderFeature(session).find(file).getMetadata(); } catch(NotfoundException e) { if(file.isPlaceholder()) { return Collections.emptyMap(); } throw e; } } return Collections.emptyMap(); } GoogleStorageMetadataFeature(final GoogleStorageSession session); @Override Map<String, String> getDefault(final Local local); @Override Map<String, String> getMetadata(final Path file); @Override void setMetadata(final Path file, final TransferStatus status); }### Answer:
@Test public void testGetMetadataBucket() throws Exception { final Path bucket = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Map<String, String> metadata = new GoogleStorageMetadataFeature(session).getMetadata(bucket); assertTrue(metadata.isEmpty()); }
|
### Question:
GoogleStorageStorageClassFeature implements Redundancy { @Override public Set<String> getClasses() { return new LinkedHashSet<>(Arrays.asList( S3Object.STORAGE_CLASS_STANDARD, "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE") ); } GoogleStorageStorageClassFeature(final GoogleStorageSession session); @Override String getDefault(); @Override Set<String> getClasses(); @Override String getClass(final Path file); @Override void setClass(final Path file, final String redundancy); }### Answer:
@Test public void testGetClasses() { assertArrayEquals(Arrays.asList( "STANDARD", "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE").toArray(), new GoogleStorageStorageClassFeature(session).getClasses().toArray()); }
|
### Question:
GoogleStorageStorageClassFeature implements Redundancy { @Override public String getClass(final Path file) throws BackgroundException { return new GoogleStorageAttributesFinderFeature(session).find(file).getStorageClass(); } GoogleStorageStorageClassFeature(final GoogleStorageSession session); @Override String getDefault(); @Override Set<String> getClasses(); @Override String getClass(final Path file); @Override void setClass(final Path file, final String redundancy); }### Answer:
@Test(expected = NotfoundException.class) public void testNotFound() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory)); final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final GoogleStorageStorageClassFeature feature = new GoogleStorageStorageClassFeature(session); feature.getClass(test); }
|
### Question:
GoogleStorageProtocol extends AbstractProtocol { @Override public String getPrefix() { return String.format("%s.%s", GoogleStorageProtocol.class.getPackage().getName(), "GoogleStorage"); } @Override String getName(); @Override String getDescription(); @Override String getIdentifier(); @Override Type getType(); @Override String getPrefix(); @Override String disk(); @Override boolean isHostnameConfigurable(); @Override boolean isPasswordConfigurable(); @Override Set<Location.Name> getRegions(); @Override Scheme getScheme(); @Override boolean isPortConfigurable(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override String favicon(); @Override DirectoryTimestamp getDirectoryTimestamp(); @Override Comparator<String> getListComparator(); }### Answer:
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.googlestorage.GoogleStorage", new GoogleStorageProtocol().getPrefix()); }
|
### Question:
GoogleStorageProtocol extends AbstractProtocol { @Override public boolean isPasswordConfigurable() { return false; } @Override String getName(); @Override String getDescription(); @Override String getIdentifier(); @Override Type getType(); @Override String getPrefix(); @Override String disk(); @Override boolean isHostnameConfigurable(); @Override boolean isPasswordConfigurable(); @Override Set<Location.Name> getRegions(); @Override Scheme getScheme(); @Override boolean isPortConfigurable(); @Override String getUsernamePlaceholder(); @Override String getPasswordPlaceholder(); @Override String favicon(); @Override DirectoryTimestamp getDirectoryTimestamp(); @Override Comparator<String> getListComparator(); }### Answer:
@Test public void testPassword() { assertFalse(new GoogleStorageProtocol().isPasswordConfigurable()); }
|
### Question:
GoogleStorageTouchFeature implements Touch<VersionId> { @Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { status.setLength(0L); final StatusOutputStream<VersionId> out = writer.write(file, status, new DisabledConnectionCallback()); new DefaultStreamCloser().close(out); return new Path(file.getParent(), file.getName(), file.getType(), new PathAttributes(file.attributes()).withVersionId(out.getStatus().id)); } GoogleStorageTouchFeature(final GoogleStorageSession session); @Override Path touch(final Path file, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String filename); @Override Touch<VersionId> withWriter(final Write<VersionId> writer); }### Answer:
@Test public void testTouch() throws Exception { final Path bucket = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new GoogleStorageTouchFeature(session).touch( new Path(bucket, String.format("%s %s", new AlphanumericRandomStringService().random(), new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.file)), new TransferStatus().withMime("text/plain")); assertTrue(new GoogleStorageFindFeature(session).find(test)); new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new GoogleStorageFindFeature(session).find(test)); }
|
### Question:
GoogleStorageSession extends HttpSession<Storage> { @Override public Storage connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) { final HttpClientBuilder configuration = builder.build(proxy, this, prompt); authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol()) .withRedirectUri(host.getProtocol().getOAuthRedirectUrl()); configuration.addInterceptorLast(authorizationService); configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt)); this.transport = new ApacheHttpTransport(configuration.build()); final UseragentProvider ua = new PreferencesUseragentProvider(); return new Storage.Builder(transport, new JacksonFactory(), new UserAgentHttpRequestInitializer(ua)) .setApplicationName(ua.get()) .build(); } GoogleStorageSession(final Host host, final X509TrustManager trust, final X509KeyManager key); @Override Storage connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt); @Override void login(final Proxy proxy, final LoginCallback prompt,
final CancelCallback cancel); HttpClient getHttpClient(); @Override @SuppressWarnings("unchecked") T _getFeature(final Class<T> type); }### Answer:
@Test public void testConnect() throws Exception { session.close(); final LoginConnectionService login = new LoginConnectionService(new DisabledLoginCallback(), new DisabledHostKeyCallback(), new DisabledPasswordStore() { @Override public String getPassword(final Scheme scheme, final int port, final String hostname, final String user) { if(user.equals("Google Cloud Storage (api-project-408246103372) OAuth2 Access Token")) { return System.getProperties().getProperty("google.accesstoken"); } if(user.equals("Google Cloud Storage (api-project-408246103372) OAuth2 Refresh Token")) { return System.getProperties().getProperty("google.refreshtoken"); } return null; } }, new DisabledProgressListener()); login.check(session, PathCache.empty(), new DisabledCancelCallback()); }
|
### Question:
GoogleStorageSession extends HttpSession<Storage> { @Override public void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { authorizationService.setTokens(authorizationService.authorize(host, prompt, cancel)); } GoogleStorageSession(final Host host, final X509TrustManager trust, final X509KeyManager key); @Override Storage connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt); @Override void login(final Proxy proxy, final LoginCallback prompt,
final CancelCallback cancel); HttpClient getHttpClient(); @Override @SuppressWarnings("unchecked") T _getFeature(final Class<T> type); }### Answer:
@Test(expected = LoginCanceledException.class) public void testConnectMissingKey() throws Exception { session.close(); session.getHost().getCredentials().setOauth(OAuthTokens.EMPTY); session.login(Proxy.DIRECT, new DisabledLoginCallback() { @Override public Credentials prompt(final Host bookmark, final String username, final String title, final String reason, final LoginOptions options) throws LoginCanceledException { assertEquals("OAuth2 Authentication", title); throw new LoginCanceledException(); } }, null); }
@Test(expected = LoginCanceledException.class) public void testInvalidProjectId() throws Exception { session.getHost().setCredentials( new Credentials("duck-1432", "") ); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); }
@Test(expected = LoginCanceledException.class) public void testProjectIdNoAuthorization() throws Exception { session.getHost().setCredentials( new Credentials("stellar-perigee-775", "") ); session.login(Proxy.DIRECT, new DisabledLoginCallback() { @Override public Credentials prompt(final Host bookmark, final String username, final String title, final String reason, final LoginOptions options) { return new Credentials("", ""); } }, new DisabledCancelCallback()); }
|
### Question:
GoogleStorageBucketListService implements ListService { @Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> buckets = new AttributedList<Path>(); Buckets response; String page = null; do { response = session.getClient().buckets().list(session.getHost().getCredentials().getUsername()) .setMaxResults(preferences.getLong("googlestorage.listing.chunksize")) .setPageToken(page) .execute(); if(null != response.getItems()) { for(Bucket item : response.getItems()) { final Path bucket = new Path(PathNormalizer.normalize(item.getName()), EnumSet.of(Path.Type.volume, Path.Type.directory), attributes.toAttributes(item) ); buckets.add(bucket); listener.chunk(directory, buckets); } } page = response.getNextPageToken(); } while(page != null); return buckets; } catch(IOException e) { throw new GoogleStorageExceptionMappingService().map("Listing directory {0} failed", e, directory); } } GoogleStorageBucketListService(final GoogleStorageSession session); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); }### Answer:
@Test public void testListContainers() throws Exception { final Path container = new Path("/", EnumSet.of(Path.Type.directory)); final AttributedList<Path> list = new GoogleStorageBucketListService(session).list(container, new DisabledListProgressListener()); assertFalse(list.isEmpty()); }
|
### Question:
GoogleStorageLifecycleFeature implements Lifecycle { @Override public LifecycleConfiguration getConfiguration(final Path file) throws BackgroundException { final Path container = containerService.getContainer(file); if(container.isRoot()) { return LifecycleConfiguration.empty(); } if(file.getType().contains(Path.Type.upload)) { return LifecycleConfiguration.empty(); } try { final Bucket.Lifecycle status = session.getClient().buckets().get(container.getName()).execute().getLifecycle(); if(null != status) { Integer transition = null; Integer expiration = null; String storageClass = null; for(Bucket.Lifecycle.Rule rule : status.getRule()) { if(!rule.getCondition().getIsLive()) { continue; } if("SetStorageClass".equals(rule.getAction().getType())) { transition = rule.getCondition().getAge(); storageClass = rule.getAction().getStorageClass(); } if("Delete".equals(rule.getAction().getType())) { expiration = rule.getCondition().getAge(); } } return new LifecycleConfiguration(transition, storageClass, expiration); } return LifecycleConfiguration.empty(); } catch(IOException e) { try { throw new GoogleStorageExceptionMappingService().map("Failure to read attributes of {0}", e, container); } catch(AccessDeniedException | InteroperabilityException l) { log.warn(String.format("Missing permission to read lifecycle configuration for %s %s", container, e.getMessage())); return LifecycleConfiguration.empty(); } } } GoogleStorageLifecycleFeature(final GoogleStorageSession session); @Override void setConfiguration(final Path file, final LifecycleConfiguration configuration); @Override LifecycleConfiguration getConfiguration(final Path file); }### Answer:
@Test public void testGetEmptyConfiguration() throws Exception { assertEquals(LifecycleConfiguration.empty(), new GoogleStorageLifecycleFeature(session).getConfiguration( new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory)))); }
@Test public void testGetConfigurationAccessDenied() throws Exception { assertEquals(LifecycleConfiguration.empty(), new GoogleStorageLifecycleFeature(session).getConfiguration( new Path("bucket", EnumSet.of(Path.Type.directory)) )); }
|
### Question:
GoogleStorageAccessControlListFeature extends DefaultAclFeature implements AclPermission { @Override public void setPermission(final Path file, final Acl acl) throws BackgroundException { try { if(containerService.isContainer(file)) { final List<BucketAccessControl> bucketAccessControls = this.toBucketAccessControl(acl); session.getClient().buckets().update(containerService.getContainer(file).getName(), new Bucket().setAcl(bucketAccessControls)).execute(); } else { final List<ObjectAccessControl> objectAccessControls = this.toObjectAccessControl(acl); session.getClient().objects().update(containerService.getContainer(file).getName(), containerService.getKey(file), new StorageObject().setAcl(objectAccessControls)).execute(); } } catch(IOException e) { final BackgroundException failure = new GoogleStorageExceptionMappingService().map("Cannot change permissions of {0}", e, file); if(file.isPlaceholder()) { if(failure instanceof NotfoundException) { return; } } throw failure; } } GoogleStorageAccessControlListFeature(final GoogleStorageSession session); @Override Acl getPermission(final Path file); @Override void setPermission(final Path file, final Acl acl); @Override List<Acl.User> getAvailableAclUsers(); @Override List<Acl.Role> getAvailableAclRoles(final List<Path> files); }### Answer:
@Test(expected = NotfoundException.class) public void testWriteNotFound() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory)); final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final GoogleStorageAccessControlListFeature f = new GoogleStorageAccessControlListFeature(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:
GoogleStorageAccessControlListFeature extends DefaultAclFeature implements AclPermission { @Override public List<Acl.User> getAvailableAclUsers() { final List<Acl.User> users = new ArrayList<Acl.User>(Arrays.asList( new Acl.CanonicalUser(), new Acl.GroupUser(Acl.GroupUser.AUTHENTICATED, false), new Acl.GroupUser(Acl.GroupUser.EVERYONE, false)) ); users.add(new Acl.EmailUser() { @Override public String getPlaceholder() { return LocaleFactory.localizedString("Google Account Email Address", "S3"); } }); users.add(new Acl.DomainUser(StringUtils.EMPTY) { @Override public String getPlaceholder() { return LocaleFactory.localizedString("Google Apps Domain", "S3"); } }); users.add(new Acl.EmailGroupUser(StringUtils.EMPTY, true) { @Override public String getPlaceholder() { return LocaleFactory.localizedString("Google Group Email Address", "S3"); } }); return users; } GoogleStorageAccessControlListFeature(final GoogleStorageSession session); @Override Acl getPermission(final Path file); @Override void setPermission(final Path file, final Acl acl); @Override List<Acl.User> getAvailableAclUsers(); @Override List<Acl.Role> getAvailableAclRoles(final List<Path> files); }### Answer:
@Test public void testRoles() { final GoogleStorageAccessControlListFeature f = new GoogleStorageAccessControlListFeature(session); final List<Acl.User> users = f.getAvailableAclUsers(); assertTrue(users.contains(new Acl.CanonicalUser())); assertTrue(users.contains(new Acl.EmailUser())); assertTrue(users.contains(new Acl.EmailGroupUser(""))); assertTrue(users.contains(new Acl.DomainUser(""))); }
|
### Question:
GoogleStorageWebsiteDistributionConfiguration implements DistributionConfiguration, Index { @Override public List<Distribution.Method> getMethods(final Path container) { return Collections.singletonList(Distribution.WEBSITE); } GoogleStorageWebsiteDistributionConfiguration(final GoogleStorageSession session); @Override List<Distribution.Method> getMethods(final Path container); @Override String getName(Distribution.Method method); @Override String getName(); @Override DescriptiveUrlBag toUrl(final Path file); @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 String getHostname(); }### Answer:
@Test public void testGetMethods() { final DistributionConfiguration configuration = new GoogleStorageWebsiteDistributionConfiguration(session); assertEquals(Collections.singletonList(Distribution.WEBSITE), configuration.getMethods(new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)))); }
|
### Question:
GoogleStorageWebsiteDistributionConfiguration implements DistributionConfiguration, Index { @Override public String getHostname() { return session.getHost().getProtocol().getDefaultHostname(); } GoogleStorageWebsiteDistributionConfiguration(final GoogleStorageSession session); @Override List<Distribution.Method> getMethods(final Path container); @Override String getName(Distribution.Method method); @Override String getName(); @Override DescriptiveUrlBag toUrl(final Path file); @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 String getHostname(); }### Answer:
@Test public void testGetProtocol() { final DistributionConfiguration configuration = new GoogleStorageWebsiteDistributionConfiguration(session); assertEquals("storage.googleapis.com", configuration.getHostname()); }
|
### Question:
GoogleStorageWebsiteDistributionConfiguration implements DistributionConfiguration, Index { @Override public DescriptiveUrlBag toUrl(final Path file) { final Distribution distribution = new Distribution(URI.create(String.format("%s: Distribution.DOWNLOAD.getScheme(), containerService.getContainer(file).getName(), this.getHostname())), Distribution.DOWNLOAD, false); distribution.setUrl(URI.create(String.format("%s: this.getHostname()))); return new DistributionUrlProvider(distribution).toUrl(file); } GoogleStorageWebsiteDistributionConfiguration(final GoogleStorageSession session); @Override List<Distribution.Method> getMethods(final Path container); @Override String getName(Distribution.Method method); @Override String getName(); @Override DescriptiveUrlBag toUrl(final Path file); @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 String getHostname(); }### Answer:
@Test public void testUrl() { final DistributionConfiguration configuration = new GoogleStorageWebsiteDistributionConfiguration(session); assertEquals("http: DescriptiveUrl.Type.origin).getUrl()); }
|
### Question:
GoogleStorageWebsiteDistributionConfiguration implements DistributionConfiguration, Index { @Override @SuppressWarnings("unchecked") public <T> T getFeature(final Class<T> type, final Distribution.Method method) { if(type == Index.class) { return (T) this; } if(type == DistributionLogging.class) { return (T) new GoogleStorageLoggingFeature(session); } return null; } GoogleStorageWebsiteDistributionConfiguration(final GoogleStorageSession session); @Override List<Distribution.Method> getMethods(final Path container); @Override String getName(Distribution.Method method); @Override String getName(); @Override DescriptiveUrlBag toUrl(final Path file); @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 String getHostname(); }### Answer:
@Test public void testFeatures() { final DistributionConfiguration d = new GoogleStorageWebsiteDistributionConfiguration(session); assertNotNull(d.getFeature(Index.class, Distribution.WEBSITE)); assertNotNull(d.getFeature(DistributionLogging.class, Distribution.WEBSITE)); assertNull(d.getFeature(Cname.class, Distribution.WEBSITE)); }
|
### Question:
GoogleStorageDeleteFeature implements Delete { @Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { try { for(Path file : files.keySet()) { callback.delete(file); if(containerService.isContainer(file)) { session.getClient().buckets().delete(file.getName()).execute(); } else { session.getClient().objects().delete(containerService.getContainer(file).getName(), containerService.getKey(file)).execute(); } } } catch(IOException e) { throw new GoogleStorageExceptionMappingService().map(e); } } GoogleStorageDeleteFeature(final GoogleStorageSession 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 testDeleteContainer() throws Exception { final Path container = new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.volume, Path.Type.directory)); container.attributes().setRegion("US"); new GoogleStorageDirectoryFeature(session).mkdir(container, null, new TransferStatus()); assertTrue(new GoogleStorageFindFeature(session).find(container)); new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(container), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new GoogleStorageFindFeature(session).find(container)); }
|
### Question:
B2MoveFeature implements Move { @Override public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { final Path copy = proxy.copy(source, target, status.length(source.attributes().getSize()), callback); new B2DeleteFeature(session, fileid).delete(Collections.singletonList(new Path(source)), callback, delete); return copy; } B2MoveFeature(final B2Session session, final B2FileidProvider fileid); @Override Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback); @Override boolean isSupported(final Path source, final Path target); @Override boolean isRecursive(final Path source, final Path target); }### Answer:
@Test public void testMove() throws Exception { final B2FileidProvider fileid = new B2FileidProvider(session).withCache(cache); final Path container = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final String name = new AlphanumericRandomStringService().random(); final Path test = new B2TouchFeature(session, fileid).touch(new Path(container, name, EnumSet.of(Path.Type.file)), new TransferStatus()); assertTrue(new B2FindFeature(session, fileid).find(test)); final Path target = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new B2MoveFeature(session, fileid).move(test, target, new TransferStatus(), new Delete.DisabledCallback(), new DisabledConnectionCallback()); assertFalse(new B2FindFeature(session, fileid).find(new Path(container, name, EnumSet.of(Path.Type.file)))); assertTrue(new B2FindFeature(session, fileid).find(target)); new B2DeleteFeature(session, fileid).delete(Collections.<Path>singletonList(target), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
B2UrlProvider implements UrlProvider { @Override public DescriptiveUrlBag toUrl(final Path file) { if(file.isVolume()) { return DescriptiveUrlBag.empty(); } final DescriptiveUrlBag list = new DescriptiveUrlBag(); if(file.isFile()) { final String download = String.format("%s/file/%s/%s", session.getClient().getDownloadUrl(), URIEncoder.encode(containerService.getContainer(file).getName()), URIEncoder.encode(containerService.getKey(file))); list.add(new DescriptiveUrl(URI.create(download), DescriptiveUrl.Type.http, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), Scheme.https.name().toUpperCase(Locale.ROOT)))); list.addAll(new WebUrlProvider(session.getHost()).toUrl(file)); } return list; } B2UrlProvider(final B2Session session); @Override DescriptiveUrlBag toUrl(final Path file); }### Answer:
@Test public void testToUrl() throws Exception { final Path bucket = new Path("/test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final B2FileidProvider fileid = new B2FileidProvider(session).withCache(cache); new B2TouchFeature(session, fileid).touch(test, new TransferStatus()); final B2UrlProvider provider = new B2UrlProvider(session); assertEquals(0, provider.toUrl(bucket).size()); assertEquals(2, provider.toUrl(test).size()); assertNotNull(provider.toUrl(test).find(DescriptiveUrl.Type.http).getUrl()); new B2DeleteFeature(session, fileid).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
B2BucketListService implements RootListService { @Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> buckets = new AttributedList<Path>(); for(B2BucketResponse bucket : session.getClient().listBuckets()) { final PathAttributes attributes = new PathAttributes(); attributes.setVersionId(bucket.getBucketId()); switch(bucket.getBucketType()) { case allPublic: attributes.setAcl(new Acl(new Acl.GroupUser(Acl.GroupUser.EVERYONE, false), new Acl.Role(Acl.Role.READ))); break; } buckets.add(new Path(PathNormalizer.normalize(bucket.getBucketName()), EnumSet.of(Path.Type.directory, Path.Type.volume), attributes)); } listener.chunk(directory, buckets); return buckets; } catch(B2ApiException e) { throw new B2ExceptionMappingService().map("Listing directory {0} failed", e, directory); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } B2BucketListService(final B2Session session); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); }### Answer:
@Test public void testList() throws Exception { final AttributedList<Path> list = new B2BucketListService(session).list( new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory)), new DisabledListProgressListener()); assertFalse(list.isEmpty()); }
|
### Question:
S3HttpRequestRetryHandler extends ExtendedHttpRequestRetryHandler { @Override public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) { if(super.retryRequest(exception, executionCount, context)) { final Object attribute = context.getAttribute(HttpCoreContext.HTTP_REQUEST); if(attribute instanceof HttpUriRequest) { final HttpUriRequest method = (HttpUriRequest) attribute; log.warn(String.format("Retrying request %s", method)); try { authorizer.authorizeHttpRequest(method, context, null); return true; } catch(ServiceException e) { log.warn("Unable to generate updated authorization string for retried request", e); } } } return false; } S3HttpRequestRetryHandler(final JetS3tRequestAuthorizer authorizer, final int retryCount); @Override boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context); }### Answer:
@Test public void testRetryRequest() { final S3HttpRequestRetryHandler h = new S3HttpRequestRetryHandler(new JetS3tRequestAuthorizer() { @Override public void authorizeHttpRequest(final HttpUriRequest httpUriRequest, final HttpContext httpContext, final String s) { } }, 1); final HttpClientContext context = new HttpClientContext(); context.setAttribute(HttpCoreContext.HTTP_REQUEST, new HttpHead()); assertTrue(h.retryRequest(new SSLException(new SocketException("Broken pipe")), 1, context)); }
|
### Question:
B2LargeUploadPartService { public List<B2UploadPartResponse> list(final String fileid) throws BackgroundException { if(log.isInfoEnabled()) { log.info(String.format("List completed parts of file %s", fileid)); } try { final List<B2UploadPartResponse> completed = new ArrayList<B2UploadPartResponse>(); Integer startPartNumber = null; do { final B2ListPartsResponse response = session.getClient().listParts( fileid, startPartNumber, null); completed.addAll(response.getFiles()); startPartNumber = response.getNextPartNumber(); } while(startPartNumber != null); return completed; } catch(B2ApiException e) { throw new B2ExceptionMappingService().map(e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } B2LargeUploadPartService(final B2Session session, final B2FileidProvider fileid); List<B2FileInfoResponse> find(final Path file); List<B2UploadPartResponse> list(final String fileid); void delete(final String id); }### Answer:
@Test public void testList() throws Exception { final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final B2StartLargeFileResponse startResponse = session.getClient().startLargeFileUpload( new B2FileidProvider(session).withCache(cache).getFileid(bucket, new DisabledListProgressListener()), file.getName(), null, Collections.emptyMap()); assertTrue(new B2LargeUploadPartService(session, new B2FileidProvider(session).withCache(cache)).list(startResponse.getFileId()).isEmpty()); session.getClient().cancelLargeFileUpload(startResponse.getFileId()); }
|
### Question:
B2LargeUploadPartService { public void delete(final String id) throws BackgroundException { if(log.isInfoEnabled()) { log.info(String.format("Delete multipart upload for fileid %s", id)); } try { session.getClient().cancelLargeFileUpload(id); } catch(B2ApiException e) { throw new B2ExceptionMappingService().map(e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } B2LargeUploadPartService(final B2Session session, final B2FileidProvider fileid); List<B2FileInfoResponse> find(final Path file); List<B2UploadPartResponse> list(final String fileid); void delete(final String id); }### Answer:
@Test public void testDelete() throws Exception { final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final B2StartLargeFileResponse startResponse = session.getClient().startLargeFileUpload( new B2FileidProvider(session).withCache(cache).getFileid(bucket, new DisabledListProgressListener()), file.getName(), null, Collections.emptyMap()); final String fileid = startResponse.getFileId(); new B2LargeUploadPartService(session, new B2FileidProvider(session).withCache(cache)).delete(startResponse.getFileId()); }
|
### Question:
S3BucketListService implements RootListService { protected String getContainer(final Host host) { if(StringUtils.isBlank(host.getProtocol().getDefaultHostname())) { return null; } final String hostname = host.getHostname(); if(hostname.equals(host.getProtocol().getDefaultHostname())) { return null; } if(hostname.endsWith(host.getProtocol().getDefaultHostname())) { return ServiceUtils.findBucketNameInHostname(hostname, host.getProtocol().getDefaultHostname()); } return null; } S3BucketListService(final S3Session session); S3BucketListService(final S3Session session, final S3LocationFeature.S3Region region); @Override AttributedList<Path> list(final Path directory, final ListProgressListener listener); }### Answer:
@Test public void testGetContainer() { assertEquals("bucketname", new S3BucketListService(new S3Session(new Host(new S3Protocol()))).getContainer(new Host(new S3Protocol(), "bucketname.s3.amazonaws.com"))); assertNull(new S3BucketListService(new S3Session(new Host(new S3Protocol()))).getContainer(new Host(new TestProtocol(), "bucketname.s3.amazonaws.com"))); }
|
### Question:
B2Session extends HttpSession<B2ApiClient> { @Override public void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { try { final String accountId = host.getCredentials().getUsername(); final String applicationKey = host.getCredentials().getPassword(); final B2AuthorizeAccountResponse response = client.authenticate(accountId, applicationKey); if(StringUtils.isNotBlank(response.getBucketId())) { final PathAttributes attributes = new PathAttributes(); attributes.setVersionId(response.getBucketId()); listService.withBucket(new Path(PathNormalizer.normalize(response.getBucketName()), EnumSet.of(Path.Type.directory, Path.Type.volume), attributes)); } retryHandler.setTokens(accountId, applicationKey, response.getAuthorizationToken()); } catch(B2ApiException e) { throw new B2ExceptionMappingService().map(e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } B2Session(final Host host, final X509TrustManager trust, final X509KeyManager key); @Override B2ApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt); @Override void logout(); @Override void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel); @Override @SuppressWarnings("unchecked") T _getFeature(final Class<T> type); }### Answer:
@Test(expected = LoginFailureException.class) public void testLoginFailure() throws Exception { final Host host = new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(), new Credentials( System.getProperties().getProperty("b2.user"), "s" )); final B2Session session = new B2Session(host, new DefaultX509TrustManager(), new DefaultX509KeyManager()); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); }
|
### Question:
B2FindFeature implements Find { @Override public boolean find(final Path file) throws BackgroundException { try { if(containerService.isContainer(file)) { final List<B2BucketResponse> buckets = session.getClient().listBuckets(); for(B2BucketResponse bucket : buckets) { if(StringUtils.equals(containerService.getContainer(file).getName(), bucket.getBucketName())) { return true; } } } else { try { return null != fileid.withCache(cache).getFileid(file, new DisabledListProgressListener()); } catch(NotfoundException e) { return false; } } return false; } catch(B2ApiException e) { throw new B2ExceptionMappingService().map(e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } B2FindFeature(final B2Session session, final B2FileidProvider fileid); @Override boolean find(final Path file); @Override Find withCache(final Cache<Path> cache); }### Answer:
@Test public void testFind() throws Exception { final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final B2FileidProvider fileid = new B2FileidProvider(session).withCache(cache); new B2TouchFeature(session, fileid).touch(file, new TransferStatus()); assertTrue(new B2FindFeature(session, fileid).find(file)); assertFalse(new B2FindFeature(session, fileid).find(new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)))); new B2DeleteFeature(session, fileid).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
SFTPSession extends Session<SSHClient> { @Override public boolean isConnected() { if(super.isConnected()) { return client.isConnected(); } return false; } SFTPSession(final Host h, final X509TrustManager trust, final X509KeyManager key); @Override boolean isConnected(); @Override SSHClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt); @Override boolean alert(final ConnectionCallback prompt); @Override void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel); SFTPEngine sftp(); @Override void disconnect(); @Override @SuppressWarnings("unchecked") T _getFeature(final Class<T> type); }### Answer:
@Test public void testLoginPassword() { assertTrue(session.isConnected()); }
|
### Question:
SFTPReadFeature implements Read { protected int getMaxUnconfirmedReads(final TransferStatus status) { if(-1 == status.getLength()) { return preferences.getInteger("sftp.read.maxunconfirmed"); } return Integer.min(((int) (status.getLength() / preferences.getInteger("connection.chunksize")) + 1), preferences.getInteger("sftp.read.maxunconfirmed")); } SFTPReadFeature(final SFTPSession session); @Override InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback); @Override boolean offset(final Path file); }### Answer:
@Test public void testUnconfirmedReadsNumber() { final SFTPReadFeature feature = new SFTPReadFeature(session); assertEquals(33, feature.getMaxUnconfirmedReads(new TransferStatus().length(TransferStatus.MEGA * 1L))); assertEquals(64, feature.getMaxUnconfirmedReads(new TransferStatus().length((long) (TransferStatus.GIGA * 1.3)))); }
|
### Question:
SFTPDirectoryFeature implements Directory<Void> { @Override public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException { try { final FileAttributes attrs; if(Permission.EMPTY != status.getPermission()) { attrs = new FileAttributes.Builder().withPermissions(Integer.parseInt(status.getPermission().getMode(), 8)).build(); } else { attrs = FileAttributes.EMPTY; } session.sftp().makeDir(folder.getAbsolute(), attrs); } catch(IOException e) { throw new SFTPExceptionMappingService().map("Cannot create folder {0}", e, folder); } return new Path(folder.getParent(), folder.getName(), folder.getType(), new SFTPAttributesFinderFeature(session).find(folder)); } SFTPDirectoryFeature(final SFTPSession session); @Override Path mkdir(final Path folder, final String region, final TransferStatus status); @Override SFTPDirectoryFeature withWriter(final Write<Void> writer); }### Answer:
@Test public void testMakeDirectory() throws Exception { final Path test = new Path(new SFTPHomeDirectoryService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); new SFTPDirectoryFeature(session).mkdir(test, null, new TransferStatus()); assertTrue(new SFTPFindFeature(session).find(test)); new SFTPDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
OpenSSHHostnameConfigurator implements HostnameConfigurator { @Override public String getHostname(final String alias) { if(StringUtils.isBlank(alias)) { return alias; } final String hostname = configuration.lookup(alias).getHostName(); if(StringUtils.isBlank(hostname)) { return alias; } if(log.isInfoEnabled()) { log.info(String.format("Using hostname alias %s from %s", alias, configuration)); } return hostname; } OpenSSHHostnameConfigurator(); OpenSSHHostnameConfigurator(final OpenSshConfig configuration); @Override String getHostname(final String alias); @Override int getPort(final String alias); @Override void reload(); @Override String toString(); }### Answer:
@Test public void testLookup() { OpenSSHHostnameConfigurator c = new OpenSSHHostnameConfigurator( new OpenSshConfig( new Local("src/test/resources", "openssh/config"))); assertEquals("cyberduck.ch", c.getHostname("alias")); }
|
### Question:
OpenSSHHostnameConfigurator implements HostnameConfigurator { @Override public int getPort(final String alias) { if(StringUtils.isBlank(alias)) { return -1; } return configuration.lookup(alias).getPort(); } OpenSSHHostnameConfigurator(); OpenSSHHostnameConfigurator(final OpenSshConfig configuration); @Override String getHostname(final String alias); @Override int getPort(final String alias); @Override void reload(); @Override String toString(); }### Answer:
@Test public void testPort() { OpenSSHHostnameConfigurator c = new OpenSSHHostnameConfigurator( new OpenSshConfig( new Local("src/test/resources", "openssh/config"))); assertEquals(555, c.getPort("portalias")); assertEquals(-1, c.getPort(null)); }
|
### Question:
OpenSSHAgentAuthenticator extends AgentAuthenticator { @Override public Collection<Identity> getIdentities() { if(!SSHAgentConnector.isConnectorAvailable()) { log.warn(String.format("SSH agent %s is not running", this)); return Collections.emptyList(); } if(null == proxy) { return Collections.emptyList(); } if(log.isDebugEnabled()) { log.debug(String.format("Retrieve identities from proxy %s", proxy)); } final List<Identity> identities = Arrays.asList(proxy.getIdentities()); if(log.isDebugEnabled()) { log.debug(String.format("Found %d identities", identities.size())); } return identities; } OpenSSHAgentAuthenticator(); @Override AgentProxy getProxy(); @Override Collection<Identity> getIdentities(); @Override String toString(); }### Answer:
@Test @Ignore public void testGetIdentities() { final OpenSSHAgentAuthenticator authenticator = new OpenSSHAgentAuthenticator(); final Collection<Identity> identities = authenticator.getIdentities(); assertNotNull(authenticator.getProxy()); assertFalse(identities.isEmpty()); }
|
### Question:
PageantAuthenticator extends AgentAuthenticator { @Override public Collection<Identity> getIdentities() { if(!PageantConnector.isConnectorAvailable()) { log.warn(String.format("Disabled agent %s", this)); return Collections.emptyList(); } if(null == proxy) { return Collections.emptyList(); } if(log.isDebugEnabled()) { log.debug(String.format("Retrieve identities from proxy %s", proxy)); } final List<Identity> identities = new ArrayList<Identity>(); if(log.isDebugEnabled()) { log.debug(String.format("Found %d identities", identities.size())); } try { Collections.addAll(identities, proxy.getIdentities()); } catch(Exception e) { log.warn(String.format("Ignore failure reading identities from %s", proxy)); } return identities; } PageantAuthenticator(); @Override AgentProxy getProxy(); @Override Collection<Identity> getIdentities(); }### Answer:
@Test public void testGetIdentities() { final PageantAuthenticator authenticator = new PageantAuthenticator(); final Collection<Identity> identities = authenticator.getIdentities(); switch(Factory.Platform.getDefault()) { case windows: assertNotNull(authenticator.getProxy()); break; default: assertNull(authenticator.getProxy()); assertTrue(identities.isEmpty()); break; } }
|
### Question:
SSHFingerprintGenerator { public String fingerprint(final PublicKey key) throws ChecksumException { return this.fingerprint(new ByteArrayInputStream( new Buffer.PlainBuffer().putPublicKey(key).getCompactData())); } String fingerprint(final PublicKey key); String fingerprint(final InputStream in); }### Answer:
@Test public void testFingerprint() throws Exception { final FileKeyProvider f = new OpenSSHKeyFile.Factory().create(); f.init("", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/71hmi4R+CZqGvZ+aVdaKIt5yb2H87yNAAcdtPAQBJBqKw/vR0iYeU/tnwKWRfnTK/NcN2H6yG/wx0o9WiavUhUaSUPesJo3/PpZ7fZMUk/Va8I7WI0i25XlWJTE8SMFftIuJ8/AVPNSCmL46qy93BlQb8W70O9XQD/yj/Cy6aPb9wlHxdaswrmdoIzI4BS28Tu1F45TalqarqTLm3wY4RpghxHo8LxCgNbmd0cr6XnOmz1RM+rlbkiuSdNphW3Ah2iCHMif/KdRCFCPi5LyUrdheOtQYvQCmFREczb3kyuQPCElQac4DeL37F9ZLLBHnRVi7KxFqDbcbNLadfExx [email protected]"); assertEquals("87:60:23:a3:56:b5:1a:24:8b:63:43:ea:5a:d4:e1:9d", new SSHFingerprintGenerator().fingerprint(f.getPublic()) ); }
|
### Question:
S3TransferAccelerationService implements TransferAcceleration { @Override public boolean getStatus(final Path file) throws BackgroundException { final Path bucket = containerService.getContainer(file); try { return session.getClient().getAccelerateConfig(bucket.getName()).isEnabled(); } catch(S3ServiceException failure) { throw new S3ExceptionMappingService().map("Failure to read attributes of {0}", failure, bucket); } } S3TransferAccelerationService(final S3Session session); S3TransferAccelerationService(final S3Session session, final String hostname); @Override boolean getStatus(final Path file); @Override void setStatus(final Path file, final boolean enabled); @Override boolean prompt(final Host bookmark, final Path file, final ConnectionCallback prompt); @Override void configure(final boolean enable, final Path file); @Override String toString(); static final String S3_ACCELERATE_HOSTNAME; static final String S3_ACCELERATE_DUALSTACK_HOSTNAME; }### Answer:
@Test public void getStatus() throws Exception { final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume)); final S3TransferAccelerationService service = new S3TransferAccelerationService(session); service.getStatus(container); }
|
### Question:
SFTPSymlinkFeature implements Symlink { @Override public void symlink(final Path file, String target) throws BackgroundException { try { session.sftp().symlink(target, file.getAbsolute()); } catch(IOException e) { throw new SFTPExceptionMappingService().map("Cannot create file {0}", e, file); } } SFTPSymlinkFeature(final SFTPSession session); @Override void symlink(final Path file, String target); }### Answer:
@Test public void testSymlink() throws Exception { final SFTPHomeDirectoryService workdir = new SFTPHomeDirectoryService(session); final Path target = new Path(workdir.find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new SFTPTouchFeature(session).touch(target, new TransferStatus()); final Path link = new Path(workdir.find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file, AbstractPath.Type.symboliclink)); new SFTPSymlinkFeature(session).symlink(link, target.getName()); assertTrue(new SFTPFindFeature(session).find(link)); assertEquals(EnumSet.of(Path.Type.file, AbstractPath.Type.symboliclink), new SFTPListService(session).list(workdir.find(), new DisabledListProgressListener()).get(link).getType()); new SFTPDeleteFeature(session).delete(Collections.singletonList(link), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new SFTPFindFeature(session).find(link)); assertTrue(new SFTPFindFeature(session).find(target)); new SFTPDeleteFeature(session).delete(Collections.singletonList(target), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
SFTPQuotaFeature implements Quota { @Override public Space get() throws BackgroundException { final Path home = new SFTPHomeDirectoryService(session).find(); if(this.isSpaceAvailableExtensionAvailable()) { try { return this.getSpaceAvailable(session.sftp(), home); } catch(BackgroundException e) { log.info(String.format("Failure obtaining disk quota. %s", e)); } } if(this.isStatVFSOpenSSHSupported()) { try { return this.getSpaceStatVFSOpenSSH(session.sftp(), home); } catch(BackgroundException e) { log.info(String.format("Failure obtaining disk quota. %s", e)); } } return new Space(0L, Long.MAX_VALUE); } SFTPQuotaFeature(final SFTPSession session); @Override Space get(); }### Answer:
@Test public void testGet() throws Exception { final Quota.Space quota = new SFTPQuotaFeature(session).get(); assertNotNull(quota.available); assertNotNull(quota.used); assertNotEquals(0L, quota.available, 0L); assertEquals(0L, quota.used, 0L); }
|
### Question:
SFTPUnixPermissionFeature extends DefaultUnixPermissionFeature implements UnixPermission { @Override public void setUnixOwner(final Path file, final String owner) throws BackgroundException { final FileAttributes attr = new FileAttributes.Builder() .withUIDGID(new Integer(owner), 0) .build(); try { session.sftp().setAttributes(file.getAbsolute(), attr); } catch(IOException e) { throw new SFTPExceptionMappingService().map("Failure to write attributes of {0}", e, file); } } SFTPUnixPermissionFeature(final SFTPSession 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 @Ignore public void testSetUnixOwner() throws Exception { final Path home = new SFTPHomeDirectoryService(session).find(); final long modified = System.currentTimeMillis(); final Path test = new Path(home, "test", EnumSet.of(Path.Type.file)); new SFTPUnixPermissionFeature(session).setUnixOwner(test, "80"); assertEquals("80", new SFTPListService(session).list(home, new DisabledListProgressListener()).get(test).attributes().getOwner()); }
|
### Question:
SFTPUnixPermissionFeature extends DefaultUnixPermissionFeature implements UnixPermission { @Override public void setUnixGroup(final Path file, final String group) throws BackgroundException { final FileAttributes attr = new FileAttributes.Builder() .withUIDGID(0, new Integer(group)) .build(); try { session.sftp().setAttributes(file.getAbsolute(), attr); } catch(IOException e) { throw new SFTPExceptionMappingService().map("Failure to write attributes of {0}", e, file); } } SFTPUnixPermissionFeature(final SFTPSession 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 @Ignore public void testSetUnixGroup() throws Exception { final Path home = new SFTPHomeDirectoryService(session).find(); final long modified = System.currentTimeMillis(); final Path test = new Path(home, "test", EnumSet.of(Path.Type.file)); new SFTPUnixPermissionFeature(session).setUnixGroup(test, "80"); assertEquals("80", new SFTPListService(session).list(home, new DisabledListProgressListener()).get(test).attributes().getGroup()); }
|
### Question:
SFTPWriteFeature extends AppendWriteFeature<Void> { @Override public boolean random() { return true; } SFTPWriteFeature(final SFTPSession session); @Override StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback); @Override boolean temporary(); @Override boolean random(); }### Answer:
@Test public void testAppend() throws Exception { final Path workdir = new SFTPHomeDirectoryService(session).find(); final Path test = new Path(workdir, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); assertFalse(new SFTPWriteFeature(session).append(test, 0L, PathCache.empty()).append); new SFTPTouchFeature(session).touch(test, new TransferStatus()); assertTrue(new SFTPWriteFeature(session).append(test, 0L, PathCache.empty()).append); new SFTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
SFTPWriteFeature extends AppendWriteFeature<Void> { protected int getMaxUnconfirmedWrites(final TransferStatus status) { if(-1 == status.getLength()) { return preferences.getInteger("sftp.write.maxunconfirmed"); } return Integer.min((int) (status.getLength() / preferences.getInteger("connection.chunksize")) + 1, preferences.getInteger("sftp.write.maxunconfirmed")); } SFTPWriteFeature(final SFTPSession session); @Override StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback); @Override boolean temporary(); @Override boolean random(); }### Answer:
@Test public void testUnconfirmedReadsNumber() { final SFTPWriteFeature feature = new SFTPWriteFeature(session); assertEquals(33, feature.getMaxUnconfirmedWrites(new TransferStatus().length(TransferStatus.MEGA * 1L))); assertEquals(64, feature.getMaxUnconfirmedWrites(new TransferStatus().length((long) (TransferStatus.GIGA * 1.3)))); }
|
### Question:
SFTPHomeDirectoryService extends DefaultHomeFinderService { @Override public Path find() throws BackgroundException { final Path home = super.find(); if(home == DEFAULT_HOME) { try { final String directory = session.sftp().canonicalize("."); 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 SFTPExceptionMappingService().map(e); } } return home; } SFTPHomeDirectoryService(final SFTPSession session); @Override Path find(); }### Answer:
@Test public void testFind() throws Exception { assertEquals(new Path("/", EnumSet.of(Path.Type.directory)), new SFTPHomeDirectoryService(session).find()); }
@Test public void testFindWithWorkdir() { assertEquals(new Path("/sandbox", EnumSet.of(Path.Type.directory)), new SFTPHomeDirectoryService(null).find(new Path("/", EnumSet.of(Path.Type.directory)), "sandbox")); assertEquals(new Path("/sandbox", EnumSet.of(Path.Type.directory)), new SFTPHomeDirectoryService(null).find(new Path("/", EnumSet.of(Path.Type.directory)), "/sandbox")); }
|
### Question:
SFTPTouchFeature implements Touch<Void> { @Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { if(file.isFile()) { try { final FileAttributes attrs; if(Permission.EMPTY != status.getPermission()) { attrs = new FileAttributes.Builder().withPermissions(Integer.parseInt(status.getPermission().getMode(), 8)).build(); } else { attrs = FileAttributes.EMPTY; } final RemoteFile handle = session.sftp().open(file.getAbsolute(), EnumSet.of(OpenMode.CREAT, OpenMode.TRUNC, OpenMode.WRITE), attrs); handle.close(); } catch(IOException e) { throw new SFTPExceptionMappingService().map("Cannot create file {0}", e, file); } } return new Path(file.getParent(), file.getName(), file.getType(), new SFTPAttributesFinderFeature(session).find(file)); } SFTPTouchFeature(final SFTPSession session); @Override Path touch(final Path file, final TransferStatus status); @Override SFTPTouchFeature withWriter(final Write writer); }### Answer:
@Test public void testTouch() throws Exception { final Path home = new SFTPHomeDirectoryService(session).find(); final Path test = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new SFTPTouchFeature(session).touch(test, new TransferStatus()); new SFTPUnixPermissionFeature(session).setUnixPermission(test, new Permission("664")); new SFTPTouchFeature(session).touch(test, new TransferStatus()); final AttributedList<Path> list = new SFTPListService(session).list(home, new DisabledListProgressListener()); assertTrue(list.contains(test)); assertEquals("664", list.get(test).attributes().getPermission().getMode()); new SFTPDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
|
### Question:
SFTPNoneAuthentication implements AuthenticationProvider<Boolean> { @Override public Boolean authenticate(final Host bookmark, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("Login using none authentication with credentials %s", bookmark.getCredentials())); } try { session.getClient().auth(bookmark.getCredentials().getUsername(), new AuthNone()); return session.getClient().isAuthenticated(); } catch(IOException e) { throw new SFTPExceptionMappingService().map(e); } } SFTPNoneAuthentication(final SFTPSession session); @Override Boolean authenticate(final Host bookmark, final LoginCallback prompt, final CancelCallback cancel); @Override String getMethod(); }### Answer:
@Test(expected = LoginFailureException.class) @Ignore public void testAuthenticate() throws Exception { assertFalse(new SFTPNoneAuthentication(session).authenticate(session.getHost(), new DisabledLoginCallback(), new DisabledCancelCallback())); }
|
### Question:
SFTPPasswordAuthentication implements AuthenticationProvider<Boolean> { @Override public Boolean authenticate(final Host bookmark, final LoginCallback callback, final CancelCallback cancel) throws BackgroundException { final Credentials credentials = bookmark.getCredentials(); if(StringUtils.isBlank(credentials.getPassword())) { final Credentials input = callback.prompt(bookmark, credentials.getUsername(), String.format("%s %s", LocaleFactory.localizedString("Login", "Login"), bookmark.getHostname()), MessageFormat.format(LocaleFactory.localizedString( "Login {0} with username and password", "Credentials"), BookmarkNameProvider.toString(bookmark)), new LoginOptions(bookmark.getProtocol()).user(false)); if(input.isPublicKeyAuthentication()) { credentials.setIdentity(input.getIdentity()); return new SFTPPublicKeyAuthentication(session).authenticate(bookmark, callback, cancel); } credentials.setSaved(input.isSaved()); credentials.setPassword(input.getPassword()); } return this.authenticate(bookmark, credentials, callback, cancel); } SFTPPasswordAuthentication(final SFTPSession session); @Override Boolean authenticate(final Host bookmark, final LoginCallback callback, final CancelCallback cancel); @Override String getMethod(); boolean authenticate(final Host host, final Credentials credentials, final LoginCallback callback, final CancelCallback cancel); }### Answer:
@Test(expected = LoginFailureException.class) public void testAuthenticateFailure() throws Exception { session.disconnect(); session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.getHost().getCredentials().setPassword("p"); assertFalse(new SFTPPasswordAuthentication(session).authenticate(session.getHost(), new DisabledLoginCallback(), new DisabledCancelCallback())); }
|
### Question:
S3StorageClassFeature implements Redundancy { @Override public Set<String> getClasses() { return STORAGE_CLASS_LIST; } S3StorageClassFeature(final S3Session session); @Override String getDefault(); @Override Set<String> getClasses(); @Override String getClass(final Path file); @Override void setClass(final Path file, final String redundancy); static final Set<String> STORAGE_CLASS_LIST; }### Answer:
@Test public void testGetClasses() { assertArrayEquals(Arrays.asList(S3Object.STORAGE_CLASS_STANDARD, "INTELLIGENT_TIERING", S3Object.STORAGE_CLASS_INFREQUENT_ACCESS, "ONEZONE_IA", S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY, S3Object.STORAGE_CLASS_GLACIER, "DEEP_ARCHIVE").toArray(), new S3StorageClassFeature(new S3Session(new Host(new S3Protocol()))).getClasses().toArray()); }
|
### Question:
SFTPCompressFeature implements Compress { public void archive(final Archive archive, final Path workdir, final List<Path> files, final ProgressListener listener, final TranscriptListener transcript) throws BackgroundException { command.send(archive.getCompressCommand(workdir, files), listener, transcript); } SFTPCompressFeature(final SFTPSession session); void archive(final Archive archive, final Path workdir, final List<Path> files,
final ProgressListener listener, final TranscriptListener transcript); void unarchive(final Archive archive, final Path file,
final ProgressListener listener, final TranscriptListener transcript); }### Answer:
@Test @Ignore public void testArchive() throws Exception { final SFTPCompressFeature feature = new SFTPCompressFeature(session); for(Archive archive : Archive.getKnownArchives()) { final Path workdir = new SFTPHomeDirectoryService(session).find(); final Path test = new Path(workdir, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); session.getFeature(Touch.class).touch(test, new TransferStatus()); feature.archive(archive, workdir, Collections.singletonList(test), new ProgressListener() { @Override public void message(final String message) { } }, new DisabledTranscriptListener()); assertTrue(new SFTPFindFeature(session).find(archive.getArchive(Collections.singletonList(test)))); new SFTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new SFTPFindFeature(session).find(test)); feature.unarchive(archive, archive.getArchive(Collections.singletonList(test)), new ProgressListener() { @Override public void message(final String message) { } }, new DisabledTranscriptListener()); assertTrue(new SFTPFindFeature(session).find(test)); new SFTPDeleteFeature(session).delete(Collections.singletonList(archive.getArchive( Collections.singletonList(test) )), new DisabledLoginCallback(), new Delete.DisabledCallback()); new SFTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); } }
|
### Question:
SFTPFindFeature implements Find { @Override public boolean find(final Path file) throws BackgroundException { if(file.isRoot()) { return true; } try { new SFTPAttributesFinderFeature(session).find(file); return true; } catch(NotfoundException e) { return false; } } SFTPFindFeature(final SFTPSession session); @Override boolean find(final Path file); }### Answer:
@Test public void testFindNotFound() throws Exception { assertFalse(new SFTPFindFeature(session).find(new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)))); }
@Test public void testFindDirectory() throws Exception { assertTrue(new SFTPFindFeature(session).find(new SFTPHomeDirectoryService(session).find())); }
@Test public void testFindFile() throws Exception { final Path file = new Path(new SFTPHomeDirectoryService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new SFTPTouchFeature(session).touch(file, new TransferStatus()); assertTrue(new SFTPFindFeature(session).find(file)); new SFTPDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Test public void testFindRoot() throws Exception { assertTrue(new SFTPFindFeature(session).find(new Path("/", EnumSet.of(Path.Type.directory)))); }
|
### Question:
SwiftProtocol extends AbstractProtocol { @Override public boolean isHostnameConfigurable() { return true; } @Override String getName(); @Override String getDescription(); @Override String getIdentifier(); @Override Scheme getScheme(); @Override boolean isHostnameConfigurable(); @Override String getContext(); @Override DirectoryTimestamp getDirectoryTimestamp(); @Override Comparator<String> getListComparator(); }### Answer:
@Test public void testConfigurable() { assertTrue(new SwiftProtocol().isHostnameConfigurable()); assertTrue(new SwiftProtocol().isPortConfigurable()); }
|
### Question:
S3StorageClassFeature implements Redundancy { @Override public String getClass(final Path file) throws BackgroundException { if(containerService.isContainer(file)) { final String key = String.format("s3.storageclass.%s", containerService.getContainer(file).getName()); if(StringUtils.isNotBlank(preferences.getProperty(key))) { return preferences.getProperty(key); } return S3Object.STORAGE_CLASS_STANDARD; } final String redundancy = new S3AttributesFinderFeature(session).find(file).getStorageClass(); if(StringUtils.isBlank(redundancy)) { return S3Object.STORAGE_CLASS_STANDARD; } return redundancy; } S3StorageClassFeature(final S3Session session); @Override String getDefault(); @Override Set<String> getClasses(); @Override String getClass(final Path file); @Override void setClass(final Path file, final String redundancy); static final Set<String> STORAGE_CLASS_LIST; }### Answer:
@Test(expected = NotfoundException.class) public void testNotFound() throws Exception { final Path container = new Path("versioning-test-us-east-1-cyberduck", EnumSet.of(Path.Type.volume)); final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final S3StorageClassFeature feature = new S3StorageClassFeature(session); feature.getClass(test); }
|
### Question:
SwiftDistributionConfiguration implements DistributionConfiguration, Index, DistributionLogging { @Override public String getName() { return LocaleFactory.localizedString("Akamai", "Mosso"); } SwiftDistributionConfiguration(final SwiftSession session, final Map<Path, Distribution> distributions); SwiftDistributionConfiguration(final SwiftSession session, final Map<Path, Distribution> distributions, final SwiftRegionService regionService); @Override void write(final Path file, final Distribution configuration, final LoginCallback prompt); @Override Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt); @Override @SuppressWarnings("unchecked") T getFeature(final Class<T> type, final Distribution.Method method); @Override DescriptiveUrlBag toUrl(final Path file); @Override String getHostname(); @Override List<Distribution.Method> getMethods(final Path container); @Override String getName(); @Override String getName(final Distribution.Method method); }### Answer:
@Test public void testGetName() throws Exception { final DistributionConfiguration configuration = new SwiftDistributionConfiguration(session, Collections.emptyMap()); assertEquals("Akamai", configuration.getName()); assertEquals("Akamai", configuration.getName(Distribution.DOWNLOAD)); }
|
### Question:
SwiftDistributionConfiguration implements DistributionConfiguration, Index, DistributionLogging { @Override @SuppressWarnings("unchecked") public <T> T getFeature(final Class<T> type, final Distribution.Method method) { if(type == Purge.class) { return (T) new SwiftDistributionPurgeFeature(session, regionService); } if(type == Index.class) { return (T) this; } if(type == DistributionLogging.class) { return (T) this; } return null; } SwiftDistributionConfiguration(final SwiftSession session, final Map<Path, Distribution> distributions); SwiftDistributionConfiguration(final SwiftSession session, final Map<Path, Distribution> distributions, final SwiftRegionService regionService); @Override void write(final Path file, final Distribution configuration, final LoginCallback prompt); @Override Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt); @Override @SuppressWarnings("unchecked") T getFeature(final Class<T> type, final Distribution.Method method); @Override DescriptiveUrlBag toUrl(final Path file); @Override String getHostname(); @Override List<Distribution.Method> getMethods(final Path container); @Override String getName(); @Override String getName(final Distribution.Method method); }### Answer:
@Test public void testFeatures() throws Exception { final DistributionConfiguration configuration = new SwiftDistributionConfiguration(session, Collections.emptyMap()); assertNotNull(configuration.getFeature(Purge.class, Distribution.DOWNLOAD)); assertNotNull(configuration.getFeature(Index.class, Distribution.DOWNLOAD)); assertNotNull(configuration.getFeature(DistributionLogging.class, Distribution.DOWNLOAD)); assertNull(configuration.getFeature(Cname.class, Distribution.DOWNLOAD)); }
|
### Question:
SwiftQuotaFeature implements Quota { @Override public Space get() throws BackgroundException { long used = 0L; try { for(Region region : session.getClient().getRegions()) { final long bytes = session.getClient().getAccountInfo(region).getBytesUsed(); if(log.isInfoEnabled()) { log.info(String.format("Add %d used in region %s", bytes, region)); } used += bytes; } } catch(GenericException e) { throw new SwiftExceptionMappingService().map("Failure to read attributes of {0}", e, new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory))); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Failure to read attributes of {0}", e, new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory))); } return new Space(used, Long.MAX_VALUE); } SwiftQuotaFeature(final SwiftSession session); @Override Space get(); }### Answer:
@Test public void testGet() throws Exception { final Quota.Space quota = new SwiftQuotaFeature(session).get(); assertNotNull(quota.available); assertNotNull(quota.used); assertNotEquals(0L, quota.available, 0L); assertNotEquals(0L, quota.used, 0L); }
|
### Question:
SwiftMoveFeature implements Move { @Override public boolean isSupported(final Path source, final Path target) { return !containerService.isContainer(source); } SwiftMoveFeature(final SwiftSession session); SwiftMoveFeature(final SwiftSession session, final SwiftRegionService regionService); @Override Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback); @Override boolean isSupported(final Path source, final Path target); }### Answer:
@Test public void testSupport() { final Path c = new Path("/c", EnumSet.of(Path.Type.directory)); assertFalse(new SwiftMoveFeature(null).isSupported(c, c)); final Path cf = new Path("/c/f", EnumSet.of(Path.Type.directory)); assertTrue(new SwiftMoveFeature(null).isSupported(cf, cf)); }
|
### Question:
SwiftSegmentService { public String manifest(final String container, final List<StorageObject> objects) { JsonArray manifestSLO = new JsonArray(); for(StorageObject s : objects) { JsonObject segmentJSON = new JsonObject(); segmentJSON.addProperty("path", String.format("/%s/%s", container, s.getName())); segmentJSON.addProperty("etag", s.getMd5sum()); segmentJSON.addProperty("size_bytes", s.getSize()); manifestSLO.add(segmentJSON); } return manifestSLO.toString(); } SwiftSegmentService(final SwiftSession session); SwiftSegmentService(final SwiftSession session, final String prefix); SwiftSegmentService(final SwiftSession session, final SwiftRegionService regionService); SwiftSegmentService(final SwiftSession session, final SwiftRegionService regionService, final String prefix); List<Path> list(final Path file); Path getSegmentsDirectory(final Path file, final Long size); Path getSegment(final Path file, final Long size, int segmentNumber); String manifest(final String container, final List<StorageObject> objects); Checksum checksum(final ChecksumCompute checksum, final List<StorageObject> objects); }### Answer:
@Test public void testManifest() { final SwiftSegmentService service = new SwiftSegmentService(session); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final StorageObject a = new StorageObject("a"); a.setMd5sum("m1"); a.setSize(1L); final StorageObject b = new StorageObject("b"); b.setMd5sum("m2"); b.setSize(1L); final String manifest = service.manifest(container.getName(), Arrays.asList(a, b)); assertEquals("[{\"path\":\"/test.cyberduck.ch/a\",\"etag\":\"m1\",\"size_bytes\":1},{\"path\":\"/test.cyberduck.ch/b\",\"etag\":\"m2\",\"size_bytes\":1}]", manifest); }
|
### Question:
SwiftSegmentService { public Checksum checksum(final ChecksumCompute checksum, final List<StorageObject> objects) throws ChecksumException { final StringBuilder concatenated = new StringBuilder(); for(StorageObject s : objects) { concatenated.append(s.getMd5sum()); } return checksum.compute(IOUtils.toInputStream(concatenated.toString(), Charset.defaultCharset()), new TransferStatus()); } SwiftSegmentService(final SwiftSession session); SwiftSegmentService(final SwiftSession session, final String prefix); SwiftSegmentService(final SwiftSession session, final SwiftRegionService regionService); SwiftSegmentService(final SwiftSession session, final SwiftRegionService regionService, final String prefix); List<Path> list(final Path file); Path getSegmentsDirectory(final Path file, final Long size); Path getSegment(final Path file, final Long size, int segmentNumber); String manifest(final String container, final List<StorageObject> objects); Checksum checksum(final ChecksumCompute checksum, final List<StorageObject> objects); }### Answer:
@Test public void testChecksum() throws Exception { final SwiftSegmentService service = new SwiftSegmentService(session); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final Path file = new Path(container, "a", EnumSet.of(Path.Type.file)); final StorageObject a = new StorageObject("a"); a.setMd5sum("m1"); a.setSize(1L); final StorageObject b = new StorageObject("b"); b.setMd5sum("m2"); b.setSize(1L); final Checksum checksum = service.checksum(new MD5ChecksumCompute(), Arrays.asList(a, b)); assertEquals(new MD5ChecksumCompute().compute(IOUtils.toInputStream("m1m2", Charset.defaultCharset()), new TransferStatus()), checksum); }
|
### Question:
SwiftSegmentService { public Path getSegmentsDirectory(final Path file, final Long size) { return new Path(file.getParent(), String.format("%s%s/%d", prefix, file.getName(), size), EnumSet.of(Path.Type.directory)); } SwiftSegmentService(final SwiftSession session); SwiftSegmentService(final SwiftSession session, final String prefix); SwiftSegmentService(final SwiftSession session, final SwiftRegionService regionService); SwiftSegmentService(final SwiftSession session, final SwiftRegionService regionService, final String prefix); List<Path> list(final Path file); Path getSegmentsDirectory(final Path file, final Long size); Path getSegment(final Path file, final Long size, int segmentNumber); String manifest(final String container, final List<StorageObject> objects); Checksum checksum(final ChecksumCompute checksum, final List<StorageObject> objects); }### Answer:
@Test public void testGetSegmentsDirectory() { final SwiftSegmentService service = new SwiftSegmentService(session, ".prefix/"); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); final String name = UUID.randomUUID().toString(); final String key = UUID.randomUUID().toString() + "/" + name; assertEquals("/test.cyberduck.ch/.prefix/" + name + "/3", service.getSegmentsDirectory(new Path(container, key, EnumSet.of(Path.Type.file)), 3L).getAbsolute()); final Path directory = new Path(container, "dir", EnumSet.of(Path.Type.directory)); assertEquals("/test.cyberduck.ch/dir/.prefix/" + name + "/3", service.getSegmentsDirectory(new Path(directory, key, EnumSet.of(Path.Type.file)), 3L).getAbsolute()); }
|
### Question:
SwiftSegmentService { public Path getSegment(final Path file, final Long size, int segmentNumber) { return new Path(this.getSegmentsDirectory(file, size), String.format("%08d", segmentNumber), EnumSet.of(Path.Type.file)); } SwiftSegmentService(final SwiftSession session); SwiftSegmentService(final SwiftSession session, final String prefix); SwiftSegmentService(final SwiftSession session, final SwiftRegionService regionService); SwiftSegmentService(final SwiftSession session, final SwiftRegionService regionService, final String prefix); List<Path> list(final Path file); Path getSegmentsDirectory(final Path file, final Long size); Path getSegment(final Path file, final Long size, int segmentNumber); String manifest(final String container, final List<StorageObject> objects); Checksum checksum(final ChecksumCompute checksum, final List<StorageObject> objects); }### Answer:
@Test public void testGetSegmentName() { final SwiftSegmentService service = new SwiftSegmentService(session, ".prefix/"); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path directory = new Path(container, "dir", EnumSet.of(Path.Type.directory)); final String name = "name"; final String key = "sub/" + name; assertEquals("/test.cyberduck.ch/dir/.prefix/name/1/00000001", service.getSegment(new Path(directory, key, EnumSet.of(Path.Type.file)), 1L, 1).getAbsolute()); }
|
### Question:
SwiftRegionService { public Region lookup(final Path file) throws BackgroundException { final Path container = containerService.getContainer(file); if(Location.unknown.equals(new SwiftLocationFeature.SwiftRegion(container.attributes().getRegion()))) { return this.lookup(location.getLocation(container)); } return this.lookup(new SwiftLocationFeature.SwiftRegion(container.attributes().getRegion())); } SwiftRegionService(final SwiftSession session); SwiftRegionService(final SwiftSession session, final SwiftLocationFeature location); Region lookup(final Path file); Region lookup(final Location.Name location); }### Answer:
@Test public void testLookupDefault() throws Exception { final Region lookup = new SwiftRegionService(session).lookup(Location.unknown); assertTrue(lookup.isDefault()); assertEquals("DFW", lookup.getRegionId()); assertNotNull(lookup.getCDNManagementUrl()); assertNotNull(lookup.getStorageUrl()); }
@Test public void testFindDefaultLocationInBookmark() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new SwiftProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( new Local("../profiles/Rackspace US (IAD).cyberduckprofile")); final SwiftSession session = new SwiftSession( new Host(profile, "identity.api.rackspacecloud.com", new Credentials( System.getProperties().getProperty("rackspace.key"), System.getProperties().getProperty("rackspace.secret") )), new DisabledX509TrustManager(), new DefaultX509KeyManager()) { }; assertEquals("IAD", session.getHost().getRegion()); final Region location = new SwiftRegionService(session).lookup(new Path("/test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume))); assertNotNull(location); assertEquals("IAD", location.getRegionId()); }
|
### Question:
SwiftTouchFeature implements Touch<StorageObject> { @Override public boolean isSupported(final Path workdir, final String filename) { return !workdir.isRoot(); } SwiftTouchFeature(final SwiftSession session, final SwiftRegionService regionService); @Override Path touch(final Path file, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String filename); @Override Touch<StorageObject> withWriter(final Write<StorageObject> writer); }### Answer:
@Test public void testSupported() { assertFalse(new SwiftTouchFeature(session, new SwiftRegionService(session)).isSupported(new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)), StringUtils.EMPTY)); assertTrue(new SwiftTouchFeature(session, new SwiftRegionService(session)).isSupported(new Path("/container", EnumSet.of(Path.Type.directory, Path.Type.volume)), StringUtils.EMPTY)); }
|
### Question:
SwiftTouchFeature implements Touch<StorageObject> { @Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { status.setLength(0L); final StatusOutputStream<StorageObject> out = writer.write(file, status, new DisabledConnectionCallback()); new DefaultStreamCloser().close(out); final StorageObject metadata = out.getStatus(); return new Path(file.getParent(), file.getName(), file.getType(), new SwiftAttributesFinderFeature(session, regionService).toAttributes(metadata)); } SwiftTouchFeature(final SwiftSession session, final SwiftRegionService regionService); @Override Path touch(final Path file, final TransferStatus status); @Override boolean isSupported(final Path workdir, final String filename); @Override Touch<StorageObject> withWriter(final Write<StorageObject> writer); }### Answer:
@Test public void testTouch() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final Path test = new SwiftTouchFeature(session, new SwiftRegionService(session)).touch( new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); final PathAttributes attributes = new SwiftAttributesFinderFeature(session).find(test); assertEquals(test.attributes().getChecksum(), attributes.getChecksum()); assertNotEquals(-1L, attributes.getModificationDate()); }
|
### Question:
SwiftLocationFeature implements Location { @Override public Set<Name> getLocations() { final Set<Name> locations = new LinkedHashSet<Name>(); if(StringUtils.isNotBlank(session.getHost().getRegion())) { locations.add(new SwiftRegion(session.getHost().getRegion())); } else { final List<Region> regions = new ArrayList<Region>(session.getClient().getRegions()); regions.sort(new Comparator<Region>() { @Override public int compare(final Region r1, final Region r2) { if(r1.isDefault()) { return -1; } if(r2.isDefault()) { return 1; } return 0; } }); for(Region region : regions) { if(StringUtils.isBlank(region.getRegionId())) { continue; } locations.add(new SwiftRegion(region.getRegionId())); } } return locations; } SwiftLocationFeature(final SwiftSession session); @Override Set<Name> getLocations(); @Override Name getLocation(final Path file); }### Answer:
@Test public void testGetLocations() throws Exception { final Set<Location.Name> locations = new SwiftLocationFeature(session).getLocations(); assertTrue(locations.contains(new SwiftLocationFeature.SwiftRegion("DFW"))); assertTrue(locations.contains(new SwiftLocationFeature.SwiftRegion("ORD"))); assertTrue(locations.contains(new SwiftLocationFeature.SwiftRegion("SYD"))); assertEquals(new SwiftLocationFeature.SwiftRegion("DFW"), locations.iterator().next()); }
|
### Question:
SwiftDistributionPurgeFeature implements Purge { @Override public void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt) throws BackgroundException { try { for(Path file : files) { if(containerService.isContainer(file)) { session.getClient().purgeCDNContainer(regionService.lookup(containerService.getContainer(file)), container.getName(), null); } else { session.getClient().purgeCDNObject(regionService.lookup(containerService.getContainer(file)), container.getName(), containerService.getKey(file), null); } } } catch(GenericException e) { throw new SwiftExceptionMappingService().map("Cannot write CDN configuration", e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Cannot write CDN configuration", e); } } SwiftDistributionPurgeFeature(final SwiftSession session); SwiftDistributionPurgeFeature(final SwiftSession session, final SwiftRegionService regionService); @Override void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt); }### Answer:
@Test(expected = InteroperabilityException.class) public void testInvalidateContainer() throws Exception { final SwiftDistributionPurgeFeature feature = new SwiftDistributionPurgeFeature(session); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.volume, Path.Type.directory)); container.attributes().setRegion("IAD"); feature.invalidate(container, Distribution.DOWNLOAD, Collections.singletonList(container), new DisabledLoginCallback()); }
@Test public void testInvalidateFile() throws Exception { final SwiftDistributionPurgeFeature feature = new SwiftDistributionPurgeFeature(session); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.volume, Path.Type.directory)); container.attributes().setRegion("IAD"); feature.invalidate(container, Distribution.DOWNLOAD, Collections.singletonList(new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file))), new DisabledLoginCallback()); }
|
### Question:
SwiftMetadataFeature implements Headers { @Override public Map<String, String> getMetadata(final Path file) throws BackgroundException { try { if(containerService.isContainer(file)) { final ContainerMetadata meta = session.getClient().getContainerMetaData(regionService.lookup(file), containerService.getContainer(file).getName()); return meta.getMetaData(); } else { final ObjectMetadata meta = session.getClient().getObjectMetaData(regionService.lookup(file), containerService.getContainer(file).getName(), containerService.getKey(file)); return meta.getMetaData(); } } catch(GenericException e) { throw new SwiftExceptionMappingService().map("Failure to read attributes of {0}", e, file); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Failure to read attributes of {0}", e, file); } } SwiftMetadataFeature(final SwiftSession session); SwiftMetadataFeature(final SwiftSession session, final SwiftRegionService regionService); @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 testGetContainerMetadata() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final Map<String, String> metadata = new SwiftMetadataFeature(session).getMetadata(container); assertFalse(metadata.isEmpty()); }
|
### Question:
SwiftAccountLoader extends OneTimeSchedulerFeature<Map<Region, AccountInfo>> { @Override protected Map<Region, AccountInfo> operate(final PasswordCallback callback, final Path file) throws BackgroundException { try { final Map<Region, AccountInfo> accounts = new ConcurrentHashMap<>(); for(Region region : session.getClient().getRegions()) { final AccountInfo info = session.getClient().getAccountInfo(region); if(log.isInfoEnabled()) { log.info(String.format("Signing key is %s", info.getTempUrlKey())); } if(StringUtils.isBlank(info.getTempUrlKey())) { try { final String key = new AsciiRandomStringService().random(); if(log.isDebugEnabled()) { log.debug(String.format("Set acccount temp URL key to %s", key)); } session.getClient().updateAccountMetadata(region, Collections.singletonMap("X-Account-Meta-Temp-URL-Key", key)); info.setTempUrlKey(key); } catch(GenericException e) { log.warn(String.format("Ignore failure %s updating account metadata", e)); } } accounts.put(region, info); } return accounts; } catch(GenericException e) { throw new SwiftExceptionMappingService().map(e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } SwiftAccountLoader(final SwiftSession session); }### Answer:
@Test public void testOperate() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); assertFalse(new SwiftAccountLoader(session).operate(new DisabledLoginCallback(), container).isEmpty()); }
|
### Question:
SwiftExceptionMappingService extends AbstractExceptionMappingService<GenericException> { @Override public BackgroundException map(final GenericException e) { final StringBuilder buffer = new StringBuilder(); this.append(buffer, e.getMessage()); final StatusLine status = e.getHttpStatusLine(); if(null != status) { this.append(buffer, String.format("%d %s", status.getStatusCode(), status.getReasonPhrase())); } switch(e.getHttpStatusCode()) { case HttpStatus.SC_BAD_REQUEST: return new LoginFailureException(buffer.toString(), e); } return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(e.getHttpStatusCode(), buffer.toString())); } @Override BackgroundException map(final GenericException e); }### Answer:
@Test public void testLoginFailure() { final GenericException f = new GenericException( "message", new Header[]{}, new BasicStatusLine(new ProtocolVersion("http", 1, 1), 403, "Forbidden")); assertTrue(new SwiftExceptionMappingService().map(f) instanceof AccessDeniedException); assertEquals("Access denied", new SwiftExceptionMappingService().map(f).getMessage()); assertEquals("Message. 403 Forbidden. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map(f).getDetail()); }
@Test public void testMap() { assertEquals("Message. 500 reason. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map( new GenericException("message", null, new StatusLine() { @Override public ProtocolVersion getProtocolVersion() { throw new UnsupportedOperationException(); } @Override public int getStatusCode() { return 500; } @Override public String getReasonPhrase() { return "reason"; } })).getDetail()); }
|
### Question:
SwiftSmallObjectUploadFeature 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); } } SwiftSmallObjectUploadFeature(final Write<StorageObject> writer); }### Answer:
@Test public void testDecorate() throws Exception { final NullInputStream n = new NullInputStream(1L); assertSame(NullInputStream.class, new SwiftSmallObjectUploadFeature(new SwiftWriteFeature( session, new SwiftRegionService(session))).decorate(n, null).getClass()); }
|
### Question:
SwiftSmallObjectUploadFeature extends HttpUploadFeature<StorageObject, MessageDigest> { @Override protected void post(final Path file, final MessageDigest digest, final StorageObject response) throws BackgroundException { this.verify(file, digest, Checksum.parse(response.getMd5sum())); } SwiftSmallObjectUploadFeature(final Write<StorageObject> writer); }### Answer:
@Test(expected = ChecksumException.class) public void testPostChecksumFailure() throws Exception { final StorageObject o = new StorageObject("f"); o.setMd5sum("d41d8cd98f00b204e9800998ecf8427f"); try { new SwiftSmallObjectUploadFeature(new SwiftWriteFeature( session, new SwiftRegionService(session))).post( new Path("/f", EnumSet.of(Path.Type.file)), MessageDigest.getInstance("MD5"), o ); } catch(ChecksumException e) { assertEquals("Upload f failed", e.getMessage()); assertEquals("Mismatch between MD5 hash d41d8cd98f00b204e9800998ecf8427e of uploaded data and ETag d41d8cd98f00b204e9800998ecf8427f returned by the server.", e.getDetail()); throw e; } }
@Test public void testPostChecksum() throws Exception { final StorageObject o = new StorageObject("f"); o.setMd5sum("d41d8cd98f00b204e9800998ecf8427e"); new SwiftSmallObjectUploadFeature(new SwiftWriteFeature( session, new SwiftRegionService(session))).post( new Path("/f", EnumSet.of(Path.Type.file)), MessageDigest.getInstance("MD5"), o ); }
|
### Question:
TerminalBrowserLauncher implements BrowserLauncher { @Override public boolean open(final String url) { console.printf("%n%s", url); return false; } @Override boolean open(final String url); }### Answer:
@Test public void open() { assertFalse(new TerminalBrowserLauncher().open("https: }
|
### Question:
TerminalProgressListener implements ProgressListener { @Override public void message(final String message) { if(StringUtils.isBlank(message)) { return; } final StringAppender appender = new StringAppender('…'); appender.append(message); console.printf("\r%s%s%s", Ansi.ansi() .fg(Ansi.Color.CYAN) .saveCursorPosition() .eraseLine(Ansi.Erase.ALL) .restoreCursorPosition(), appender.toString(), Ansi.ansi().reset()); } @Override void message(final String message); }### Answer:
@Test public void testNullMessage() { new TerminalProgressListener().message(null); }
@Test public void testMessage() { new TerminalProgressListener().message("b"); }
|
### Question:
DeletePathFinder implements TransferItemFinder { @Override public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) { if(StringUtils.containsAny(remote.getName(), '*')) { return Collections.singleton(new TransferItem(remote.getParent())); } return Collections.singleton(new TransferItem(remote)); } @Override Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote); }### Answer:
@Test public void testFindDirectory() throws Exception { final CommandLineParser parser = new PosixParser(); final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--delete", "rackspace: assertTrue(new DeletePathFinder().find(input, TerminalAction.delete, new Path("/remote", EnumSet.of(Path.Type.directory))).contains( new TransferItem(new Path("/remote", EnumSet.of(Path.Type.directory))) )); }
@Test public void testFindFile() throws Exception { final CommandLineParser parser = new PosixParser(); final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--delete", "rackspace: assertTrue(new DeletePathFinder().find(input, TerminalAction.delete, new Path("/remote", EnumSet.of(Path.Type.file))).contains( new TransferItem(new Path("/remote", EnumSet.of(Path.Type.file))) )); }
@Test public void testFindWildcard() throws Exception { final CommandLineParser parser = new PosixParser(); final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--delete", "rackspace: assertTrue(new DeletePathFinder().find(input, TerminalAction.delete, new Path("/remote/*.txt", EnumSet.of(Path.Type.file))).contains( new TransferItem(new Path("/remote", EnumSet.of(Path.Type.directory))) )); }
|
### Question:
TerminalStreamListener implements StreamListener { @Override public void recv(final long bytes) { this.increment(); } TerminalStreamListener(final TransferSpeedometer meter); TerminalStreamListener(final TransferSpeedometer meter, final int width); @Override void recv(final long bytes); @Override void sent(final long bytes); }### Answer:
@Test public void testRecv() { final DownloadTransfer transfer = new DownloadTransfer(new Host(new TestProtocol()), Collections.<TransferItem>emptyList()); final TerminalStreamListener l = new TerminalStreamListener(new TransferSpeedometer(transfer)); l.recv(1L); transfer.addSize(1L); l.recv(1L); }
|
### Question:
TerminalStreamListener implements StreamListener { @Override public void sent(final long bytes) { this.increment(); } TerminalStreamListener(final TransferSpeedometer meter); TerminalStreamListener(final TransferSpeedometer meter, final int width); @Override void recv(final long bytes); @Override void sent(final long bytes); }### Answer:
@Test public void testSent() { final DownloadTransfer transfer = new DownloadTransfer(new Host(new TestProtocol()), Collections.<TransferItem>emptyList()); final TerminalStreamListener l = new TerminalStreamListener(new TransferSpeedometer(transfer)); l.sent(1L); transfer.addSize(1L); l.sent(1L); }
|
### Question:
TerminalLoginCallback extends TerminalPasswordCallback implements LoginCallback { @Override public void warn(final Host bookmark, final String title, final String reason, final String defaultButton, final String cancelButton, final String preference) throws ConnectionCanceledException { console.printf("%n%s", reason); if(!prompt.prompt(String.format("%s (y) or %s (n): ", defaultButton, cancelButton))) { throw new LoginCanceledException(); } } TerminalLoginCallback(); TerminalLoginCallback(final TerminalPromptReader prompt); @Override void warn(final Host bookmark, final String title, final String reason,
final String defaultButton, final String cancelButton, final String preference); @Override Credentials prompt(final Host bookmark, final String username, final String title, final String reason, final LoginOptions options); @Override Local select(final Local identity); }### Answer:
@Test(expected = LoginCanceledException.class) public void testWarn() throws Exception { new TerminalLoginCallback(new TerminalPromptReader() { @Override public boolean prompt(final String message) { return false; } }).warn(new Host(new TestProtocol()), "", "", "", "", ""); }
|
### Question:
DownloadGlobFilter extends DownloadDuplicateFilter { @Override public boolean accept(final Path file) { if(!super.accept(file)) { return false; } if(pattern.matcher(file.getName()).matches()) { return true; } if(log.isDebugEnabled()) { log.debug(String.format("Skip %s excluded with regex", file.getAbsolute())); } return false; } DownloadGlobFilter(final String glob); @Override boolean accept(final Path file); @Override Pattern toPattern(); @Override String toString(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testAccept() { assertTrue(new DownloadGlobFilter("*.css").accept(new Path("/dir/f.css", EnumSet.of(Path.Type.file)))); assertFalse(new DownloadGlobFilter("*.css").accept(new Path("/dir/f.png", EnumSet.of(Path.Type.file)))); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.