method2testcases
stringlengths
118
6.63k
### 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 { @Override public Multimap<String, String> buildRequestHeaders() { checkState(headerTag != null, "headerTag should have been injected!"); checkState(metadataPrefix != null, "metadataPrefix should have been injected!"); ImmutableMultimap.Builder<String, String> returnVal = ImmutableMultimap.builder(); for (Entry<String, String> entry : headers.entries()) { returnVal.put(entry.getKey().replace(DEFAULT_AMAZON_HEADERTAG, headerTag), entry.getValue()); } boolean replace = false; if (cacheControl != null) { returnVal.put(HttpHeaders.CACHE_CONTROL, cacheControl); replace = true; } if (contentDisposition != null) { returnVal.put(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); replace = true; } if (contentEncoding != null) { returnVal.put(HttpHeaders.CONTENT_ENCODING, contentEncoding); replace = true; } if (contentLanguage != null) { returnVal.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); replace = true; } if (contentType != null) { returnVal.put(HttpHeaders.CONTENT_TYPE, contentType); replace = true; } if (metadata != null) { for (Map.Entry<String, String> entry : metadata.entrySet()) { String key = entry.getKey(); returnVal.put(key.startsWith(metadataPrefix) ? key : metadataPrefix + key, entry.getValue()); } replace = true; } if (replace) { returnVal.put(METADATA_DIRECTIVE.replace(DEFAULT_AMAZON_HEADERTAG, headerTag), "REPLACE"); } return returnVal.build(); } @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 void testBuildRequestHeaders() { CopyObjectOptions options = ifSourceModifiedSince(now).ifSourceETagDoesntMatch(etag).overrideMetadataWith( goodMeta); options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG); options.setMetadataPrefix(USER_METADATA_PREFIX); Multimap<String, String> headers = options.buildRequestHeaders(); assertEquals(getOnlyElement(headers.get(COPY_SOURCE_IF_MODIFIED_SINCE)), new SimpleDateFormatDateService() .rfc822DateFormat(now)); assertEquals(getOnlyElement(headers.get(COPY_SOURCE_IF_NO_MATCH)), "\"" + etag + "\""); for (String value : goodMeta.values()) assertTrue(headers.containsValue(value)); }
### 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: BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }### Answer: @Test public void testWithASmallSet() { HttpRequest result = binder.bindToRequest(request, ImmutableSet.of("key1", "key2")); Payload payload = Payloads .newStringPayload("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Delete>" + "<Object><Key>key1</Key></Object><Object><Key>key2</Key></Object></Delete>"); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); assertEquals(result.getPayload(), payload); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptySetThrowsException() { binder.bindToRequest(request, ImmutableSet.of()); } @Test(expectedExceptions = NullPointerException.class) public void testFailsOnNullSet() { binder.bindToRequest(request, null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testExpectedASetInstance() { binder.bindToRequest(request, ImmutableList.of()); }
### Question: BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }### Answer: @Test public void testPassWithMinimumDetailsAndPayload5GB() { ObjectMetadata md = ObjectMetadataBuilder.create().key("foo").build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); assertEquals(binder.bindToRequest(request, md), HttpRequest.builder().method("POST") .endpoint("http: } @Test public void testExtendedPropertiesBind() { ObjectMetadata md = ObjectMetadataBuilder.create().key("foo").cacheControl("no-cache").userMetadata( ImmutableMap.of("foo", "bar")).build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); assertEquals(binder.bindToRequest(request, md), HttpRequest.builder().method("POST").endpoint("http: ImmutableMultimap.of("Cache-Control", "no-cache", "x-amz-meta-foo", "bar", "Content-Type", "binary/octet-stream")).build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNoKeyIsBad() { ObjectMetadata md = ObjectMetadataBuilder.create().build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); binder.bindToRequest(request, md); } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeObjectMetadata() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: injector.getInstance(BindObjectMetadataToRequest.class).bindToRequest(request, new File("foo")); } @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); }
### 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: BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }### Answer: @Test public void testPassWithMinimumDetailsAndPayload5GB() { HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: Payload payload = Payloads .newStringPayload("<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>\"a54357aff0632cce46d942af68356b38\"</ETag></Part></CompleteMultipartUpload>"); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request = binder.bindToRequest(request, ImmutableMap.<Integer, String> of(1, "\"a54357aff0632cce46d942af68356b38\"")); assertEquals(request.getPayload().getRawContent(), payload.getRawContent()); assertEquals(request, HttpRequest.builder().method("PUT").endpoint("http: payload).build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyIsBad() { HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: binder.bindToRequest(request, ImmutableMap.<Integer, String> of()); } @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); }
### 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 { public HttpRequest filter(HttpRequest request) throws HttpException { request = replaceDateHeader(request); Credentials current = creds.get(); if (current instanceof SessionCredentials) { request = replaceSecurityTokenHeader(request, SessionCredentials.class.cast(current)); } String signature = calculateSignature(createStringToSign(request)); request = replaceAuthorizationHeader(request, signature); utils.logRequest(signatureLog, request, "<<"); return request; } @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(threadPoolSize = 3, dataProvider = "dataProvider", timeOut = 10000) void testIdempotent(HttpRequest request) { request = filter.filter(request); String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION); String date = request.getFirstHeaderOrNull(HttpHeaders.DATE); int iterations = 1; while (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) { date = request.getFirstHeaderOrNull(HttpHeaders.DATE); request = filter.filter(request); if (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) assert signature.equals(request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION)) : String.format( "sig: %s != %s on attempt %s", signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION), iterations); else iterations++; } System.out.printf("%s: %d iterations before the timestamp updated %n", Thread.currentThread().getName(), iterations); }
### 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: UpdateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.UpdatePayload> { @Override protected String createPayload(Server.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateServer>") .append("<request>") .append(format("<serverId>%s</serverId>", payload.id())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateServer>"); return requestBuilder.toString(); } UpdateServerRequestBinder(); }### Answer: @Test public void testCreatePayload() { UpdateServerRequestBinder binder = new UpdateServerRequestBinder(); Server.Request.UpdatePayload payload = Server.Request.updatingBuilder() .id("qwertyui-qwer-qwer-qwer-qwertyyuiiop") .cores(8) .ram(8 * 1024) .name("apache-node") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public Set<String> getSecurityGroupIds() { return securityGroupIds; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testDefaultSecurityGroupIds() { TemplateOptions options = new CloudStackTemplateOptions(); assertEquals(options.as(CloudStackTemplateOptions.class).getSecurityGroupIds(), ImmutableSet.of()); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds) { this.securityGroupIds = ImmutableSet.copyOf(securityGroupIds); return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testSecurityGroupIds() { TemplateOptions options = new CloudStackTemplateOptions().securityGroupIds(ImmutableSet.of("3")); assertEquals(options.as(CloudStackTemplateOptions.class).getSecurityGroupIds(), ImmutableSet.of("3")); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateSecurityGroup() { return generateSecurityGroup; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testGenerateSecurityGroupDefaultsFalse() { TemplateOptions options = new CloudStackTemplateOptions(); assertFalse(options.as(CloudStackTemplateOptions.class) .shouldGenerateSecurityGroup()); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup) { this.generateSecurityGroup = generateSecurityGroup; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testGenerateSecurityGroup() { TemplateOptions options = new CloudStackTemplateOptions().generateSecurityGroup(true); assertTrue(options.as(CloudStackTemplateOptions.class) .shouldGenerateSecurityGroup()); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { @Override public CloudStackTemplateOptions networks(Iterable<String> networks) { return CloudStackTemplateOptions.class.cast(super.networks(networks)); } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testNetworkId() { TemplateOptions options = new CloudStackTemplateOptions().networks("3"); assertEquals(options.as(CloudStackTemplateOptions.class).getNetworks(), ImmutableSet.of("3")); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) { this.ipOnDefaultNetwork = ipOnDefaultNetwork; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testIpOnDefaultNetwork() { TemplateOptions options = new CloudStackTemplateOptions().ipOnDefaultNetwork("10.0.0.1"); assertEquals(options.as(CloudStackTemplateOptions.class).getIpOnDefaultNetwork(), "10.0.0.1"); }
### Question: CreateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.CreatePayload> { @Override protected String createPayload(Server.Request.CreatePayload payload) { requestBuilder.append("<ws:createServer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<internetAccess>%s</internetAccess>", payload.hasInternetAccess())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:createServer>"); return requestBuilder.toString(); } CreateServerRequestBinder(); }### Answer: @Test public void testCreatePayload() { CreateServerRequestBinder binder = new CreateServerRequestBinder(); Server.Request.CreatePayload payload = Server.Request.creatingBuilder() .name("jclouds-node") .cores(4) .ram(4 * 1024) .dataCenterId("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldSetupStaticNat() { return setupStaticNat; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testSetupStaticNatDefaultsTrue() { TemplateOptions options = new CloudStackTemplateOptions(); assertTrue(options.as(CloudStackTemplateOptions.class) .shouldSetupStaticNat()); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat) { this.setupStaticNat = setupStaticNat; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testSetupStaticNat() { TemplateOptions options = new CloudStackTemplateOptions().setupStaticNat(false); assertFalse(options.as(CloudStackTemplateOptions.class) .shouldSetupStaticNat()); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateKeyPair() { return generateKeyPair; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testGenerateKeyPairDefaultsFalse() { TemplateOptions options = new CloudStackTemplateOptions(); assertFalse(options.as(CloudStackTemplateOptions.class) .shouldGenerateKeyPair()); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair) { this.generateKeyPair = generateKeyPair; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testGenerateKeyPair() { TemplateOptions options = new CloudStackTemplateOptions().generateKeyPair(true); assertTrue(options.as(CloudStackTemplateOptions.class) .shouldGenerateKeyPair()); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions keyPair(String keyPair) { this.keyPair = keyPair; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testKeyPair() { TemplateOptions options = keyPair("test"); assertEquals(options.as(CloudStackTemplateOptions.class).getKeyPair(), "test"); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions diskOfferingId(String diskOfferingId) { this.diskOfferingId = diskOfferingId; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testDiskOfferingId() { TemplateOptions options = diskOfferingId("test"); assertEquals(options.as(CloudStackTemplateOptions.class).getDiskOfferingId(), "test"); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public int getDataDiskSize() { return dataDiskSize; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testDataDiskSizeDefault() { TemplateOptions options = new CloudStackTemplateOptions(); assertEquals(options.as(CloudStackTemplateOptions.class).getDataDiskSize(), 0); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions dataDiskSize(int dataDiskSize) { this.dataDiskSize = dataDiskSize; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testDataDiskSize() { TemplateOptions options = dataDiskSize(10); assertEquals(options.as(CloudStackTemplateOptions.class).getDataDiskSize(), 10); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions account(String account) { this.account = account; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testAccount() { TemplateOptions options = account("test"); assertEquals(options.as(CloudStackTemplateOptions.class).getAccount(), "test"); }
### Question: CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions domainId(String domainId) { this.domainId = domainId; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testDomainId() { TemplateOptions options = domainId("test"); assertEquals(options.as(CloudStackTemplateOptions.class).getDomainId(), "test"); }
### Question: AddFirewallRuleToNicRequestBinder extends BaseProfitBricksRequestBinder<Firewall.Request.AddRulePayload> { @Override protected String createPayload(Firewall.Request.AddRulePayload payload) { requestBuilder.append("<ws:addFirewallRulesToNic>") .append(format("<nicId>%s</nicId>", payload.nicId())); for (Firewall.Rule rule : payload.rules()) requestBuilder .append("<request>") .append(formatIfNotEmpty("<icmpCode>%s</icmpCode>", rule.icmpCode())) .append(formatIfNotEmpty("<icmpType>%s</icmpType>", rule.icmpType())) .append(formatIfNotEmpty("<name>%s</name>", rule.name())) .append(formatIfNotEmpty("<portRangeEnd>%s</portRangeEnd>", rule.portRangeEnd())) .append(formatIfNotEmpty("<portRangeStart>%s</portRangeStart>", rule.portRangeStart())) .append(formatIfNotEmpty("<protocol>%s</protocol>", rule.protocol())) .append(formatIfNotEmpty("<sourceIp>%s</sourceIp>", rule.sourceIp())) .append(formatIfNotEmpty("<sourceMac>%s</sourceMac>", rule.sourceMac())) .append(formatIfNotEmpty("<targetIp>%s</targetIp>", rule.targetIp())) .append("</request>"); requestBuilder.append("</ws:addFirewallRulesToNic>"); return requestBuilder.toString(); } AddFirewallRuleToNicRequestBinder(); }### Answer: @Test public void testCreatePayload() { AddFirewallRuleToNicRequestBinder binder = new AddFirewallRuleToNicRequestBinder(); Firewall.Request.AddRulePayload payload = Firewall.Request.createAddRulePayload( "nic-id", ImmutableList.of( Firewall.Rule.builder() .name("name") .portRangeEnd(45678) .portRangeStart(12345) .protocol(Firewall.Protocol.TCP) .sourceIp("192.168.0.1") .sourceMac("aa:bb:cc:dd:ee:ff") .targetIp("192.168.0.2") .build() )); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### 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: LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); @Override LoginResponse load(Credentials input); @Override String toString(); }### Answer: @Test public void testWithDoubleDomainname() { LoginResponse response = createMock(LoginResponse.class); SessionApi client = createMock(SessionApi.class); expect(client.loginUserInDomainWithHashOfPassword(eq("User"), eq("Test/Domain"), (String) anyObject())).andReturn(response); replay(client); LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client); Credentials cred = new Credentials("Test/Domain/User", "koffiedik"); obj.load(cred); } @Test public void testWithSingleDomainname() { LoginResponse response = createMock(LoginResponse.class); SessionApi client = createMock(SessionApi.class); expect(client.loginUserInDomainWithHashOfPassword(eq("User"), eq("Domain"), (String) anyObject())).andReturn(response); replay(client); LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client); Credentials cred = new Credentials("Domain/User", "koffiedik"); obj.load(cred); } @Test public void testWithNoDomainname() { LoginResponse response = createMock(LoginResponse.class); SessionApi client = createMock(SessionApi.class); expect(client.loginUserInDomainWithHashOfPassword(eq("User"), eq(""), (String) anyObject())).andReturn(response); replay(client); LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client); Credentials cred = new Credentials("User", "koffiedik"); obj.load(cred); }
### 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: NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations, Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); @Override NodeMetadata apply(Node from); }### Answer: @Test public void testNodesParse() throws Exception { assertEquals(parser.apply(NodesFromYamlTest.TEST1), expectedNodeMetadataFromResource(resource, provider)); assertEquals(credentialStore, ImmutableMap.of("node#cluster-1", new Credentials("myUser", NodesFromYamlTest.key))); } @Test public void testNodesParseLocation() throws Exception { assertEquals(parser.apply(NodesFromYamlTest.TEST2), expectedNodeMetadataFromResource(resource, zoneCalled("virginia", provider))); assertEquals(credentialStore, ImmutableMap.of("node#cluster-1", new Credentials("myUser", NodesFromYamlTest.key))); } @Test public void testNodesParseLoginPort() throws Exception { assertEquals(parser.apply(NodesFromYamlTest.TEST3), expectedNodeMetadataFromResource(2, resource, provider, 2022)); }
### Question: FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public void removeBlob(final String container, final String blobKey) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(blobKey); String fileName = buildPathStartingFromBaseDir(container, blobKey); logger.debug("Deleting blob %s", fileName); File fileToBeDeleted = new File(fileName); if (fileToBeDeleted.isDirectory()) { try { UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(fileToBeDeleted.toPath()); if (view != null) { for (String s : view.list()) { view.delete(s); } } } catch (IOException e) { logger.debug("Could not delete attributes from %s: %s", fileToBeDeleted, e); } } try { delete(fileToBeDeleted); } catch (IOException e) { logger.debug("Could not delete %s: %s", fileToBeDeleted, e); } removeDirectoriesTreeOfBlobKey(container, blobKey); } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders, @Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir, @Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType, FilesystemContainerNameValidator filesystemContainerNameValidator, FilesystemBlobKeyValidator filesystemBlobKeyValidator, Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); }### Answer: @Test public void testDeletingInvalidPathFileEndsNormally() { String invalidPathBlobKey = "A<!:!@#$%^&*?]8 /\0"; try { storageStrategy.removeBlob(CONTAINER_NAME, invalidPathBlobKey); } catch (InvalidPathException ipe) { fail("Deleting an invalid path ended with an InvalidPathException.", ipe); } }
### 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: UpdateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.UpdatePayload> { @Override protected String createPayload(Snapshot.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.id())) .append(format("<description>%s</description>", payload.description())) .append(format("<snapshotName>%s</snapshotName>", payload.name())) .append(formatIfNotEmpty("<bootable>%s</bootable>", payload.bootable())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<cpuHotUnPlug>%s</cpuHotUnPlug>", payload.isCpuHotUnPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<ramHotUnPlug>%s</ramHotUnPlug>", payload.isRamHotUnPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateSnapshot>"); return requestBuilder.toString(); } protected UpdateSnapshotRequestBinder(); }### Answer: @Test public void testUpdatePayload() { UpdateSnapshotRequestBinder binder = new UpdateSnapshotRequestBinder(); Snapshot.Request.UpdatePayload payload = Snapshot.Request.updatingBuilder() .id("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh") .description("description") .name("snapshot-name") .bootable(true) .osType(OsType.LINUX) .isCpuHotPlug(true) .isCpuHotUnPlug(true) .isRamHotPlug(true) .isRamHotUnPlug(true) .isNicHotPlug(true) .isNicHotUnPlug(true) .isDiscVirtioHotPlug(true) .isDiscVirtioHotUnPlug(true) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldAutoAssignFloatingIp() { return autoAssignFloatingIp; } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test public void testautoAssignFloatingIpDefault() { NovaTemplateOptions options = new NovaTemplateOptions(); assert !options.shouldAutoAssignFloatingIp(); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { public NovaTemplateOptions autoAssignFloatingIp(boolean enable) { this.autoAssignFloatingIp = enable; return this; } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test public void testautoAssignFloatingIp() { NovaTemplateOptions options = new NovaTemplateOptions().autoAssignFloatingIp(true); assert options.shouldAutoAssignFloatingIp(); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateKeyPair() { return generateKeyPair; } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test public void testGenerateKeyPairDefault() { NovaTemplateOptions options = new NovaTemplateOptions(); assert !options.shouldGenerateKeyPair(); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { public NovaTemplateOptions generateKeyPair(boolean enable) { this.generateKeyPair = enable; return this; } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test public void testGenerateKeyPair() { NovaTemplateOptions options = new NovaTemplateOptions().generateKeyPair(true); assert options.shouldGenerateKeyPair(); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { @Override public NovaTemplateOptions installPrivateKey(String privateKey) { return NovaTemplateOptions.class.cast(super.installPrivateKey(privateKey)); } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testinstallPrivateKeyBadFormat() { NovaTemplateOptions options = new NovaTemplateOptions(); options.installPrivateKey("whompy"); } @Test public void testinstallPrivateKey() throws IOException { NovaTemplateOptions options = new NovaTemplateOptions(); options.installPrivateKey("-----BEGIN RSA PRIVATE KEY-----"); assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----"); } @Test public void testinstallPrivateKeyStatic() throws IOException { NovaTemplateOptions options = installPrivateKey("-----BEGIN RSA PRIVATE KEY-----"); assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----"); } @Test(expectedExceptions = NullPointerException.class) public void testinstallPrivateKeyNPE() { installPrivateKey(null); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { @Override public NovaTemplateOptions authorizePublicKey(String publicKey) { return NovaTemplateOptions.class.cast(super.authorizePublicKey(publicKey)); } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testauthorizePublicKeyBadFormat() { NovaTemplateOptions options = new NovaTemplateOptions(); options.authorizePublicKey("whompy"); } @Test public void testauthorizePublicKey() throws IOException { NovaTemplateOptions options = new NovaTemplateOptions(); options.authorizePublicKey("ssh-rsa"); assertEquals(options.getPublicKey(), "ssh-rsa"); } @Test public void testauthorizePublicKeyStatic() throws IOException { NovaTemplateOptions options = authorizePublicKey("ssh-rsa"); assertEquals(options.getPublicKey(), "ssh-rsa"); } @Test(expectedExceptions = NullPointerException.class) public void testauthorizePublicKeyNPE() { authorizePublicKey(null); }
### 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: NovaTemplateOptions extends TemplateOptions implements Cloneable { public NovaTemplateOptions userData(byte[] userData) { checkArgument(checkNotNull(userData, "userData").length <= 16 * 1024, "userData cannot be larger than 16kb"); this.userData = userData; return this; } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test public void testUserData() { NovaTemplateOptions options = new NovaTemplateOptions(); options.userData("test".getBytes()); assertEquals(new String(options.getUserData()), "test"); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { public NovaTemplateOptions availabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; return this; } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test public void testAvailabilityZone() { NovaTemplateOptions options = new NovaTemplateOptions(); options.availabilityZone("nova"); assertEquals(options.getAvailabilityZone(), "nova"); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { public NovaTemplateOptions diskConfig(String diskConfig) { this.diskConfig = diskConfig; return this; } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test public void testDiskConfig() { NovaTemplateOptions options = new NovaTemplateOptions(); options.diskConfig(Server.DISK_CONFIG_AUTO); assertEquals(options.getDiskConfig(), Server.DISK_CONFIG_AUTO); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { @Override public NovaTemplateOptions blockOnPort(int port, int seconds) { return NovaTemplateOptions.class.cast(super.blockOnPort(port, seconds)); } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testblockOnPortBadFormat() { NovaTemplateOptions options = new NovaTemplateOptions(); options.blockOnPort(-1, -1); } @Test public void testblockOnPort() { NovaTemplateOptions options = new NovaTemplateOptions(); options.blockOnPort(22, 30); assertEquals(options.getPort(), 22); assertEquals(options.getSeconds(), 30); } @Test public void testblockOnPortStatic() { NovaTemplateOptions options = blockOnPort(22, 30); assertEquals(options.getPort(), 22); assertEquals(options.getSeconds(), 30); }
### Question: NovaTemplateOptions extends TemplateOptions implements Cloneable { @Override public NovaTemplateOptions inboundPorts(int... ports) { return NovaTemplateOptions.class.cast(super.inboundPorts(ports)); } @Override NovaTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); NovaTemplateOptions autoAssignFloatingIp(boolean enable); NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames); NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames); NovaTemplateOptions generateKeyPair(boolean enable); NovaTemplateOptions keyPairName(String keyPairName); boolean shouldAutoAssignFloatingIp(); NovaTemplateOptions availabilityZone(String availabilityZone); NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings); NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings); Optional<Set<String>> getFloatingIpPoolNames(); String getKeyPairName(); boolean shouldGenerateKeyPair(); byte[] getUserData(); String getDiskConfig(); boolean getConfigDrive(); Set<Network> getNovaNetworks(); String getAvailabilityZone(); Set<BlockDeviceMapping> getBlockDeviceMappings(); @Override NovaTemplateOptions blockOnPort(int port, int seconds); @Override NovaTemplateOptions inboundPorts(int... ports); @Override NovaTemplateOptions authorizePublicKey(String publicKey); @Override NovaTemplateOptions installPrivateKey(String privateKey); @Override NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override NovaTemplateOptions dontAuthorizePublicKey(); @Override NovaTemplateOptions nameTask(String name); @Override NovaTemplateOptions runAsRoot(boolean runAsRoot); @Override NovaTemplateOptions runScript(Statement script); @Override NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override NovaTemplateOptions overrideLoginPassword(String password); @Override NovaTemplateOptions overrideLoginPrivateKey(String privateKey); @Override NovaTemplateOptions overrideLoginUser(String loginUser); @Override NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override NovaTemplateOptions userMetadata(Map<String, String> userMetadata); @Override NovaTemplateOptions userMetadata(String key, String value); @Override NovaTemplateOptions nodeNames(Iterable<String> nodeNames); @Override NovaTemplateOptions networks(Iterable<String> networks); @Override NovaTemplateOptions networks(String... networks); NovaTemplateOptions userData(byte[] userData); NovaTemplateOptions diskConfig(String diskConfig); NovaTemplateOptions configDrive(boolean configDrive); NovaTemplateOptions novaNetworks(Set<Network> novaNetworks); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testinboundPortsBadFormat() { NovaTemplateOptions options = new NovaTemplateOptions(); options.inboundPorts(-1, -1); } @Test public void testinboundPorts() { NovaTemplateOptions options = new NovaTemplateOptions(); options.inboundPorts(22, 30); assertEquals(options.getInboundPorts()[0], 22); assertEquals(options.getInboundPorts()[1], 30); } @Test public void testinboundPortsStatic() { NovaTemplateOptions options = inboundPorts(22, 30); assertEquals(options.getInboundPorts()[0], 22); assertEquals(options.getInboundPorts()[1], 30); }
### 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: OrphanedGroupsByRegionId implements Function<Set<? extends NodeMetadata>, Multimap<String, String>> { public Multimap<String, String> apply(Set<? extends NodeMetadata> deadNodes) { Iterable<? extends NodeMetadata> nodesWithGroup = filter(deadNodes, NodePredicates.hasGroup()); Set<RegionAndName> regionAndGroupNames = ImmutableSet.copyOf(filter(transform(nodesWithGroup, new Function<NodeMetadata, RegionAndName>() { @Override public RegionAndName apply(NodeMetadata input) { String regionId = input.getLocation().getScope() == LocationScope.HOST ? input.getLocation() .getParent().getId() : input.getLocation().getId(); return RegionAndName.fromRegionAndName(regionId, input.getGroup()); } }), allNodesInGroupTerminated)); Multimap<String, String> regionToRegionAndGroupNames = Multimaps.transformValues(Multimaps.index(regionAndGroupNames, RegionAndName.REGION_FUNCTION), RegionAndName.NAME_FUNCTION); return regionToRegionAndGroupNames; } @Inject protected OrphanedGroupsByRegionId(ComputeService computeService); @VisibleForTesting OrphanedGroupsByRegionId(Predicate<RegionAndName> allNodesInGroupTerminated); Multimap<String, String> apply(Set<? extends NodeMetadata> deadNodes); }### Answer: @Test public void testWhenComputeServiceSaysAllNodesAreDeadBothGroupsAreReturned() { ServerInRegion withoutHost = new ServerInRegion(new ServerInRegionToNodeMetadataTest().expectedServer(), "az-1.region-a.geo-1"); ServerInRegion withHost = new ServerInRegion(new ParseServerTest().expected(), "az-1.region-a.geo-1"); ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata( NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers .<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of()), Suppliers .<Set<? extends Hardware>> ofInstance(ImmutableSet.<Hardware> of()), namingConvention); Set<? extends NodeMetadata> set = ImmutableSet.of(converter.apply(withHost), converter.apply(withoutHost)); assertEquals(new OrphanedGroupsByRegionId(Predicates.<RegionAndName> alwaysTrue()).apply(set), ImmutableMultimap .<String, String> builder().putAll("az-1.region-a.geo-1", "sample", "test").build()); } @Test public void testWhenComputeServiceSaysAllNodesAreDeadNoGroupsAreReturned() { ServerInRegion withoutHost = new ServerInRegion(new ServerInRegionToNodeMetadataTest().expectedServer(), "az-1.region-a.geo-1"); ServerInRegion withHost = new ServerInRegion(new ParseServerTest().expected(), "az-1.region-a.geo-1"); ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata( NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers .<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of()), Suppliers .<Set<? extends Hardware>> ofInstance(ImmutableSet.<Hardware> of()), namingConvention); Set<? extends NodeMetadata> set = ImmutableSet.of(converter.apply(withHost), converter.apply(withoutHost)); assertEquals(new OrphanedGroupsByRegionId(Predicates.<RegionAndName> alwaysFalse()).apply(set), ImmutableMultimap .<String, String> of()); }
### 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: NovaSecurityGroupInRegionToSecurityGroup implements Function<SecurityGroupInRegion, SecurityGroup> { @Override public SecurityGroup apply(final SecurityGroupInRegion groupInRegion) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); final org.jclouds.openstack.nova.v2_0.domain.SecurityGroup group = groupInRegion.getSecurityGroup(); builder.id(group.getId()); builder.providerId(group.getId()); builder.ownerId(group.getTenantId()); builder.name(group.getName()); if (group.getRules() != null) { builder.ipPermissions(filter(transform(group.getRules(), new Function<SecurityGroupRule, IpPermission>() { @Override public IpPermission apply(SecurityGroupRule input) { return securityGroupRuleToIpPermission(groupInRegion, input); } }), Predicates.notNull())); } final String regionId = groupInRegion.getRegion(); Location region = locationIndex.get().get(regionId); checkState(region != null, "location %s not in locationIndex: %s", regionId, locationIndex.get()); builder.location(region); builder.id(regionId + "/" + group.getId()); return builder.build(); } @Inject NovaSecurityGroupInRegionToSecurityGroup(Supplier<Map<String, Location>> locationIndex); @Override SecurityGroup apply(final SecurityGroupInRegion groupInRegion); }### Answer: @Test public void testApplyWithGroup() { NovaSecurityGroupInRegionToSecurityGroup parser = createGroupParser(); final org.jclouds.openstack.nova.v2_0.domain.SecurityGroup otherGroup = securityGroupWithCidr(); SecurityGroupInRegion origGroup = new SecurityGroupInRegion(securityGroupWithGroup(), region.getId(), allGroups); SecurityGroup newGroup = parser.apply(origGroup); assertEquals(newGroup.getId(), origGroup.getRegion() + "/" + origGroup.getSecurityGroup().getId()); assertEquals(newGroup.getProviderId(), origGroup.getSecurityGroup().getId()); assertEquals(newGroup.getName(), origGroup.getSecurityGroup().getName()); assertEquals(newGroup.getOwnerId(), origGroup.getSecurityGroup().getTenantId()); final IpPermission permission = Iterables.getOnlyElement(newGroup.getIpPermissions()); assertEquals(Iterables.getOnlyElement(permission.getGroupIds()), region.getId() + "/" + otherGroup.getId()); assertEquals(permission.getFromPort(), 10); assertEquals(permission.getToPort(), 20); assertTrue(permission.getCidrBlocks().isEmpty()); assertEquals(newGroup.getLocation().getId(), origGroup.getRegion()); } @Test public void testApplyWithCidr() { NovaSecurityGroupInRegionToSecurityGroup parser = createGroupParser(); SecurityGroupInRegion origGroup = new SecurityGroupInRegion(securityGroupWithCidr(), region.getId(), allGroups); SecurityGroup newGroup = parser.apply(origGroup); assertEquals(newGroup.getId(), origGroup.getRegion() + "/" + origGroup.getSecurityGroup().getId()); assertEquals(newGroup.getProviderId(), origGroup.getSecurityGroup().getId()); assertEquals(newGroup.getName(), origGroup.getSecurityGroup().getName()); assertEquals(newGroup.getOwnerId(), origGroup.getSecurityGroup().getTenantId()); final IpPermission permission = Iterables.getOnlyElement(newGroup.getIpPermissions()); assertEquals(permission.getFromPort(), 10); assertEquals(permission.getToPort(), 20); assertEquals(Iterables.getOnlyElement(permission.getCidrBlocks()), IP_RANGE); assertTrue(permission.getGroupIds().isEmpty()); assertEquals(newGroup.getLocation().getId(), origGroup.getRegion()); }
### Question: FlavorInRegionToHardware implements Function<FlavorInRegion, Hardware> { @Override public Hardware apply(FlavorInRegion flavorInRegion) { Location location = locationIndex.get().get(flavorInRegion.getRegion()); checkState(location != null, "location %s not in locationIndex: %s", flavorInRegion.getRegion(), locationIndex.get()); Flavor flavor = flavorInRegion.getFlavor(); return new HardwareBuilder().id(flavorInRegion.slashEncode()).providerId(flavor.getId()).name(flavor.getName()) .ram(flavor.getRam()).processor(new Processor(flavor.getVcpus(), 1.0)).volume( new VolumeImpl(Float.valueOf(flavor.getDisk()), true, true)).location(location).build(); } @Inject FlavorInRegionToHardware(Supplier<Map<String, Location>> locationIndex); @Override Hardware apply(FlavorInRegion flavorInRegion); }### Answer: @Test public void testConversionWhereLocationFound() { UUID id = UUID.randomUUID(); FlavorInRegion flavorInRegionToConvert = new FlavorInRegion(Flavor.builder().id(id.toString()) .name("Test Flavor " + id).ram(262144).disk(10000).vcpus(16).build(), "az-1.region-a.geo-1"); Hardware converted = new FlavorInRegionToHardware(locationIndex).apply(flavorInRegionToConvert); Flavor flavorToConvert = flavorInRegionToConvert.getFlavor(); assertEquals(converted.getName(), flavorToConvert.getName()); assertEquals(converted.getId(), flavorInRegionToConvert.slashEncode()); assertEquals(converted.getProviderId(), flavorToConvert.getId()); assertEquals(converted.getLocation(), locationIndex.get().get("az-1.region-a.geo-1")); assertEquals(converted.getRam(), flavorToConvert.getRam()); assertNotNull(converted.getProcessors()); assertFalse(converted.getProcessors().isEmpty()); assertEquals(converted.getProcessors().iterator().next().getCores(), (double) flavorToConvert.getVcpus()); assertNotNull(converted.getVolumes()); assertFalse(converted.getVolumes().isEmpty()); assertEquals(converted.getVolumes().iterator().next().getSize(), Float.valueOf(flavorToConvert.getDisk())); } @Test(expectedExceptions = IllegalStateException.class) public void testConversionWhereLocationNotFound() { UUID id = UUID.randomUUID(); FlavorInRegion flavorInRegionToConvert = new FlavorInRegion(Flavor.builder().id(id.toString()) .name("Test Flavor " + id).ram(262144).disk(10000).vcpus(16).build(), "South"); new FlavorInRegionToHardware(locationIndex).apply(flavorInRegionToConvert); }
### Question: LoadFloatingIpsForInstance extends CacheLoader<RegionAndId, Iterable<? extends FloatingIpForServer>> { @Override public Iterable<? extends FloatingIpForServer> load(final RegionAndId key) throws Exception { String region = key.getRegion(); Optional<? extends FloatingIPApi> ipApiOptional = api.getFloatingIPApi(region); if (ipApiOptional.isPresent()) { return ipApiOptional.get().list().filter( new Predicate<FloatingIP>() { @Override public boolean apply(FloatingIP input) { return key.getId().equals(input.getInstanceId()); } }) .transform(new Function<FloatingIP, FloatingIpForServer>() { @Override public FloatingIpForServer apply(FloatingIP input) { return FloatingIpForServer.create(key, input.getId(), input.getIp()); } }); } return ImmutableSet.of(); } @Inject LoadFloatingIpsForInstance(NovaApi api); @Override Iterable<? extends FloatingIpForServer> load(final RegionAndId key); }### Answer: @Test public void testReturnsPublicIpOnMatch() throws Exception { NovaApi api = createMock(NovaApi.class); FloatingIPApi ipApi = createMock(FloatingIPApi.class); FloatingIP testIp = FloatingIP.builder().id("1").ip("1.1.1.1").fixedIp("10.1.1.1").instanceId("i-blah").build(); expect(api.getFloatingIPApi("RegionOne")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce(); expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of(testIp))) .atLeastOnce(); replay(api); replay(ipApi); LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api); FloatingIpForServer floatingIpForServer = FloatingIpForServer.create(RegionAndId.fromRegionAndId("RegionOne", "i-blah"), "1", "1.1.1.1"); assertEquals(ImmutableSet.copyOf(parser.load(RegionAndId.fromRegionAndId("RegionOne", "i-blah"))), ImmutableSet.of(floatingIpForServer)); verify(api); verify(ipApi); } @Test public void testReturnsNullWhenNotFound() throws Exception { NovaApi api = createMock(NovaApi.class); FloatingIPApi ipApi = createMock(FloatingIPApi.class); expect(api.getFloatingIPApi("region")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce(); expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of())) .atLeastOnce(); replay(api); replay(ipApi); LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api); assertFalse(parser.load(RegionAndId.fromRegionAndId("region", "i-blah")).iterator().hasNext()); verify(api); verify(ipApi); } @Test public void testReturnsNullWhenNotAssigned() throws Exception { NovaApi api = createMock(NovaApi.class); FloatingIPApi ipApi = createMock(FloatingIPApi.class); expect(api.getFloatingIPApi("region")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce(); expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of(FloatingIP.builder().id("1").ip("1.1.1.1").build()))) .atLeastOnce(); replay(api); replay(ipApi); LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api); assertFalse(parser.load(RegionAndId.fromRegionAndId("region", "i-blah")).iterator().hasNext()); verify(api); verify(ipApi); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions hostname(@Nullable String hostname) { this.hostname = hostname; return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testHostname() { TemplateOptions options = DockerTemplateOptions.Builder.hostname("hostname"); assertEquals(options.as(DockerTemplateOptions.class).getHostname(), "hostname"); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions memory(@Nullable Integer memory) { this.memory = memory; return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testMemory() { TemplateOptions options = DockerTemplateOptions.Builder.memory(1024); assertEquals(options.as(DockerTemplateOptions.class).getMemory(), Integer.valueOf(1024)); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions cpuShares(@Nullable Integer cpuShares) { this.cpuShares = cpuShares; return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testCpuShares() { TemplateOptions options = DockerTemplateOptions.Builder.cpuShares(2); assertEquals(options.as(DockerTemplateOptions.class).getCpuShares(), Integer.valueOf(2)); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions volumes(Map<String, String> volumes) { this.volumes = NullSafeCopies.copyOf(volumes); return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testVolumes() { TemplateOptions options = DockerTemplateOptions.Builder.volumes(ImmutableMap.of("/tmp", "/tmp")); assertEquals(options.as(DockerTemplateOptions.class).getVolumes(), ImmutableMap.of("/tmp", "/tmp")); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions dns(Iterable<String> dns) { this.dns = NullSafeCopies.copyOf(dns); return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testDns() { TemplateOptions options = DockerTemplateOptions.Builder.dns("8.8.8.8", "8.8.4.4"); assertEquals(options.as(DockerTemplateOptions.class).getDns(), ImmutableList.of("8.8.8.8", "8.8.4.4")); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions entrypoint(Iterable<String> entrypoint) { this.entrypoint = NullSafeCopies.copyWithNullOf(entrypoint); return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testEntrypoint() { TemplateOptions options = DockerTemplateOptions.Builder.entrypoint("/bin/sh", "-c"); assertEquals(options.as(DockerTemplateOptions.class).getEntrypoint(), ImmutableList.of("/bin/sh", "-c")); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions commands(Iterable<String> commands) { this.commands = NullSafeCopies.copyWithNullOf(commands); return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testCommands() { TemplateOptions options = DockerTemplateOptions.Builder.commands("chmod 666 /etc/*", "rm -rf /var/run"); assertEquals(options.as(DockerTemplateOptions.class).getCommands(), ImmutableList.of("chmod 666 /etc/*", "rm -rf /var/run")); }
### 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: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions env(Iterable<String> env) { this.env = NullSafeCopies.copyWithNullOf(env); return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testEnv() { TemplateOptions options = DockerTemplateOptions.Builder.env(ImmutableList.of("HOST=abc", "PORT=1234")); assertEquals(options.as(DockerTemplateOptions.class).getEnv(), ImmutableList.of("HOST=abc", "PORT=1234")); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings) { this.portBindings = NullSafeCopies.copyOf(portBindings); return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testPortBindings() { TemplateOptions options = DockerTemplateOptions.Builder.portBindings(ImmutableMap.<Integer, Integer>builder().put(8443, 443).put(8080, 80).build()); assertEquals(options.as(DockerTemplateOptions.class).getPortBindings(), ImmutableMap.<Integer, Integer>builder().put(8443, 443).put(8080, 80).build()); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions networkMode(@Nullable String networkMode) { this.networkMode = networkMode; return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testNetworkMode() { TemplateOptions options = DockerTemplateOptions.Builder.networkMode("host"); assertEquals(options.as(DockerTemplateOptions.class).getNetworkMode(), "host"); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions privileged(boolean privileged) { this.privileged = privileged; return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testPrivileged() { TemplateOptions options = DockerTemplateOptions.Builder.privileged(true); assertEquals(options.as(DockerTemplateOptions.class).getPrivileged(), true); }
### Question: DockerTemplateOptions extends TemplateOptions implements Cloneable { public DockerTemplateOptions configBuilder(Config.Builder configBuilder) { this.configBuilder = configBuilder != null ? Config.builder().fromConfig(configBuilder.image(NO_IMAGE).build()) : null; return this; } @Override DockerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); DockerTemplateOptions volumes(Map<String, String> volumes); DockerTemplateOptions dns(Iterable<String> dns); DockerTemplateOptions dns(String...dns); DockerTemplateOptions hostname(@Nullable String hostname); DockerTemplateOptions memory(@Nullable Integer memory); DockerTemplateOptions entrypoint(Iterable<String> entrypoint); DockerTemplateOptions entrypoint(String... entrypoint); DockerTemplateOptions commands(Iterable<String> commands); DockerTemplateOptions commands(String...commands); DockerTemplateOptions cpuShares(@Nullable Integer cpuShares); DockerTemplateOptions env(Iterable<String> env); DockerTemplateOptions env(String...env); DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings); DockerTemplateOptions networkMode(@Nullable String networkMode); DockerTemplateOptions extraHosts(Map<String, String> extraHosts); DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom); DockerTemplateOptions privileged(boolean privileged); DockerTemplateOptions openStdin(boolean openStdin); DockerTemplateOptions configBuilder(Config.Builder configBuilder); Map<String, String> getVolumes(); List<String> getDns(); List<String> getVolumesFrom(); String getHostname(); Integer getMemory(); List<String> getEntrypoint(); List<String> getCommands(); Integer getCpuShares(); List<String> getEnv(); Map<Integer, Integer> getPortBindings(); String getNetworkMode(); Map<String, String> getExtraHosts(); boolean getPrivileged(); boolean getOpenStdin(); Config.Builder getConfigBuilder(); @Override DockerTemplateOptions blockOnPort(int port, int seconds); @Override DockerTemplateOptions inboundPorts(int... ports); @Override DockerTemplateOptions authorizePublicKey(String publicKey); @Override DockerTemplateOptions installPrivateKey(String privateKey); @Override DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override DockerTemplateOptions dontAuthorizePublicKey(); @Override DockerTemplateOptions nameTask(String name); @Override DockerTemplateOptions runAsRoot(boolean runAsRoot); @Override DockerTemplateOptions runScript(Statement script); @Override DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override DockerTemplateOptions overrideLoginPassword(String password); @Override DockerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override DockerTemplateOptions overrideLoginUser(String loginUser); @Override DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override DockerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override DockerTemplateOptions userMetadata(String key, String value); @Override DockerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override DockerTemplateOptions networks(Iterable<String> networks); }### Answer: @Test public void testConfigBuilder() { Builder builder = Config.builder().memory(1024) .cpuShares(100).cmd(ImmutableList.<String> of("/opt/jboss/wildfly/bin/standalone.sh", "-b", "0.0.0.0")) .env(ImmutableList.<String> of("JAVA_HOME=/opt/jdk-1.8", "MGMT_USER=admin", "MGMT_PASSWORD=Schroedinger's Cat")); TemplateOptions options = DockerTemplateOptions.Builder.configBuilder(builder); Builder builderInOpts = options.as(DockerTemplateOptions.class).getConfigBuilder(); assertNotNull(builderInOpts); Config configFromOptions = builderInOpts.build(); assertEquals(configFromOptions, builder.build()); assertEquals(configFromOptions.env(), ImmutableList.<String> of("JAVA_HOME=/opt/jdk-1.8", "MGMT_USER=admin", "MGMT_PASSWORD=Schroedinger's Cat")); }
### 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); }