method2testcases
stringlengths
118
3.08k
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public int[] getInboundPorts() { return Ints.toArray(inboundPorts); } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testDefaultOpen22() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getInboundPorts()[0], 22); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public boolean shouldBlockUntilRunning() { return blockUntilRunning; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testblockUntilRunningDefault() { TemplateOptions options = new TemplateOptions(); assertEquals(options.toString(), "{}"); assertEquals(options.shouldBlockUntilRunning(), true); }
### Question: JschSshClient implements SshClient { SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); if (e.getMessage() != null && e.getMessage().indexOf("Auth fail") != -1) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } JschSshClient(ProxyConfig proxyConfig, BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket, LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); @Override void put(String path, String contents); void connect(); Payload get(String path); @Override void put(String path, Payload contents); @Override String toString(); @Override @PreDestroy void disconnect(); @Override boolean isConnected(); ExecResponse exec(String command); @Override String getHostAddress(); @Override String getUsername(); @Override ExecChannel execChannel(String command); }### Answer: @Test(expectedExceptions = AuthorizationException.class) public void testPropateConvertsAuthException() { ssh.propagate(new JSchException("Auth fail"), ""); }
### Question: DelegatingImageExtension implements ImageExtension { public boolean deleteImage(String id) { boolean success = delegate.deleteImage(id); if (success) { imageCache.removeImage(id); } return success; } @Inject DelegatingImageExtension(@Assisted ImageCacheSupplier imageCache, @Assisted ImageExtension delegate, AddDefaultCredentialsToImage addDefaultCredentialsToImage, Map<String, Credentials> credentialStore); ImageTemplate buildImageTemplateFromNode(String name, String id); ListenableFuture<Image> createImage(final ImageTemplate template); boolean deleteImage(String id); }### Answer: @Test public void deleteUnregistersImageFromCache() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); expect(delegate.deleteImage("test")).andReturn(true); imageCache.removeImage("test"); expectLastCall(); replay(delegate, imageCache); new DelegatingImageExtension(imageCache, delegate, null, null).deleteImage("test"); verify(delegate, imageCache); } @Test public void deleteDoesNotUnregisterImageFromCacheWhenFailed() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); expect(delegate.deleteImage("test")).andReturn(false); replay(delegate, imageCache); new DelegatingImageExtension(imageCache, delegate, null, null).deleteImage("test"); verify(delegate, imageCache); }
### Question: ProfitBricksSoapMessageEnvelope implements HttpRequestFilter { @Override public HttpRequest filter(HttpRequest request) throws HttpException { checkNotNull(request.getPayload(), "HTTP Request must contain payload message."); return createSoapRequest(request); } @Override HttpRequest filter(HttpRequest request); }### Answer: @Test public void testPayloadEnclosedWithSoapTags() { String requestBody = "<ws:getAllDataCenters/>"; String expectedPayload = SOAP_PREFIX.concat(requestBody).concat(SOAP_SUFFIX); HttpRequest request = HttpRequest.builder().method("POST").endpoint(ENDPOINT).payload(requestBody).build(); ProfitBricksSoapMessageEnvelope soapEnvelope = new ProfitBricksSoapMessageEnvelope(); HttpRequest filtered = soapEnvelope.filter(request); assertEquals(filtered.getPayload().getRawContent(), expectedPayload); assertEquals(filtered.getPayload().getContentMetadata().getContentLength(), Long.valueOf(expectedPayload.getBytes().length)); } @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = ".*must contain payload message.*") public void testNullRequest() { HttpRequest request = HttpRequest.builder().method("POST").endpoint(ENDPOINT).build(); new ProfitBricksSoapMessageEnvelope().filter(request); }
### Question: MacAddresses { public static boolean isMacAddress(String in) { return MAC_ADDR_PATTERN.matcher(in).matches(); } static boolean isMacAddress(String in); }### Answer: @Test public void testIsMacAddress() { for (String addr : expectedValidAddresses) assertTrue(isMacAddress(addr)); for (String addr : expectedInvalidAddresses) assertFalse(isMacAddress(addr)); }
### Question: DeregisterLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.DeregisterPayload> { @Override protected String createPayload(LoadBalancer.Request.DeregisterPayload payload) { requestBuilder.append("<ws:deregisterServersOnLoadBalancer>"); for (String s : payload.serverIds()) requestBuilder.append(format("<serverIds>%s</serverIds>", s)); requestBuilder.append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())) .append("</ws:deregisterServersOnLoadBalancer>"); return requestBuilder.toString(); } DeregisterLoadBalancerRequestBinder(); }### Answer: @Test public void testDeregisterPayload() { DeregisterLoadBalancerRequestBinder binder = new DeregisterLoadBalancerRequestBinder(); String actual = binder.createPayload(LoadBalancer.Request.createDeregisteringPayload( "load-balancer-id", ImmutableList.of("1", "2"))); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: BackoffOnNotFoundWhenGetBucketACL extends CacheLoader<String, AccessControlList> { @Override public AccessControlList load(String bucketName) { ResourceNotFoundException last = null; for (int currentTries = 0; currentTries < maxTries; currentTries++) { try { return client.getBucketACL(bucketName); } catch (ResourceNotFoundException e) { imposeBackoffExponentialDelay(100L, 200L, 2, currentTries, maxTries); last = e; } } throw last; } @Inject BackoffOnNotFoundWhenGetBucketACL(S3Client client); @Override AccessControlList load(String bucketName); @Override String toString(); }### Answer: @Test void testMaxRetriesNotExceededReturnsValue() { AccessControlList acl = createMock(AccessControlList.class); int attempts = 5; BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new ResourceNotFoundException()).times(attempts - 1); expect(mock.getBucketACL("foo")).andReturn(acl); replay(mock); assertSame(backoff.load("foo"), acl); verify(mock); } @Test(expectedExceptions = ResourceNotFoundException.class) void testMaxRetriesExceededThrowsException() { int attempts = 5; BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new ResourceNotFoundException()).times(attempts); replay(mock); backoff.load("foo"); } @Test(expectedExceptions = UncheckedExecutionException.class) void testDoesntCatchOtherExceptions() { BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new UncheckedExecutionException(new TimeoutException())); replay(mock); backoff.load("foo"); verify(mock); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions overrideMetadataWith(Map<String, String> metadata) { checkNotNull(metadata, "metadata"); this.metadata = metadata; return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testMetaNPE() { overrideMetadataWith(null); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public String getIfModifiedSince() { return getFirstHeaderOrNull(COPY_SOURCE_IF_MODIFIED_SINCE); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test public void testNullIfModifiedSince() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfModifiedSince()); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince) { checkState(getIfMatch() == null, "ifETagMatches() is not compatible with ifModifiedSince()"); checkState(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifModifiedSince()"); replaceHeader(COPY_SOURCE_IF_MODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull(ifModifiedSince, "ifModifiedSince"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testIfModifiedSinceNPE() { ifSourceModifiedSince(null); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince) { checkState(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()"); checkState(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifUnmodifiedSince()"); replaceHeader(COPY_SOURCE_IF_UNMODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull(ifUnmodifiedSince, "ifUnmodifiedSince"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test public void testIfUnmodifiedSince() { CopyObjectOptions options = new CopyObjectOptions(); options.ifSourceUnmodifiedSince(now); isNowExpected(options); } @Test public void testIfUnmodifiedSinceStatic() { CopyObjectOptions options = ifSourceUnmodifiedSince(now); isNowExpected(options); } @Test(expectedExceptions = NullPointerException.class) public void testIfUnmodifiedSinceNPE() { ifSourceUnmodifiedSince(null); }
### Question: CreateLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.CreatePayload> { @Override protected String createPayload(LoadBalancer.Request.CreatePayload payload) { requestBuilder.append("<ws:createLoadBalancer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<loadBalancerName>%s</loadBalancerName>", payload.name())) .append(format("<loadBalancerAlgorithm>%s</loadBalancerAlgorithm>", payload.algorithm())) .append(format("<ip>%s</ip>", payload.ip())) .append(format("<lanId>%s</lanId>", payload.lanId())); for (String serverId : payload.serverIds()) requestBuilder.append(format("<serverIds>%s</serverIds>", serverId)); requestBuilder .append("</request>") .append("</ws:createLoadBalancer>"); return requestBuilder.toString(); } CreateLoadBalancerRequestBinder(); }### Answer: @Test public void testCreatePayload() { CreateLoadBalancerRequestBinder binder = new CreateLoadBalancerRequestBinder(); String actual = binder.createPayload( LoadBalancer.Request.creatingBuilder() .dataCenterId("datacenter-id") .name("load-balancer-name") .algorithm(Algorithm.ROUND_ROBIN) .ip("10.0.0.1") .lanId(2) .serverIds(ImmutableList.<String>of( "server-id-1", "server-id-2")) .build()); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public String getIfUnmodifiedSince() { return getFirstHeaderOrNull(COPY_SOURCE_IF_UNMODIFIED_SINCE); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test public void testNullIfUnmodifiedSince() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfUnmodifiedSince()); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public String getIfMatch() { return getFirstHeaderOrNull(COPY_SOURCE_IF_MATCH); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test public void testNullIfETagMatches() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfMatch()); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceETagMatches(String eTag) { checkState(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkState(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); replaceHeader(COPY_SOURCE_IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testIfETagMatchesNPE() { ifSourceETagMatches(null); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public String getIfNoneMatch() { return getFirstHeaderOrNull(COPY_SOURCE_IF_NO_MATCH); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test public void testNullIfETagDoesntMatch() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfNoneMatch()); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceETagDoesntMatch(String eTag) { checkState(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); Preconditions.checkState(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); replaceHeader(COPY_SOURCE_IF_NO_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testIfETagDoesntMatchNPE() { ifSourceETagDoesntMatch(null); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CannedAccessPolicy getAcl() { return acl; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test public void testAclDefault() { CopyObjectOptions options = new CopyObjectOptions(); assertEquals(options.getAcl(), CannedAccessPolicy.PRIVATE); }
### Question: UpdateLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.UpdatePayload> { @Override protected String createPayload(LoadBalancer.Request.UpdatePayload payload) { return requestBuilder.append("<ws:updateLoadBalancer>") .append("<request>") .append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())) .append(formatIfNotEmpty("<loadBalancerName>%s</loadBalancerName>", payload.name())) .append(formatIfNotEmpty("<loadBalancerAlgorithm>%s</loadBalancerAlgorithm>", payload.algorithm())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append("</request>") .append("</ws:updateLoadBalancer>").toString(); } UpdateLoadBalancerRequestBinder(); }### Answer: @Test public void testDeregisterPayload() { UpdateLoadBalancerRequestBinder binder = new UpdateLoadBalancerRequestBinder(); LoadBalancer.Request.UpdatePayload payload = LoadBalancer.Request.updatingBuilder() .id("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee") .name("load-balancer-name") .algorithm(LoadBalancer.Algorithm.ROUND_ROBIN) .ip("10.0.0.2") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: RegisterLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.RegisterPayload> { @Override protected String createPayload(LoadBalancer.Request.RegisterPayload payload) { requestBuilder .append("<ws:registerServersOnLoadBalancer>") .append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())); for (String s : payload.serverIds()) requestBuilder.append(format("<serverIds>%s</serverIds>", s)); requestBuilder.append("</ws:registerServersOnLoadBalancer>"); return requestBuilder.toString().replaceAll("\\s+", ""); } RegisterLoadBalancerRequestBinder(); }### Answer: @Test public void testRegisterPayload() { RegisterLoadBalancerRequestBinder binder = new RegisterLoadBalancerRequestBinder(); String actual = binder.createPayload(LoadBalancer.Request.createRegisteringPaylod( "load-balancer-id", ImmutableList.of("1", "2"))); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: AddRomDriveToServerRequestBinder extends BaseProfitBricksRequestBinder<Drive.Request.AddRomDriveToServerPayload> { @Override protected String createPayload(Drive.Request.AddRomDriveToServerPayload payload) { requestBuilder.append("<ws:addRomDriveToServer>") .append("<request>") .append(format("<imageId>%s</imageId>", payload.imageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:addRomDriveToServer>"); return requestBuilder.toString(); } AddRomDriveToServerRequestBinder(); }### Answer: @Test public void testAddRomDriveToServerPayload() { AddRomDriveToServerRequestBinder binder = new AddRomDriveToServerRequestBinder(); Drive.Request.AddRomDriveToServerPayload payload = Drive.Request.AddRomDriveToServerPayload.builder() .serverId("server-id") .imageId("image-id") .deviceNumber("device-number") .build(); String actual = binder.createPayload(payload); assertEquals(actual, expectedPayload); }
### Question: ConnectStorageToServerRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.ConnectPayload> { @Override protected String createPayload(Storage.Request.ConnectPayload payload) { requestBuilder.append("<ws:connectStorageToServer>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<busType>%s</busType>", payload.busType())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:connectStorageToServer>"); return requestBuilder.toString(); } ConnectStorageToServerRequestBinder(); }### Answer: @Test public void testCreatePayload() { ConnectStorageToServerRequestBinder binder = new ConnectStorageToServerRequestBinder(); Storage.Request.ConnectPayload payload = Storage.Request.connectingBuilder() .serverId("qwertyui-qwer-qwer-qwer-qwertyyuiiop") .storageId("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh") .busType(Storage.BusType.VIRTIO) .deviceNumber(2) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: BindAsHostPrefixIfConfigured implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { String payloadAsString = payload.toString(); if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) { request = bindAsHostPrefix.bindToRequest(request, payload); String host = request.getEndpoint().getHost(); if (request.getEndpoint().getPort() != -1) { host += ":" + request.getEndpoint().getPort(); } return (R) request.toBuilder().replaceHeader(HttpHeaders.HOST, host).build(); } else { StringBuilder path = new StringBuilder(request.getEndpoint().getRawPath()); if (servicePath.equals("/")) { if (path.toString().equals("/")) path.append(payloadAsString); else path.insert(0, "/" + payloadAsString); } else { int indexToInsert = 0; indexToInsert = path.indexOf(servicePath); indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert += servicePath.length(); path.insert(indexToInsert, "/" + payloadAsString); } return (R) request.toBuilder().replacePath(path.toString()).build(); } } @Inject BindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix, @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, @Named(PROPERTY_S3_SERVICE_PATH) String servicePath); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object payload); }### Answer: @Test(dataProvider = "objects") public void testObject(String key) throws InterruptedException { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: BindAsHostPrefixIfConfigured binder = injector.getInstance(BindAsHostPrefixIfConfigured.class); request = binder.bindToRequest(request, "bucket"); assertEquals(request.getRequestLine(), "GET http: }
### Question: FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>, InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } @Inject FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client); @Override Boolean createOrPropagate(Throwable t); @Override FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists setContext(@Nullable HttpRequest request); }### Answer: @Test(expectedExceptions = IllegalStateException.class) void testIllegalStateIsNotOk() throws Exception { S3Client client = createMock(S3Client.class); replay(client); Exception e = new IllegalStateException(); new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).createOrPropagate(e); } @Test(expectedExceptions = AWSResponseException.class) void testBlahIsNotOk() throws Exception { S3Client client = createMock(S3Client.class); replay(client); Exception e = getErrorWithCode("blah"); new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).createOrPropagate(e); }
### Question: ETagFromHttpResponseViaRegex implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String value = null; String content = returnStringIf200.apply(response); if (content != null) { Matcher matcher = PATTERN.matcher(content); if (matcher.find()) { value = matcher.group(1); if (value.indexOf(ESCAPED_QUOTE) != -1) { value = value.replace(ESCAPED_QUOTE, "\""); } } } return value; } @Inject ETagFromHttpResponseViaRegex(ReturnStringIf2xx returnStringIf200); @Override String apply(HttpResponse response); }### Answer: @Test public void test() { HttpResponse response = HttpResponse.builder().statusCode(200).payload( Payloads.newInputStreamPayload(getClass().getResourceAsStream("/complete-multipart-upload.xml"))) .build(); ETagFromHttpResponseViaRegex parser = new ETagFromHttpResponseViaRegex(new ReturnStringIf2xx()); assertEquals(parser.apply(response), "\"3858f62230ac3c915f300c664312c11f-9\""); }
### Question: CreateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.CreatePayload> { @Override protected String createPayload(Nic.Request.CreatePayload payload) { requestBuilder.append("<ws:createNic>") .append("<request>") .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:createNic>"); return requestBuilder.toString(); } CreateNicRequestBinder(); }### Answer: @Test public void testCreatePayload() { CreateNicRequestBinder binder = new CreateNicRequestBinder(); Nic.Request.CreatePayload payload = Nic.Request.creatingBuilder() .ip("192.168.0.1") .name("nic-name") .dhcpActive(true) .serverId("server-id") .lanId(1) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: DefaultEndpointThenInvalidateRegion implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { try { return delegate.apply(from); } finally { bucketToRegionCache.invalidate(from.toString()); } } @Inject DefaultEndpointThenInvalidateRegion(AssignCorrectHostnameForBucket delegate, @Bucket LoadingCache<String, Optional<String>> bucketToRegionCache); @Override URI apply(@Nullable Object from); }### Answer: @SuppressWarnings("unchecked") @Test public void testInvalidate() throws Exception { LoadingCache<String, Optional<String>> bucketToRegionCache = createMock(LoadingCache.class); bucketToRegionCache.invalidate("mybucket"); replay(bucketToRegionCache); AssignCorrectHostnameForBucket delegate = new AssignCorrectHostnameForBucket(REGION_TO_ENDPOINT, Functions.forMap(ImmutableMap.of("mybucket", Optional.of("us-west-1")))); new DefaultEndpointThenInvalidateRegion(delegate, bucketToRegionCache).apply("mybucket"); verify(bucketToRegionCache); }
### Question: RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag, @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag, @org.jclouds.location.Provider Supplier<Credentials> creds, @TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils, DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); }### Answer: @Test void testAppendBucketNameHostHeader() throws SecurityException, NoSuchMethodException { GeneratedHttpRequest request = processor.createRequest( method(S3Client.class, "getBucketLocation", String.class), ImmutableList.<Object>of("bucket")); StringBuilder builder = new StringBuilder(); ((RequestAuthorizeSignatureV2) filter).appendBucketName(request, builder); assertEquals(builder.toString(), ""); } @Test void testAppendBucketNameHostHeaderService() throws SecurityException, NoSuchMethodException { HttpRequest request = listOwnedBuckets(); StringBuilder builder = new StringBuilder(); ((RequestAuthorizeSignatureV2) filter).appendBucketName(request, builder); assertEquals(builder.toString(), ""); }
### Question: RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendUriPath(HttpRequest request, StringBuilder toSign) { toSign.append(request.getEndpoint().getRawPath()); if (request.getEndpoint().getQuery() != null) { Multimap<String, String> params = queryParser().apply(request.getEndpoint().getQuery()); char separator = '?'; for (String paramName : Ordering.natural().sortedCopy(params.keySet())) { if (!SIGNED_PARAMETERS.contains(paramName)) { continue; } toSign.append(separator).append(paramName); String paramValue = get(params.get(paramName), 0); if (paramValue != null) { toSign.append("=").append(paramValue); } separator = '&'; } } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag, @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag, @org.jclouds.location.Provider Supplier<Credentials> creds, @TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils, DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); }### Answer: @Test void testAclQueryString() throws SecurityException, NoSuchMethodException { HttpRequest request = putBucketAcl(); StringBuilder builder = new StringBuilder(); ((RequestAuthorizeSignatureV2) filter).appendUriPath(request, builder); assertEquals(builder.toString(), "/" + bucketName + "?acl"); }
### Question: AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } static String parseRegionName(final String host, final String serviceHint); static String parseServiceName(URI endpoint); }### Answer: @Test public void testParseRegion() { Assert.assertEquals( AwsHostNameUtils.parseRegionName("test.s3.cn-north-1.amazonaws.com.cn", "s3"), "cn-north-1" ); } @Test public void testParseDefaultRegion() { Assert.assertEquals( AwsHostNameUtils.parseRegionName("s3.amazonaws.com", "s3"), "us-east-1" ); }
### Question: AwsHostNameUtils { public static String parseServiceName(URI endpoint) { String host = endpoint.getHost(); if (!host.endsWith(".amazonaws.com") && !host.endsWith(".amazonaws.com.cn")) { return "s3"; } String serviceAndRegion = host.substring(0, host.indexOf(".amazonaws.com")); if (serviceAndRegion.endsWith(".s3") || S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) { return "s3"; } char separator = '.'; if (serviceAndRegion.indexOf(separator) == -1) { return serviceAndRegion; } return serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator)); } static String parseRegionName(final String host, final String serviceHint); static String parseServiceName(URI endpoint); }### Answer: @Test public void testParseService() { Assert.assertEquals( AwsHostNameUtils.parseServiceName(URI.create("https: "s3" ); Assert.assertEquals( AwsHostNameUtils.parseServiceName(URI.create("https: "s3" ); }
### Question: SetInternetAccessBinder extends BaseProfitBricksRequestBinder<Nic.Request.SetInternetAccessPayload> { @Override protected String createPayload(Nic.Request.SetInternetAccessPayload payload) { requestBuilder.append("<ws:setInternetAccess>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append(format("<internetAccess>%s</internetAccess>", payload.internetAccess())) .append("</ws:setInternetAccess>"); return requestBuilder.toString(); } SetInternetAccessBinder(); }### Answer: @Test public void testCreatePayload() { SetInternetAccessBinder binder = new SetInternetAccessBinder(); Nic.Request.SetInternetAccessPayload payload = Nic.Request.setInternetAccessBuilder() .dataCenterId("datacenter-id") .internetAccess(true) .lanId(1) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: InvalidateSessionAndRetryOn401AndLogoutOnClose extends BackoffLimitedRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { try { switch (response.getStatusCode()) { case 401: authenticationResponseCache.invalidateAll(); return super.shouldRetryRequest(command, response); } return false; } finally { releasePayload(response); } } @Inject protected InvalidateSessionAndRetryOn401AndLogoutOnClose(LoadingCache<Credentials, LoginResponse> authenticationResponseCache, SessionApi sessionClient); @Override boolean shouldRetryRequest(HttpCommand command, HttpResponse response); @PreDestroy void logoutOnClose(); }### Answer: @SuppressWarnings("unchecked") @Test public void test401ShouldRetryAndFailAfterFiveAttempts() { HttpCommand command = createMock(HttpCommand.class); SessionApi sessionClient = createMock(SessionApi.class); LoadingCache<Credentials, LoginResponse> cache = createMock(LoadingCache.class); cache.invalidateAll(); expectLastCall().anyTimes(); final AtomicInteger counter = new AtomicInteger(); expect(command.incrementFailureCount()).andAnswer(new IAnswer<Integer>() { @Override public Integer answer() throws Throwable { return counter.incrementAndGet(); } }).anyTimes(); expect(command.isReplayable()).andReturn(true).anyTimes(); expect(command.getFailureCount()).andAnswer(new IAnswer<Integer>() { @Override public Integer answer() throws Throwable { return counter.get(); } }).anyTimes(); replay(cache, command); HttpResponse response = HttpResponse.builder().payload( Payloads.newStringPayload("Not relevant")).statusCode(401).build(); InvalidateSessionAndRetryOn401AndLogoutOnClose retry = new InvalidateSessionAndRetryOn401AndLogoutOnClose(cache, sessionClient); for (int i = 0; i < 5; i++) { assertTrue(retry.shouldRetryRequest(command, response)); } assertFalse(retry.shouldRetryRequest(command, response)); verify(cache, command); }
### Question: UpdateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.UpdatePayload> { @Override protected String createPayload(Nic.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateNic>") .append("<request>") .append(format("<nicId>%s</nicId>", payload.id())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:updateNic>"); return requestBuilder.toString(); } UpdateNicRequestBinder(); }### Answer: @Test public void testCreatePayload() { UpdateNicRequestBinder binder = new UpdateNicRequestBinder(); Nic.Request.UpdatePayload payload = Nic.Request.updatingBuilder() .id("nic-id") .ip("192.168.0.1") .name("nic-name") .dhcpActive(true) .lanId(1) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: WindowsLoginCredentialsFromEncryptedData implements Function<EncryptedPasswordAndPrivateKey, LoginCredentials> { @Override public LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey) { if (dataAndKey == null) return null; try { KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey()); KeyFactory kf = crypto.rsaKeyFactory(); PrivateKey privKey = kf.generatePrivate(keySpec); Cipher cipher = crypto.cipher("RSA"); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] cipherText = base64().decode(whitespace.matcher(dataAndKey.getEncryptedPassword()).replaceAll("")); byte[] plainText = cipher.doFinal(cipherText); String password = new String(plainText, UTF_8); return LoginCredentials.builder() .user("Administrator") .password(password) .noPrivateKey() .build(); } catch (Exception e) { throw Throwables.propagate(e); } } @Inject WindowsLoginCredentialsFromEncryptedData(Crypto crypto); @Override LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey); }### Answer: @Test public void testApply() throws Exception { WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto()); LoginCredentials credentials = f.apply(new EncryptedPasswordAndPrivateKey(ENCRYPTED_PASSWORD, PRIVATE_KEY)); assertEquals(credentials.getUser(), "Administrator"); assertEquals(credentials.getOptionalPassword().get(), "u4.y9mb;nR."); assertFalse(credentials.getOptionalPrivateKey().isPresent()); } @Test public void testApply() throws Exception { WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto()); LoginCredentials credentials = f.apply(new EncryptedPasswordAndPrivateKey(ENCRYPTED_PASSWORD, PRIVATE_KEY)); assertEquals(credentials.getUser(), "Administrator"); assertEquals(credentials.getPassword(), "u4.y9mb;nR."); assertFalse(credentials.getOptionalPrivateKey().isPresent()); }
### Question: VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } @Inject VirtualMachineDestroyed(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); }### Answer: @Test public void testIsDestroyed() { VirtualMachine virtualMachine = VirtualMachine.builder(). id("229").state(VirtualMachine.State.DESTROYED).build(); expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine); replay(client, virtualMachineClient); assertTrue(new VirtualMachineDestroyed(client).apply(virtualMachine)); verify(client, virtualMachineClient); } @Test public void testStillRunning() { VirtualMachine virtualMachine = VirtualMachine.builder(). id("229").state(VirtualMachine.State.RUNNING).build(); expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine); replay(client, virtualMachineClient); assertFalse(new VirtualMachineDestroyed(client).apply(virtualMachine)); verify(client, virtualMachineClient); }
### Question: VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } @Inject VirtualMachineExpunged(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); }### Answer: @Test public void testWaitForVirtualMachineToBeExpunged() { VirtualMachine virtualMachine = VirtualMachine.builder().id("229").build(); expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(null); replay(client, virtualMachineClient); assertTrue(new VirtualMachineExpunged(client).apply(virtualMachine)); verify(client, virtualMachineClient); } @Test public void testNoRemovedYet() { VirtualMachine virtualMachine = VirtualMachine.builder().id("229").build(); expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine); replay(client, virtualMachineClient); assertFalse(new VirtualMachineExpunged(client).apply(virtualMachine)); verify(client, virtualMachineClient); }
### Question: JobComplete implements Predicate<String> { @Inject public JobComplete(CloudStackApi client) { this.client = client; } @Inject JobComplete(CloudStackApi client); boolean apply(String jobId); }### Answer: @Test public void testJobComplete() { AsyncJob<?> job = AsyncJob.builder().id("100") .status(Status.SUCCEEDED).resultCode(ResultCode.SUCCESS).build(); expect((Object) asyncJobClient.getAsyncJob(job.getId())).andReturn(job); replay(client, asyncJobClient); assertTrue(new JobComplete(client).apply(job.getId())); verify(client, asyncJobClient); }
### Question: JobComplete implements Predicate<String> { public boolean apply(String jobId) { logger.trace(">> looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) { return false; } logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); if (job.hasFailed()) { throw new AsyncJobException(String.format("job %s failed with exception %s", job.toString(), job.getError().toString())); } return job.hasSucceed(); } @Inject JobComplete(CloudStackApi client); boolean apply(String jobId); }### Answer: @Test public void testFailedJobComplete() { AsyncJob<?> job = AsyncJob.builder().id("100") .status(Status.FAILED).resultCode(ResultCode.FAIL) .error(AsyncJobError.builder().errorCode(ErrorCode.INTERNAL_ERROR).errorText("Dummy test error").build()).build(); expect((Object) asyncJobClient.getAsyncJob(job.getId())).andReturn(job); replay(client, asyncJobClient); try { new JobComplete(client).apply(job.getId()); fail("No exception thrown"); } catch (AsyncJobException e) { assertTrue(e.toString().contains("Dummy test error")); } verify(client, asyncJobClient); }
### Question: OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } @Inject OSCategoryIn(CloudStackApi client); OSCategoryIn(Supplier<Map<String, String>> categoriesSupplier, Supplier<Set<OSType>> osTypesSupplier); @Override Predicate<Template> apply(final Set<String> acceptableCategories); }### Answer: @Test public void testTemplateInAcceptableCategory() { assertTrue(new OSCategoryIn(client).apply(acceptableCategories).apply( Template.builder().id("1").OSTypeId("10").build() )); verify(client, guestOSClient); } @Test public void testTemplateNotInAcceptableCategory() { assertFalse(new OSCategoryIn(client).apply(acceptableCategories).apply( Template.builder().id("2").OSTypeId("30").build() )); verify(client, guestOSClient); }
### Question: CloudStackSecurityGroupToSecurityGroup implements Function<org.jclouds.cloudstack.domain.SecurityGroup, SecurityGroup> { @Override public SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); builder.id(group.getId()); builder.providerId(group.getId()); builder.name(group.getName()); builder.ownerId(group.getAccount()); builder.ipPermissions(transform(group.getIngressRules(), ruleToPermission)); return builder.build(); } @Inject CloudStackSecurityGroupToSecurityGroup(Function<IngressRule, IpPermission> ruleToPermission); @Override SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group); }### Answer: @Test public void testApply() { IngressRule ruleToConvert = IngressRule.builder() .id("some-id") .account("some-account") .securityGroupName("some-group-name") .protocol(IpProtocol.TCP.toString()) .startPort(10) .endPort(20) .CIDR("0.0.0.0/0") .build(); org.jclouds.cloudstack.domain.SecurityGroup origGroup = org.jclouds.cloudstack.domain.SecurityGroup.builder() .id("some-id") .name("some-group") .description("some-description") .account("some-account") .ingressRules(ImmutableSet.of(ruleToConvert)) .build(); CloudStackSecurityGroupToSecurityGroup parser = createGroupParser(); SecurityGroup group = parser.apply(origGroup); assertEquals(group.getId(), origGroup.getId()); assertEquals(group.getProviderId(), origGroup.getId()); assertEquals(group.getName(), origGroup.getName()); assertEquals(group.getOwnerId(), origGroup.getAccount()); assertEquals(group.getIpPermissions(), ImmutableSet.copyOf(transform(origGroup.getIngressRules(), ruleConverter))); }
### Question: IngressRuleToIpPermission implements Function<IngressRule, IpPermission> { @Override public IpPermission apply(IngressRule rule) { IpPermission.Builder builder = IpPermission.builder(); builder.ipProtocol(IpProtocol.fromValue(rule.getProtocol())); builder.fromPort(rule.getStartPort()); builder.toPort(rule.getEndPort()); if (rule.getCIDR() != null) { builder.cidrBlock(rule.getCIDR()); } if (rule.getSecurityGroupName() != null && rule.getAccount() != null) { builder.tenantIdGroupNamePair(rule.getAccount(), rule.getSecurityGroupName()); } return builder.build(); } IngressRuleToIpPermission(); @Override IpPermission apply(IngressRule rule); }### Answer: @Test public void testApplyWithTCP() { IngressRule ruleToConvert = IngressRule.builder() .id("some-id") .account("some-account") .securityGroupName("some-group-name") .protocol(IpProtocol.TCP.toString()) .startPort(10) .endPort(20) .CIDR("0.0.0.0/0") .build(); IngressRuleToIpPermission converter = new IngressRuleToIpPermission(); IpPermission convertedPerm = converter.apply(ruleToConvert); assertEquals(convertedPerm.getIpProtocol(), IpProtocol.fromValue(ruleToConvert.getProtocol())); assertEquals(convertedPerm.getFromPort(), ruleToConvert.getStartPort()); assertEquals(convertedPerm.getToPort(), ruleToConvert.getEndPort()); assertEquals(convertedPerm.getCidrBlocks(), ImmutableSet.of("0.0.0.0/0")); assertEquals(convertedPerm.getTenantIdGroupNamePairs().size(), 1); assertEquals(convertedPerm.getGroupIds().size(), 0); }
### Question: CreateUniqueKeyPair extends CacheLoader<String, SshKeyPair> { @Override public SshKeyPair load(String input) { SshKeyPair keyPair = null; while (keyPair == null) { try { keyPair = client.getSSHKeyPairApi().createSSHKeyPair(input); logger.debug(">> creating SSH key pair with name %s", input); } catch (IllegalStateException e) { logger.error(e, "<< error creating SSH key pair with name %s: ", Throwables.getRootCause(e).getMessage()); throw Throwables.propagate(e); } } logger.debug("<< created keyPair(%s)", keyPair.getName()); return keyPair; } @Inject CreateUniqueKeyPair(CloudStackApi client); @Override SshKeyPair load(String input); }### Answer: @Test public void testLoad() throws UnknownHostException { final CloudStackApi client = createMock(CloudStackApi.class); SSHKeyPairApi keyClient = createMock(SSHKeyPairApi.class); SshKeyPair pair = createMock(SshKeyPair.class); expect(client.getSSHKeyPairApi()).andReturn(keyClient); expect(keyClient.createSSHKeyPair("group-1")).andReturn(pair); replay(client, keyClient); CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(CloudStackApi.class).toInstance(client); } }).getInstance(CreateUniqueKeyPair.class); assertEquals(parser.load("group-1"), pair); verify(client, keyClient); }
### Question: CreateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.CreatePayload> { @Override protected String createPayload(Snapshot.Request.CreatePayload payload) { requestBuilder.append("<ws:createSnapshot>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(formatIfNotEmpty("<description>%s</description>", payload.description())) .append(formatIfNotEmpty("<snapshotName>%s</snapshotName>", payload.name())) .append("</request>") .append("</ws:createSnapshot>"); return requestBuilder.toString(); } protected CreateSnapshotRequestBinder(); }### Answer: @Test public void testCreatePayload() { CreateSnapshotRequestBinder binder = new CreateSnapshotRequestBinder(); Snapshot.Request.CreatePayload payload = Snapshot.Request.creatingBuilder() .storageId("123-1233-1324") .name("snapshot-name") .description("describing-the-snapshot") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: NodesParsedFromSupplier implements Supplier<LoadingCache<String, Node>> { @Override public LoadingCache<String, Node> get() { LoadingCache<String, Node> nodes = parser.apply(supplier); checkState(nodes != null && nodes.size() > 0, "no nodes parsed from supplier: %s", supplier); return nodes; } @Inject NodesParsedFromSupplier(@Provider ByteSource supplier, Function<ByteSource, LoadingCache<String, Node>> parser); @Override LoadingCache<String, Node> get(); }### Answer: @Test(expectedExceptions = IllegalStateException.class) public void testMustParseSomething() throws Exception { new NodesParsedFromSupplier(ByteSource.wrap("nodes:\n".getBytes(Charsets.UTF_8)), new NodesFromYamlStream()).get(); }
### Question: RollbackSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.RollbackPayload> { @Override protected String createPayload(Snapshot.Request.RollbackPayload payload) { requestBuilder.append("<ws:rollbackSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.snapshotId())) .append(format("<storageId>%s</storageId>", payload.storageId())) .append("</request>") .append("</ws:rollbackSnapshot>"); return requestBuilder.toString(); } protected RollbackSnapshotRequestBinder(); }### Answer: @Test public void testRollbackPayload() { RollbackSnapshotRequestBinder binder = new RollbackSnapshotRequestBinder(); Snapshot.Request.RollbackPayload payload = Snapshot.Request.createRollbackPayload("snapshot-id", "storage-id"); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: CreateDataCenterRequestBinder extends BaseProfitBricksRequestBinder<DataCenter.Request.CreatePayload> { @Override protected String createPayload(DataCenter.Request.CreatePayload payload) { requestBuilder.append("<ws:createDataCenter>") .append("<request>") .append(format("<dataCenterName>%s</dataCenterName>", payload.name())) .append(format("<location>%s</location>", payload.location().getId())) .append("</request>") .append("</ws:createDataCenter>"); return requestBuilder.toString(); } CreateDataCenterRequestBinder(); }### Answer: @Test public void testCreatePayload() { CreateDataCenterRequestBinder binder = new CreateDataCenterRequestBinder(); DataCenter.Request.CreatePayload payload = DataCenter.Request.creatingPayload("JClouds-DC", Location.DE_FKB); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: UpdateDataCenterRequestBinder extends BaseProfitBricksRequestBinder<DataCenter.Request.UpdatePayload> { @Override protected String createPayload(DataCenter.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateDataCenter>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.id())) .append(format("<dataCenterName>%s</dataCenterName>", payload.name())) .append("</request>") .append("</ws:updateDataCenter>"); return requestBuilder.toString(); } UpdateDataCenterRequestBinder(); }### Answer: @Test public void testCreatePayload() { UpdateDataCenterRequestBinder binder = new UpdateDataCenterRequestBinder(); DataCenter.Request.UpdatePayload payload = DataCenter.Request.updatingPayload("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Apache-DC"); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: ProvisioningManager implements Closeable { public Object provision(ProvisioningJob job) { if (terminated.get()) { logger.warn("Job(%s) submitted but the provisioning manager is already closed", job); return null; } logger.debug("Job(%s) submitted to group '%s'", job, job.getGroup()); ListeningExecutorService workerGroup = getWorkerGroup(job.getGroup()); return getUnchecked(workerGroup.submit(job)); } Object provision(ProvisioningJob job); @Override void close(); }### Answer: @Test public void testProvision() throws IOException { ProvisioningManager manager = new ProvisioningManager(); AtomicInteger completedJobs = new AtomicInteger(0); try { for (int i = 0; i < 5; i++) { manager.provision(new MockJob(200, "slow", completedJobs)); manager.provision(new MockJob(0, "fast", completedJobs)); manager.provision(new MockJob(100, "normal", completedJobs)); } } finally { manager.close(); } assertEquals(completedJobs.get(), 15); } @Test public void testProvisionInterrupted() { ProvisioningManager manager = new ProvisioningManager(); AtomicInteger completedJobs = new AtomicInteger(0); manager.provision(new ShutdownExecutorJob(manager, completedJobs)); manager.provision(new MockJob(0, "rejected", completedJobs)); assertEquals(completedJobs.get(), 1); }
### Question: StorageToVolume implements Function<Storage, Volume> { @Override public Volume apply(Storage storage) { checkNotNull(storage, "Null storage"); String device = ""; if (storage.deviceNumber() != null) device = storage.deviceNumber().toString(); return new VolumeBuilder() .id(storage.id()) .size(storage.size()) .bootDevice(storage.bootDevice()) .device(device) .durable(true) .type(Volume.Type.LOCAL) .build(); } @Override Volume apply(Storage storage); }### Answer: @Test public void testStorageToVolume() { Storage storage = Storage.builder() .id("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh") .size(40) .name("hdd-1") .busType(Storage.BusType.VIRTIO) .bootDevice(true) .deviceNumber(1) .build(); Volume actual = fnVolume.apply(storage); Volume expected = new VolumeBuilder() .id(storage.id()) .size(40f) .bootDevice(true) .device("1") .type(Volume.Type.LOCAL) .durable(true) .build(); assertEquals(actual, expected); }
### Question: CreateVolumeOptions extends BaseEC2RequestOptions { public CreateVolumeOptions volumeType(String volumeType) { formParameters.put("VolumeType", checkNotNull(volumeType, "volumeType")); return this; } CreateVolumeOptions withSize(int size); int getSize(); CreateVolumeOptions fromSnapshotId(String snapshotId); String getSnapshotId(); CreateVolumeOptions volumeType(String volumeType); String getVolumeType(); CreateVolumeOptions withIops(Integer iops); Integer getIops(); CreateVolumeOptions isEncrypted(boolean encrypted); boolean getEncrypted(); }### Answer: @Test public void testVolumeType() { CreateVolumeOptions options = new CreateVolumeOptions(); options.volumeType("test"); assertEquals(options.buildFormParameters().get("VolumeType"), ImmutableList.of("test")); } @Test public void testVolumeTypeStatic() { CreateVolumeOptions options = volumeType("test"); assertEquals(options.buildFormParameters().get("VolumeType"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testVolmeTypeNPE() { volumeType(null); }
### Question: CreateVolumeOptions extends BaseEC2RequestOptions { public CreateVolumeOptions fromSnapshotId(String snapshotId) { formParameters.put("SnapshotId", checkNotNull(snapshotId, "snapshotId")); return this; } CreateVolumeOptions withSize(int size); int getSize(); CreateVolumeOptions fromSnapshotId(String snapshotId); String getSnapshotId(); CreateVolumeOptions volumeType(String volumeType); String getVolumeType(); CreateVolumeOptions withIops(Integer iops); Integer getIops(); CreateVolumeOptions isEncrypted(boolean encrypted); boolean getEncrypted(); }### Answer: @Test public void testFromSnapshotId() { CreateVolumeOptions options = new CreateVolumeOptions(); options.fromSnapshotId("test"); assertEquals(options.buildFormParameters().get("SnapshotId"), ImmutableList.of("test")); } @Test public void testWithSnapshotIdStatic() { CreateVolumeOptions options = fromSnapshotId("test"); assertEquals(options.buildFormParameters().get("SnapshotId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testFromSnapshotIdNPE() { fromSnapshotId(null); }
### Question: CreateVolumeOptions extends BaseEC2RequestOptions { public CreateVolumeOptions withIops(Integer iops) { formParameters.put("Iops", checkNotNull(iops, "iops").toString()); return this; } CreateVolumeOptions withSize(int size); int getSize(); CreateVolumeOptions fromSnapshotId(String snapshotId); String getSnapshotId(); CreateVolumeOptions volumeType(String volumeType); String getVolumeType(); CreateVolumeOptions withIops(Integer iops); Integer getIops(); CreateVolumeOptions isEncrypted(boolean encrypted); boolean getEncrypted(); }### Answer: @Test public void testWithIops() { CreateVolumeOptions options = new CreateVolumeOptions(); options.withIops(5); assertEquals(options.buildFormParameters().get("Iops"), ImmutableList.of("5")); } @Test public void testWithIopsStatic() { CreateVolumeOptions options = withIops(5); assertEquals(options.buildFormParameters().get("Iops"), ImmutableList.of("5")); }
### Question: CreateVolumeOptions extends BaseEC2RequestOptions { public CreateVolumeOptions withSize(int size) { formParameters.put("Size", Integer.toString(size)); return this; } CreateVolumeOptions withSize(int size); int getSize(); CreateVolumeOptions fromSnapshotId(String snapshotId); String getSnapshotId(); CreateVolumeOptions volumeType(String volumeType); String getVolumeType(); CreateVolumeOptions withIops(Integer iops); Integer getIops(); CreateVolumeOptions isEncrypted(boolean encrypted); boolean getEncrypted(); }### Answer: @Test public void testWithSize() { CreateVolumeOptions options = new CreateVolumeOptions(); options.withSize(5); assertEquals(options.buildFormParameters().get("Size"), ImmutableList.of("5")); } @Test public void testWithSizeStatic() { CreateVolumeOptions options = withSize(5); assertEquals(options.buildFormParameters().get("Size"), ImmutableList.of("5")); }
### Question: CreateVolumeOptions extends BaseEC2RequestOptions { public CreateVolumeOptions isEncrypted(boolean encrypted) { if (encrypted) formParameters.put("Encrypted", "true"); return this; } CreateVolumeOptions withSize(int size); int getSize(); CreateVolumeOptions fromSnapshotId(String snapshotId); String getSnapshotId(); CreateVolumeOptions volumeType(String volumeType); String getVolumeType(); CreateVolumeOptions withIops(Integer iops); Integer getIops(); CreateVolumeOptions isEncrypted(boolean encrypted); boolean getEncrypted(); }### Answer: @Test public void testIsEncrypted() { CreateVolumeOptions options = new CreateVolumeOptions(); options.isEncrypted(true); assertEquals(options.buildFormParameters().get("Encrypted"), ImmutableList.of("true")); } @Test public void testIsEncryptedStatic() { CreateVolumeOptions options = isEncrypted(true); assertEquals(options.buildFormParameters().get("Encrypted"), ImmutableList.of("true")); }
### Question: RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withKeyName(String keyName) { formParameters.put("KeyName", checkNotNull(keyName, "keyName")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer: @Test public void testWithKeyName() { RunInstancesOptions options = new RunInstancesOptions(); options.withKeyName("test"); assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of("test")); } @Test public void testWithKeyNameStatic() { RunInstancesOptions options = withKeyName("test"); assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testWithKeyNameNPE() { withKeyName(null); }
### Question: RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withSecurityGroup(String securityGroup) { return withSecurityGroups(securityGroup); } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer: @Test public void testWithSecurityGroup() { RunInstancesOptions options = new RunInstancesOptions(); options.withSecurityGroup("test"); assertEquals(options.buildFormParameters().get("SecurityGroup.1"), ImmutableList.of("test")); } @Test public void testWithSecurityGroupStatic() { RunInstancesOptions options = withSecurityGroup("test"); assertEquals(options.buildFormParameters().get("SecurityGroup.1"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testWithSecurityGroupNPE() { withSecurityGroup(null); }
### Question: RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withUserData(byte[] unencodedData) { int length = checkNotNull(unencodedData, "unencodedData").length; checkArgument(length > 0, "userData cannot be empty"); checkArgument(length <= 16 * 1024, "userData cannot be larger than 16kb"); formParameters.put("UserData", base64().encode(unencodedData)); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer: @Test public void testWithUserData() { RunInstancesOptions options = new RunInstancesOptions(); options.withUserData("test".getBytes()); assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); } @Test public void testWithUserDataStatic() { RunInstancesOptions options = withUserData("test".getBytes()); assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); } @Test(expectedExceptions = NullPointerException.class) public void testWithUserDataNPE() { withUserData(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testWithUserDataEmpty() { withUserData("".getBytes()); }
### Question: RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions asType(String type) { formParameters.put("InstanceType", checkNotNull(type, "type")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer: @Test public void testWithInstanceType() { RunInstancesOptions options = new RunInstancesOptions(); options.asType(InstanceType.C1_XLARGE); assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); } @Test public void testWithInstanceTypeStatic() { RunInstancesOptions options = asType(InstanceType.C1_XLARGE); assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); } @Test(expectedExceptions = NullPointerException.class) public void testWithInstanceTypeNPE() { asType(null); }
### Question: RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withKernelId(String kernelId) { formParameters.put("KernelId", checkNotNull(kernelId, "kernelId")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer: @Test public void testWithKernelId() { RunInstancesOptions options = new RunInstancesOptions(); options.withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test public void testWithKernelIdStatic() { RunInstancesOptions options = withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testWithKernelIdNPE() { withKernelId(null); }
### Question: RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withRamdisk(String ramDiskId) { formParameters.put("RamdiskId", checkNotNull(ramDiskId, "ramDiskId")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer: @Test public void testWithRamdisk() { RunInstancesOptions options = new RunInstancesOptions(); options.withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); } @Test public void testWithRamdiskStatic() { RunInstancesOptions options = withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testWithRamdiskNPE() { withRamdisk(null); }
### Question: DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds) { this.sshKeyIds = ImmutableSet.copyOf(checkNotNull(sshKeyIds, "sshKeyIds cannot be null")); return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer: @Test public void testSShKeyIds() { TemplateOptions options = new DigitalOcean2TemplateOptions().sshKeyIds(ImmutableSet.of(1, 2, 3)); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getSshKeyIds(), ImmutableSet.of(1, 2, 3)); }
### Question: RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withClientToken(String clientToken) { formParameters.put("ClientToken", checkNotNull(clientToken, "clientToken")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer: @Test public void testWithClientToken() { RunInstancesOptions options = withClientToken("some-token"); assertEquals(options.buildFormParameters().get("ClientToken"), ImmutableList.of("some-token")); } @Test(expectedExceptions = NullPointerException.class) public void testWithClientTokenNPE() { withClientToken(null); }
### Question: DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking) { this.privateNetworking = privateNetworking; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer: @Test public void testPrivateNetworking() { TemplateOptions options = new DigitalOcean2TemplateOptions().privateNetworking(true); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getPrivateNetworking(), true); }
### Question: Car { private Car() { if (servoCommand == null) { Environment env = Config.getEnvironment(); String servo_CommandConfig="servoblaster"; try { servo_CommandConfig = env.getString(Config.SERVO_COMMAND); } catch (Exception e) { ErrorHandler.getInstance().handle(e); } switch (servo_CommandConfig) { case "adafruit": try { servoCommand=new AdaFruit(); LOG.info("using AdaFruit ServoCommand handling"); } catch (Exception e) { ErrorHandler.getInstance().handle(e); } break; default: servoCommand = new ServoBlaster(); } } engine = new Engine(this, new EngineMap(servoCommand)); steering = new Steering(this, new SteeringMap(servoCommand)); led = new Led(new LedMap(servoCommand)); } private Car(); void configure(Engine engine, Steering steering, Led led); void setPowerOn(); void setPowerOff(); boolean powerIsOn(); void stop(); void turn(ServoPosition position); void drive(ServoPosition speed); Engine getEngine(); Steering getSteering(); Led getLed(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; }### Answer: @Test public void testCar() throws Exception { Car car = getCar(); car.setPowerOn(); int tvalues[]= {-1,120,1000}; for (int tvalue:tvalues) { car.turn(new ServoPosition(tvalue,tvalue*10)); } int dvalues[]= {-1,150,1000}; for (int dvalue:dvalues) { car.drive(new ServoPosition(dvalue,dvalue*10)); } if (debug) servoCommand.showLog(); }
### Question: Configuration { public Configuration(String graphFilePath, boolean readInis) { this.graphFilePath = graphFilePath; setGraph(TinkerGraph.open()); File graphFile = getGraphFile(); if (readInis) { fromIni(); write(); } else { if (graphFile.exists()) { read(graphFile); } } } Configuration(String graphFilePath, boolean readInis); Configuration(); String getGraphFilePath(); void setGraphFilePath(String graphFilePath); void fromIni(); void addEnv(Environment env); TinkerGraph getGraph(); void setGraph(TinkerGraph graph); GraphTraversalSource g(); File getGraphFile(); void read(File graphFile); void write(File graphFile); String asString(); Map<String, Environment> getEnvironments(); Environment getEnvironmentFromVertex(Vertex v); void write(); static String STORE_MODE; static String STORE_EXTENSION; }### Answer: @Test public void testConfiguration() throws Exception { Configuration config=getMockConfiguration(); long nodeCount = config.g().V().count().next().longValue(); assertEquals(1,nodeCount); config.write(); assertTrue(config.getGraphFile().canRead()); config.getGraphFile().delete(); }
### Question: Environment { private Environment() { runningOnRaspberryPi = isPi(); } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberryPi(); Properties getProperties(); JsonObject asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; }### Answer: @Test public void testEnvironment() throws Exception { String ip = "1.2.3.4"; int port = 8080; File propFile = setProperties(Config.REMOTECAR_HOST, ip, Config.WEBCONTROL_PORT, "" + port); Environment env = Config.getEnvironment(); String piIp = env.getString(Config.REMOTECAR_HOST); assertEquals(ip, piIp); assertFalse(env.isPi()); assertEquals(port, env.getInteger(Config.WEBCONTROL_PORT)); propFile.delete(); }
### Question: Environment { public List<String> getMyIpAddresses() { try { return Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .map(iface -> Collections.list(iface.getInetAddresses())) .flatMap(Collection::stream).map(InetAddress::getHostAddress) .collect(Collectors.toList()); } catch (SocketException e) { LOG.error("Error while determining IP addresses: ", e); return null; } } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberryPi(); Properties getProperties(); JsonObject asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; }### Answer: @Test public void testGetMyIpAddresses() { List<String> ips = Environment.getInstance().getMyIpAddresses(); assertNotNull(ips); assertTrue(ips.size() > 1); }
### Question: Environment { public static void mock() { Environment.from("../rc-drivecontrol/src/test/resources/dukes/dukes.ini"); } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberryPi(); Properties getProperties(); JsonObject asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; }### Answer: @Test public void testMock() throws Exception { Environment.mock(); JsonObject jo = Environment.getInstance().asJsonObject(); String json = jo.toString(); if (debug) System.out.println(json); Environment env = Config.getEnvironment(); assertEquals(-20.0,env.getDouble(Config.WHEEL_MAX_LEFT_ANGLE),0.001); }
### Question: ClusterStarter { public void deployVerticles(AbstractVerticle... verticles) throws Exception { DeploymentOptions deploymentOptions = this.getDeployMentOptions(true); if (vertx == null) { this.clusteredVertx(resultHandler -> { vertx = resultHandler.result(); if (vertx == null) { ErrorHandler.getInstance().handle(new RuntimeException( "vertx not available resultHandler result is null")); } this.deployVerticles(deploymentOptions, verticles); }); } else { this.deployVerticles(deploymentOptions, verticles); } } Vertx getVertx(); void prepare(); void configureCluster(String clusterHostname,String publicHost); void clusteredVertx(Handler<AsyncResult<Vertx>> resultHandler); DeploymentOptions getDeployMentOptions(boolean worker); void deployVerticles(AbstractVerticle... verticles); VertxOptions getOptions(); void undeployVerticle(DukesVerticle verticle); String getHostname(); void setHostname(String hostname); static final int MAX_START_TIME; }### Answer: @Test public void testClusterStarter() throws Exception { Environment.mock(); ClusterStarter starter = new ClusterStarter(); TestVerticle testVerticle = new TestVerticle(); starter.deployVerticles(testVerticle); testVerticle.waitStatus(Status.started, ClusterStarter.MAX_START_TIME, 10); int minLoops=5; while (testVerticle.counter <=minLoops) { Thread.sleep(TestVerticle.TEST_INTERVAL_MS); } }
### Question: ErrorHandler { public static String getStackTraceText(Throwable th) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); th.printStackTrace(pw); String exceptionText = sw.toString(); return exceptionText; } static String getStackTraceText(Throwable th); }### Answer: @Test public void testErrorHandler() { String trace=null; try { throw new Exception("oops - a problem"); } catch (Throwable th) { trace=ErrorHandler.getStackTraceText(th); } assertNotNull(trace); assertTrue(trace.contains("oops - a problem")); assertTrue(trace.contains("TestErrorHandler.java:18")); }
### Question: ROI { public ROI(String name,double rx, double ry, double rw, double rh) { this.name=name; this.rx = rx; this.ry = ry; this.rw = rw; this.rh = rh; } ROI(String name,double rx, double ry, double rw, double rh); Rect roiRect(Size base); Mat region(Mat image); String toString(); }### Answer: @Test public void testROI() throws Exception { if (!isTravis()) { NativeLibrary.load(); File imgRoot = new File(testPath); assertTrue(imgRoot.isDirectory()); Mat image = Imgcodecs.imread(testPath + "dukes_roi_test_image.jpg"); assertNotNull(image); assertEquals(960, image.height()); assertEquals(1280, image.width()); ROI rois[] = { new ROI("all", 0, 0, 1, 1), new ROI("far", 0, 0, 1, 0.5), new ROI("near", 0, 0.5, 1, 0.5), new ROI("left", 0, 0, 0.5, 1), new ROI("right", 0.5, 0, 0.5, 1) }; for (ROI roi : rois) { System.out.println(roi); Mat roiImage = roi.region(image); if (debug) System.out.println(String.format("%10s: %4d x %4d", roi.name, roiImage.width(), roiImage.height())); assertEquals(roiImage.width(), image.width() * roi.rw, 0.1); assertEquals(roiImage.height(), image.height() * roi.rh, 0.1); this.writeImage("dukes_roi_" + roi.name, roiImage); } } }
### Question: StraightLaneNavigator extends TinkerPopDatabase implements Navigator { public StraightLaneNavigator() { this(DEFAULT_TIME_WINDOW); } StraightLaneNavigator(); StraightLaneNavigator(int timeWindow); DukesVerticle getSender(); void setSender(DukesVerticle sender); Vertex addToGraph(LaneDetectionResult ldr); @Override LaneDetectionResult fromJsonObject(JsonObject jo); boolean cmdOk(AngleRange angleRange, int minFound); void setTime(LaneDetectionResult ldr); void analyzeAngleRanges(int timeWindow, boolean showDebug); @Override JsonObject getNavigationInstruction(LaneDetectionResult ldr); JsonObject steerCommand(Double angle); @Override void navigateWithInstruction(JsonObject navigationInstruction); @Override void navigateWithMessage(Message<JsonObject> ldrMessage); @Override void navigateWithLaneDetectionResult(LaneDetectionResult ldr); @Override void videoStopped(VideoInfo videoInfo); static int COMMAND_LOOP_INTERVAL; static final int MAX_DURATION_NO_LINES_DETECTED; static final int DEFAULT_TIME_WINDOW; }### Answer: @Test public void testStraightLaneNavigator() { LaneDetectionResult ldrs[] = { getLdr(1, 0, -45., 0., 45.), getLdr(2, 100, -46., 1., 46.), getLdr(3, 200, -47., 0., 47.) }; StraightLaneNavigator nav = new StraightLaneNavigator(); for (LaneDetectionResult ldr : ldrs) nav.getNavigationInstruction(ldr); long nodeCount = nav.g().V().count().next().longValue(); assertEquals(3, nodeCount); }
### Question: WatchDog extends DukesVerticle { public WatchDog(Car car) throws Exception { super(Characters.FLASH); this.car = car; Environment env = Config.getEnvironment(); HEARTBEAT_INTERVAL_MS=env.getInteger(Config.WATCHDOG_HEARTBEAT_INTERVAL_MS); MAX_MISSED_BEATS=env.getInteger(Config.WATCHDOG_MAX_MISSED_BEATS); } WatchDog(Car car); @Override void start(); }### Answer: @Test public void testWatchDog() throws Exception { ClusterStarter clusterStarter=new ClusterStarter(); Car car=TestCar.getCar(); Environment env = Config.getEnvironment(); int heartBeatInterval=env.getInteger(Config.WATCHDOG_HEARTBEAT_INTERVAL_MS); assertEquals(20,heartBeatInterval); int maxMissedBeats=env.getInteger(Config.WATCHDOG_MAX_MISSED_BEATS); assertEquals(2,maxMissedBeats); WatchDog watchDog=new WatchDog(car); clusterStarter.deployVerticles(watchDog); watchDog.waitStatus(Status.started,20000,10); Vertx vertx=clusterStarter.getVertx(); assertNotNull(vertx); assertEquals(watchDog.getVertx(),vertx); watchDog.send(Characters.FLASH,"type","heartbeat"); int loops=0; while(!car.powerIsOn() && loops<=100) { Thread.sleep(10); loops++; } assertTrue(loops<100); LOG.info(String.format("car powered on after %3d msecs",loops*10)); Thread.sleep(heartBeatInterval*(maxMissedBeats+3)); assertTrue(!car.powerIsOn()); }
### Question: Car { public Steering getSteering() { return steering; } private Car(); void configure(Engine engine, Steering steering, Led led); void setPowerOn(); void setPowerOff(); boolean powerIsOn(); void stop(); void turn(ServoPosition position); void drive(ServoPosition speed); Engine getEngine(); Steering getSteering(); Led getLed(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; }### Answer: @Test public void testSteering() throws Exception { Car car = getCar(); Steering steering = car.getSteering(); steering.center(); ServoPosition cpos = steering.getSteeringMap().getCurrentPosition(); System.out.println(cpos); }
### Question: Car { public Led getLed() { return led; } private Car(); void configure(Engine engine, Steering steering, Led led); void setPowerOn(); void setPowerOff(); boolean powerIsOn(); void stop(); void turn(ServoPosition position); void drive(ServoPosition speed); Engine getEngine(); Steering getSteering(); Led getLed(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; }### Answer: @Test public void testLed() throws Exception { Car car = getCar(); Led led = car.getLed(); led.statusLedOn(); led.statusLedOff(); if (debug) servoCommand.showLog(); }
### Question: ImageFetcher { public ImageFetcher(String source) { this.source = source; } ImageFetcher(String source); double getFps(); void setFps(double fps); int getFrameIndex(); boolean isStaticImage(); void setStaticImage(boolean staticImage); boolean open(); void close(); long waitForNextFrame(); Image fetch(); Image createNextImage(Mat frame, long currentMillis); Observable<Image> toObservable(); boolean hasNext(); boolean isClosed(); public boolean debug; static double DEFAULT_FPS; }### Answer: @Test public void testImageFetcher() { ImageFetcher imageFetcher = getTestImageFetcher(); imageFetcher.debug=debug; Image image; do { image= imageFetcher.fetch(); } while (image != null); if (debug) { String msg = String.format("%s has %d frames", testSource, imageFetcher.getFrameIndex()); System.out.println(msg); } assertEquals(488, imageFetcher.getFrameIndex()); }
### Question: ImageFetcher { public Observable<Image> toObservable() { Observable<Image> observable = Observable .create(new ObservableOnSubscribe<Image>() { @Override public void subscribe(ObservableEmitter<Image> observableEmitter) throws Exception { hasNext=true; while (hasNext && !isClosed()) { final Image image = ImageFetcher.this.fetch(); if (hasNext) { if (debug && frameIndex % Math.round(getFps()) == 0) { String msg = String.format("->%6d:%4.0fx%4.0f", frameIndex, size.width, size.height); LOG.info(msg); } observableEmitter.onNext(image); } } observableEmitter.onComplete(); } }); return observable; } ImageFetcher(String source); double getFps(); void setFps(double fps); int getFrameIndex(); boolean isStaticImage(); void setStaticImage(boolean staticImage); boolean open(); void close(); long waitForNextFrame(); Image fetch(); Image createNextImage(Mat frame, long currentMillis); Observable<Image> toObservable(); boolean hasNext(); boolean isClosed(); public boolean debug; static double DEFAULT_FPS; }### Answer: @Test public void testImageFetcherObservable() { ImageFetcher imageFetcher = getTestImageFetcher(); Observable<Image> imageObservable = imageFetcher.toObservable(); ImageObserver imageObserver = new ImageObserver(); imageObserver.debug=debug; imageObservable.subscribe(imageObserver); assertNull(imageObserver.error); assertTrue(imageObserver.completed); assertEquals(768,imageObserver.cols); assertEquals(576,imageObserver.rows); } @Test public void testImageFetcherObservableSample() { ImageFetcher imageFetcher = getTestImageFetcher(); Observable<Image> imageObservable = imageFetcher.toObservable(); ImageObserver imageObserver = new ImageObserver(); imageObserver.debug=debug; imageObservable.sample(40, TimeUnit.MILLISECONDS).subscribe(imageObserver); assertNull(imageObserver.error); assertTrue(imageObserver.completed); assertEquals(768,imageObserver.cols); assertEquals(576,imageObserver.rows); }
### Question: RemoteCar extends DukesVerticle { public RemoteCar() { super(Characters.GENERAL_LEE); } RemoteCar(); @Override void start(); void parseArguments(String[] args); void mainInstance(String... args); static void main(String... args); @Option(name = "-ph", aliases = { "--publichost" }, usage = "hostname") String publicHost; }### Answer: @Test public void testRemoteCar() throws Exception { Environment.mock(); ClusterStarter clusterStarter = new ClusterStarter(); clusterStarter.prepare(); RemoteCar remoteCar = new RemoteCar(); clusterStarter.deployVerticles(remoteCar); DukesVerticle.debug=true; remoteCar.waitStatus(Status.started, ClusterStarter.MAX_START_TIME, 10); JsonObject configJo=Config.getEnvironment().asJsonObject(); remoteCar.send(Characters.GENERAL_LEE,configJo); Thread.sleep(ClusterStarter.MAX_START_TIME); }
### Question: RemoteCar extends DukesVerticle { public static void main(String... args) { RemoteCar remoteCar = new RemoteCar(); remoteCar.mainInstance(args); } RemoteCar(); @Override void start(); void parseArguments(String[] args); void mainInstance(String... args); static void main(String... args); @Option(name = "-ph", aliases = { "--publichost" }, usage = "hostname") String publicHost; }### Answer: @Test public void testRemoteCarCommandLine() { Environment.mock(); String args[]= {}; RemoteCar.main(args); }
### Question: ItemCache { final void cleanUp() { Instant now = Instant.now(); records.values().forEach(r->r.checkExpiration(now)); } ItemCache(Duration maxAge); void shutdown(); @Nullable Approvable get(HashId itemId); @Nullable ItemResult getResult(HashId itemId); void put(Approvable item, ItemResult result); void update(HashId itemId, ItemResult result); void idsCheck(HashId itemId); int size(); }### Answer: @Test public void cleanUp() throws Exception { ItemCache c = new ItemCache(Duration.ofMillis(10)); TestItem i1 = new TestItem(true); c.put(i1, ItemResult.UNDEFINED); assertEquals(i1, c.get(i1.getId())); Thread.sleep(11); c.cleanUp(); assertEquals(null, c.get(i1.getId())); }
### Question: ConsoleInterceptor { public static String copyOut(Block block) throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(bos, true); PrintStream oldStream = System.out; PrintStream oldErr = System.err; System.setOut(printStream); System.setErr(printStream); try { block.call(); } finally { System.setOut(oldStream); System.setErr(oldErr); } return bos.toString(); } static String copyOut(Block block); }### Answer: @Test public void interceptStdout() throws Exception { String result = ConsoleInterceptor.copyOut(() ->{ System.out.print("hello world"); System.out.print('!'); System.out.println(); System.out.println("foobar"); }); assertEquals("hello world!\nfoobar\n", result); result = ConsoleInterceptor.copyOut( () ->{ System.out.print("hello"); System.out.println(" world!"); }); assertEquals("hello world!\n", result); result = ConsoleInterceptor.copyOut( () ->{ System.out.print(58387); System.out.println(" world!"); }); assertEquals("58387 world!\n", result); }
### Question: AbstractKey implements Bindable, KeyMatcher { public byte[] fingerprint() { throw new RuntimeException("this key does not support fingerprints"); } byte[] encrypt(byte[] plain); byte[] decrypt(byte[] plain); byte[] sign(InputStream input, HashType hashType); byte[] sign(byte[] input, HashType hashType); boolean verify(InputStream input, byte[] signature, HashType hashType); boolean verify(byte[] input, byte[] signature, HashType hashType); boolean verify(String input, byte[] signature, HashType hashType); KeyInfo info(); byte[] packedInfo(); byte[] pack(); String packToBase64String(); void unpack(byte[] bytes); boolean canSign(); boolean isPublic(); boolean isPrivate(); AbstractKey getPublicKey(); @Override final Binder toBinder(); @Override final T updateFrom(Binder source); static AbstractKey fromBinder(Binder binder); boolean matchType(AbstractKey other); boolean matchTag(AbstractKey other); void setTag(String tag); void setTag(byte[] tag); @Override String toString(); Capsule.KeySource asKeySource(); byte[] fingerprint(); Digest updateDigestWithKeyComponents(Digest digest); byte[] createAnonymousId(); boolean matchAnonymousId(@NonNull byte[] packedId); KeyAddress address(boolean useSha3_384, int keyMark); final KeyAddress getShortAddress(); final KeyAddress getLongAddress(); @Override boolean isMatchingKey(AbstractKey key); @Override final boolean isMatchingKeyAddress(KeyAddress other); static final int FINGERPRINT_SHA256; static final int FINGERPRINT_SHA384; static final int TYPE_PRIVATE; static final int TYPE_PUBLIC; static final int TYPE_PRIVATE_PASSWORD; static final int TYPE_PRIVATE_PASSWORD_V2; }### Answer: @Test public void fingerprint() throws Exception { PrivateKey k = TestKeys.privateKey(0); byte[] f1 = k.getPublicKey().fingerprint(); assertEquals(33, f1.length); byte[] f2 = k.fingerprint(); assertArrayEquals(f1, f2); assertEquals(AbstractKey.FINGERPRINT_SHA256, f1[0]); }
### Question: Average { public double average() { if (n < 1) throw new IllegalStateException("too few samples"); return sum / n; } synchronized long update(double value); double average(); double stdev2(); double stdev(); long length(); double correctedStdev(); @Override String toString(); double variation(); }### Answer: @Test public void average() throws Exception { Average a = new Average(); for( int i=0; i<5; i++) a.update(i); for( int i=4; i>=0; i--) a.update(i); assertTrue(a.toString().startsWith("2.0±1.414213562373095")); assertEquals(1.490711985, a.correctedStdev(), 0.00001); }
### Question: RunnableWithDynamicPeriod implements Runnable { public void cancel(boolean b) { synchronized (cancelled) { cancelled.set(true); } } RunnableWithDynamicPeriod(Runnable lambda, List<Integer> periods, ScheduledExecutorService es); @Override void run(); void cancel(boolean b); void restart(); }### Answer: @Test public void testCancel() throws Exception { executorService.submit(() -> System.out.println("warm up executor")); Thread.sleep(1000); List<Integer> periods = Arrays.asList(100,100,100,200); time = System.nanoTime(); AtomicInteger iTick = new AtomicInteger(0); AtomicInteger errorsCount = new AtomicInteger(0); RunnableWithDynamicPeriod r = new RunnableWithDynamicPeriod(() -> { long t1 = System.nanoTime(); long dt = (t1 - time) / 1000000; time = t1; long dt0 = periods.get(Math.min(iTick.get(), periods.size()-1)); System.out.println("tick: " + dt + "ms, must be " + dt0 + "ms"); if (!(Math.abs(dt0 - dt) < dt0/10)) errorsCount.incrementAndGet(); iTick.incrementAndGet(); }, periods, executorService); r.run(); System.out.println("wait for ticks"); Thread.sleep(2000); AtomicInteger ticksCount = new AtomicInteger(iTick.get()); System.out.println("now cancel"); r.cancel(true); Thread.sleep(2000); Assert.assertEquals(ticksCount.get(), iTick.get()); }
### Question: BufferedLogger implements AutoCloseable { public @NonNull Entry log(String message) { Entry entry = new Entry(message); queue.add(entry); return entry; } BufferedLogger(int maxEntries); void e(String s); void flush(); boolean flush(long millis); PrintStream printTo(PrintStream ps, boolean printTimestamp); @NonNull Entry log(String message); @NonNull Entry d(String message); @NonNull List<Entry> getLast(int maxEntries); List<Entry> slice(long id, int maxEntries); void clear(); List<Entry> getCopy(); void interceptStdOut(); @Override void close(); void stopInterceptingStdOut(); }### Answer: @Test public void log() throws Exception { BufferedLogger log = new BufferedLogger(3); for (int i = 0; i < 10; i++) { log.log("line " + i); } log.flush(); assertEquals("line 7,line 8,line 9", str(log.getCopy())); }
### Question: Do { public static String snakeToCamelCase(String snakeString) { StringBuilder b = new StringBuilder(); for(String s: snakeString.split("_") ) { if(s.length() > 0 ) { b.append(Character.toUpperCase(s.charAt(0))); b.append(s.substring(1, s.length()).toLowerCase()); } } return b.toString(); } static byte[] read(String fileName); static byte[] read(InputStream inputStream); static String readToString(InputStream inputStream); static A checkSame(A oldValue, B newValue, Runnable onChanged); static T sample(Collection source); static SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); }### Answer: @Test public void snakeToCamelCase() throws Exception { assertEquals("HelloWorld!", Do.snakeToCamelCase("hello_wORld_!")); assertEquals("Hello", Do.snakeToCamelCase("hello_")); assertEquals("Hello", Do.snakeToCamelCase("hello")); assertEquals("Hello", Do.snakeToCamelCase("_hello")); }
### Question: Do { public static <T> T sample(Collection source) { int size = source.size(); if (size <= 0) return null; int i = Do.randomInt(size); if (source instanceof List && source instanceof RandomAccess) return (T) ((List) source).get(i); else return (T) source.toArray()[i]; } static byte[] read(String fileName); static byte[] read(InputStream inputStream); static String readToString(InputStream inputStream); static A checkSame(A oldValue, B newValue, Runnable onChanged); static T sample(Collection source); static SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); }### Answer: @Test public void sample() throws Exception { HashSet<String> x = new HashSet<>(Do.listOf("aa", "bb", "cc", "cd")); HashSet<String> y = new HashSet<>(); ArrayList<String> z = new ArrayList<>(Do.listOf("aa", "bb", "cc", "cd")); HashSet<String> t = new HashSet<>(); int repetitions = 10000; for (int i = 0; i < repetitions; i++) { y.add(Do.sample(x)); t.add(Do.sample(z)); } assertEquals(y,x); }
### Question: Do { public static int randomInt(int max) { return getRng().nextInt(max); } static byte[] read(String fileName); static byte[] read(InputStream inputStream); static String readToString(InputStream inputStream); static A checkSame(A oldValue, B newValue, Runnable onChanged); static T sample(Collection source); static SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); }### Answer: @Test public void randomInt() throws Exception { double sum = 0; int repetitions = 20000; int min = 10000, max = -1000; for(int i=0; i < repetitions; i++ ) { int x = Do.randomInt(100); sum += x; if( x < min ) min = x; if( x > max ) max = x; } sum /= repetitions; assertThat( sum, is(closeTo(50, 0.9))); assertThat(min, is(lessThan(20))); assertThat(max, is(greaterThan(80))); }
### Question: DeferredResult { public DeferredResult success(Handler handler) { synchronized (successHandlers) { successHandlers.add(handler); } if (done && success) invokeSuccess(); return this; } DeferredResult success(Handler handler); DeferredResult failure(Handler handler); DeferredResult done(Handler handler); void sendSuccess(Object data); void sendFailure(Object data); boolean isDone(); @SuppressWarnings("unchecked") T getResult(); T waitSuccess(); T await(); T await(long millis); final DeferredResult join(); boolean isSuccess(); final boolean join(long millis); }### Answer: @Test public void success() throws Exception { DeferredResult dr = new DeferredResult(); dr.success( (text-> assertEquals("hello", text))); dr.sendSuccess("hello"); }
### Question: AsyncEvent { public void fire(T result) { synchronized (mutex) { this.result = result; fired = true; for (Consumer<T> consumer : consumers) pool.execute(() -> consumer.accept(result)); consumers.clear(); mutex.notifyAll(); } } AsyncEvent<T> addConsumer(Consumer<T> consumer); void fire(T result); boolean isFired(); @Deprecated T waitFired(); T await(); T await(long milliseconds); final void fire(); }### Answer: @Test public void fire() throws Exception { for(int n=0; n<500; n++) { AsyncEvent<Integer> event = new AsyncEvent<>(); int values[] = new int[] { 0, 0}; CountDownLatch latch = new CountDownLatch(2); event.addConsumer(i -> { values[0] = i; latch.countDown(); }); event.addConsumer(i -> { values[1] = i; latch.countDown(); }); event.fire(11); int res = event.waitFired(); assertEquals(11, res); latch.await(); assertEquals(11, values[0]); assertEquals(11, values[1]); } }
### Question: JsonConnector extends BasicConnector implements Connector { @Override public void send(Map<String, Object> data) throws IOException { if (closed.get()) throw new IOException("connection closed"); out.write((toJsonString(data) + "\n").getBytes()); } JsonConnector(InputStream in, OutputStream out); @Override void send(Map<String, Object> data); @Override Map<String, Object> receive(); }### Answer: @Test(timeout = 100) public void send() throws Exception { StreamConnector sa = new StreamConnector(); JsonConnector jsc = new JsonConnector(sa.getInputStream(), sa.getOutputStream()); jsc.send(Do.map("hello", "мыльня")); Map<String, Object> res = jsc.receive(); assertEquals(1, res.size()); assertEquals("мыльня", res.get("hello")); }
### Question: Informer { public void post(Object event) { int result; int processedCount = invokeCollection(weakInvocations, event); processedCount += invokeCollection(strongInvocations, event); if (processedCount == 0 && !(event instanceof LostEvent)) { post(new LostEvent(event)); } } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer: @Test public void testPost() throws Exception { Receiver2 receiver = new Receiver2(); informer.registerStrong(receiver); informer.post(123); assertEquals(0, Receiver2.stringCalls); assertEquals(1, Receiver2.objectCalls); assertEquals(123, receiver.lastObject); informer.post("test1"); assertEquals(2, Receiver2.stringCalls); assertEquals(2, Receiver2.objectCalls); assertEquals("test1", receiver.lastObject); assertEquals(0, Receiver2.lostCount); }
### Question: Informer { public void postAfter(final Object event, final long millis) { new Thread(new Runnable() { @Override public void run() { try { Thread.currentThread().sleep(millis); post(event); } catch (InterruptedException e) { } } }).start(); } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer: @Test public void testPostAfter() throws Exception { Receiver1 r1 = new Receiver1(); informer.registerWeak(r1); informer.postAfter(11, 100); assertEquals(0, Receiver1.lostCount); sleep(40); assertEquals(0, Receiver1.lostCount); sleep(70); assertEquals(1, Receiver1.lostCount); }
### Question: Informer { public void registerWeak(Object subscriber) { register(subscriber, true); } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer: @Test public void testRegisterWeak() throws Exception { assertEquals(0, Receiver1.lostCount); informer.registerWeak(new Receiver1()); System.gc(); informer.post(11); assertEquals(0, Receiver1.lostCount); }
### Question: Informer { public void registerStrong(Object subscriber) { register(subscriber, false); } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer: @Test public void testRegisterStrong() throws Exception { assertEquals(0, Receiver1.lostCount); informer.registerStrong(new Receiver1()); informer.post(11); assertEquals(1, Receiver1.lostCount); }
### Question: Informer { public boolean unregister(Object subscriber) { boolean found = (weakInvocations.remove(subscriber) != null); found = found || (strongInvocations.remove(subscriber) != null); return found; } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer: @Test public void testUnregister() throws Exception { assertEquals(0, Receiver1.lostCount); Receiver1 r1 = new Receiver1(); informer.registerWeak(r1); informer.unregister(r1); informer.post(11); assertEquals(0, Receiver1.lostCount); informer.registerStrong(r1); informer.unregister(r1); informer.post(11); assertEquals(0, Receiver1.lostCount); }
### Question: Safe58 { public static String encode(byte[] input) { if (input.length == 0) { return ""; } input = copyOfRange(input, 0, input.length); int zeroCount = 0; while (zeroCount < input.length && input[zeroCount] == 0) { ++zeroCount; } byte[] temp = new byte[input.length * 2]; int j = temp.length; int startAt = zeroCount; while (startAt < input.length) { byte mod = divmod58(input, startAt); if (input[startAt] == 0) { ++startAt; } temp[--j] = (byte) ALPHABET[mod]; } while (j < temp.length && temp[j] == ALPHABET[0]) { ++j; } while (--zeroCount >= 0) { temp[--j] = (byte) ALPHABET[0]; } byte[] output = copyOfRange(temp, j, temp.length); return new String(output); } static String encode(byte[] input); static byte[] decode(String input); static byte[] decode(String input, boolean strict); }### Answer: @Test public void encode() { for(int i=0; i<100;i++) { byte [] src = Do.randomBytes(256+Do.randomInt(1024)); assertArrayEquals(src, Safe58.decode(Safe58.encode(src))); } }
### Question: KeyAddress implements KeyMatcher { @Override public boolean isMatchingKey(AbstractKey key) { KeyAddress other = new KeyAddress(key, 0, _isLong); if (other.keyMask != keyMask) return false; if (!Arrays.equals(keyDigest, other.keyDigest)) return false; return true; } KeyAddress(); KeyAddress(AbstractKey key, int typeMark, boolean useSha3_384); KeyAddress(byte[] packedSource); KeyAddress(String packedString); KeyAddress(Binder binder); @Override boolean isMatchingKey(AbstractKey key); @Override boolean isMatchingKeyAddress(KeyAddress other); final boolean isLong(); final byte[] getPacked(); final int getTypeMark(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static BiAdapter getBiAdapter(); }### Answer: @Test public void isMatchingKey() throws KeyAddress.IllegalAddressException { testMatch(true); testMatch(false); }