method2testcases
stringlengths 118
3.08k
|
---|
### Question:
DeliveryParameterBuilder { public DeliveryParameterBuilder projection(String... elements) { if (elements != null) { nameValuePairs.add(new NameValuePair(ELEMENTS, String.join(",", elements))); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer:
@Test public void testProjection() { List<NameValuePair> params = DeliveryParameterBuilder.params().projection("foo", "bar").build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("elements", params.get(0).getName()); Assert.assertEquals("foo,bar", params.get(0).getValue()); } |
### Question:
DeliveryParameterBuilder { public DeliveryParameterBuilder linkedItemsDepth(Integer depth) { if (depth != null) { nameValuePairs.add(new NameValuePair(DEPTH, depth.toString())); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer:
@Test public void testLinkedItemsDepth() { List<NameValuePair> params = DeliveryParameterBuilder.params().linkedItemsDepth(3).build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("depth", params.get(0).getName()); Assert.assertEquals("3", params.get(0).getValue()); } |
### Question:
DeliveryParameterBuilder { public DeliveryParameterBuilder excludeLinkedItems() { nameValuePairs.add(new NameValuePair(DEPTH, "0")); return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer:
@Test public void testExcludeLinkedItems() { List<NameValuePair> params = DeliveryParameterBuilder.params().excludeLinkedItems().build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("depth", params.get(0).getName()); Assert.assertEquals("0", params.get(0).getValue()); } |
### Question:
DeliveryParameterBuilder { public DeliveryParameterBuilder language(String language) { if (language != null) { nameValuePairs.add(new NameValuePair(LANGUAGE, language)); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer:
@Test public void testLanguage() { List<NameValuePair> params = DeliveryParameterBuilder.params().language(Locale.US.toLanguageTag()).build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("language", params.get(0).getName()); Assert.assertEquals("en-US", params.get(0).getValue()); } |
### Question:
DeliveryParameterBuilder { public DeliveryParameterBuilder includeTotalCount() { nameValuePairs.add(new NameValuePair(INCLUDE_TOTAL_COUNT, "true")); return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer:
@Test public void testIncludeTotalCount() { List<NameValuePair> params = DeliveryParameterBuilder.params().includeTotalCount().build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("includeTotalCount", params.get(0).getName()); Assert.assertEquals("true", params.get(0).getValue()); } |
### Question:
ThymeleafTemplateEngine implements TemplateEngine { protected boolean supports(TemplateEngineModel data) { if (!configured) { return false; } String contentType = getContentTypeFromModel(data.getInlineContentItem()); if (contentType == null) { return false; } Set<ITemplateResolver> templateResolvers = templateEngine.getTemplateResolvers(); for (ITemplateResolver resolver : templateResolvers) { if (resolver instanceof AbstractTemplateResolver) { TemplateResolution templateResolution = resolver.resolveTemplate(templateEngine.getConfiguration(), null, contentType, null); if (templateResolution != null && templateResolution.getTemplateResource().exists()) { return true; } } } return false; } @Override void setViewResolverConfiguration(ViewResolverConfiguration viewResolverConfiguration); @Override String process(TemplateEngineModel data); }### Answer:
@Test public void testIllegalStateException() throws RenderingEngineMissingException { ThymeleafInlineContentItemsResolver resolver = new ThymeleafInlineContentItemsResolver(); ArticleItem articleItem = new ArticleItem(); articleItem.setTitle("Test"); TemplateEngineModel templateEngineModel = new TemplateEngineModel(); templateEngineModel.setInlineContentItem(articleItem); Assert.assertFalse(resolver.supports(templateEngineModel)); try { resolver.resolve(templateEngineModel); Assert.fail("Expected IllegalStateException"); } catch (IllegalStateException e) { Assert.assertEquals("Engine not configured. Did you call setViewResolverConfiguration()?", e.getMessage()); } } |
### Question:
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled) { this.backupsEnabled = backupsEnabled; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer:
@Test public void testBackupsEnabled() { TemplateOptions options = new DigitalOcean2TemplateOptions().backupsEnabled(true); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getBackupsEnabled(), true); } |
### Question:
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair) { this.autoCreateKeyPair = autoCreateKeyPair; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer:
@Test public void testAutoCreateKeyPair() { TemplateOptions options = new DigitalOcean2TemplateOptions().autoCreateKeyPair(false); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getAutoCreateKeyPair(), false); } |
### Question:
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions userData(byte[] userData) { this.userData = userData; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer:
@Test public void testUserData() { byte[] userData = "Lorem ipsum".getBytes(); TemplateOptions options = new DigitalOcean2TemplateOptions().userData(userData); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getUserData(), userData); } |
### Question:
DropletStatusToStatus implements Function<Droplet.Status, Status> { @Override public Status apply(final Droplet.Status input) { return toPortableStatus.apply(input); } @Override Status apply(final Droplet.Status input); }### Answer:
@Test public void testAllStatesHaveMapping() { DropletStatusToStatus function = new DropletStatusToStatus(); for (Status status : Status.values()) { assertNotEquals(function.apply(status), UNRECOGNIZED); } } |
### Question:
SizeToHardware implements Function<Size, Hardware> { @Override public Hardware apply(Size input) { HardwareBuilder builder = new HardwareBuilder(); builder.id(input.slug()); builder.providerId(input.slug()); builder.name(input.slug()); builder.ram(input.memory()); builder.processor(new Processor(input.vcpus(), input.vcpus())); builder.volume(new VolumeBuilder() .size(Float.valueOf(input.disk())) .type(Type.LOCAL) .build()); ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("costPerHour", String.valueOf(input.priceHourly())); metadata.put("costPerMonth", String.valueOf(input.priceMonthly())); builder.userMetadata(metadata.build()); return builder.build(); } @Override Hardware apply(Size input); }### Answer:
@Test public void testConvertSize() { Size size = Size.create("2gb", true, 1.0f, 10f, 0.05f, 2048, 1, 20, ImmutableList.<String> of()); Hardware expected = new HardwareBuilder().id("2gb").providerId("2gb").name("2gb") .processor(new Processor(1.0, 1.0)).ram(2048) .volume(new VolumeBuilder().size(20f).type(Type.LOCAL).build()) .userMetadata(ImmutableMap.of("costPerHour", "0.05", "costPerMonth", "10")).build(); SizeToHardware function = new SizeToHardware(); assertEquals(function.apply(size), expected); } |
### Question:
RegionToLocation implements Function<Region, Location> { @Override public Location apply(Region input) { LocationBuilder builder = new LocationBuilder(); builder.id(input.slug()); builder.description(input.name()); builder.scope(LocationScope.REGION); builder.parent(getOnlyElement(justProvider.get())); builder.iso3166Codes(ImmutableSet.<String> of()); builder.metadata(ImmutableMap.<String, Object> of("available", input.available(), "features", input.features())); return builder.build(); } @Inject RegionToLocation(JustProvider justProvider); @Override Location apply(Region input); }### Answer:
@Test public void testConvertRegion() { DigitalOcean2ProviderMetadata metadata = new DigitalOcean2ProviderMetadata(); JustProvider locationsSupplier = new JustProvider(metadata.getId(), Suppliers.<URI> ofInstance(URI .create(metadata.getEndpoint())), ImmutableSet.<String> of()); Region region = Region.create("reg1", "Region1", ImmutableList.<String> of(), true, ImmutableList.<String> of("virtio", "metadata")); Location expected = new LocationBuilder().id("reg1").description("reg1/Region 1") .parent(getOnlyElement(locationsSupplier.get())).scope(LocationScope.REGION).build(); Location location = new RegionToLocation(locationsSupplier).apply(region); assertEquals(location, expected); assertEquals(location.getMetadata().get("available"), true); assertEquals(location.getMetadata().get("features"), ImmutableList.of("virtio", "metadata")); } |
### Question:
ECDSAKeys { public static String fingerprintPublicKey(String publicKeyOpenSSH) throws IOException { ECPublicKeySpec publicKeySpec = publicKeySpecFromOpenSSH(publicKeyOpenSSH); String fingerprint = null; try { ECPublicKey pk = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(publicKeySpec); fingerprint = fingerprint(pk); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return fingerprint; } static String encodeAsOpenSSH(ECPublicKey key); static ECPublicKeySpec publicKeySpecFromOpenSSH(String ecDsaPub); static ECPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(ECPublicKey publicKey); static byte[] encodeECPoint(ECPoint group, EllipticCurve curve); static ECPoint decodeECPoint(byte[] M, EllipticCurve curve); static final String ECDSA_SHA2_PREFIX; }### Answer:
@Test public void testCanReadRsaAndCompareFingerprintOnPublicECDSAKey() throws IOException { String ecdsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-ecdsa.pub")); String fingerPrint = ECDSAKeys.fingerprintPublicKey(ecdsa); assertEquals(fingerPrint, expectedFingerPrint); } |
### Question:
BindS3UploadPolicyAndSignature implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { String encodedJson = base64().encode(checkNotNull(input, "json").toString().getBytes(UTF_8)); Builder<String, String> builder = ImmutableMultimap.builder(); builder.put("Storage.S3.UploadPolicy", encodedJson); String signature = signer.sign(encodedJson); builder.put("Storage.S3.UploadPolicySignature", signature); return (R) request.toBuilder().replaceFormParams(builder.build()).build(); } @Inject BindS3UploadPolicyAndSignature(FormSignerV2 signer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testNullIsBad() { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); } |
### Question:
ECDSAKeys { public static String encodeAsOpenSSH(ECPublicKey key) { String curveName = null; try { curveName = getCurveName(key.getParams()); } catch (IOException e) { propagate(e); } String keyFormat = ECDSA_SHA2_PREFIX + curveName; byte[] keyBlob = keyBlob(key); return keyFormat + " " + base64().encode(keyBlob); } static String encodeAsOpenSSH(ECPublicKey key); static ECPublicKeySpec publicKeySpecFromOpenSSH(String ecDsaPub); static ECPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(ECPublicKey publicKey); static byte[] encodeECPoint(ECPoint group, EllipticCurve curve); static ECPoint decodeECPoint(byte[] M, EllipticCurve curve); static final String ECDSA_SHA2_PREFIX; }### Answer:
@Test public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { String ecdsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-ecdsa.pub")); ECPublicKeySpec spec = ECDSAKeys.publicKeySpecFromOpenSSH(ecdsa); ECPublicKey key = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(spec); assertTrue(ecdsa.startsWith(ECDSAKeys.encodeAsOpenSSH(key))); } |
### Question:
VolumeDetached implements Predicate<Attachment> { public boolean apply(Attachment attachment) { logger.trace("looking for volume %s", attachment.getVolumeId()); Volume volume = Iterables.getOnlyElement(client.describeVolumesInRegion(attachment .getRegion(), attachment.getVolumeId())); if (volume.getAttachments().isEmpty()) { return true; } Attachment lastAttachment = getLast(volume.getAttachments()); logger.trace("%s: looking for status %s: currently: %s", lastAttachment, Attachment.Status.DETACHED, lastAttachment.getStatus()); return lastAttachment.getStatus() == Attachment.Status.DETACHED; } @Inject VolumeDetached(ElasticBlockStoreApi client); boolean apply(Attachment attachment); }### Answer:
@Test public void testVolumeWithEmptyListOfAttachments() { Attachment attachment = newAttachmentWithStatus(Status.ATTACHED); Set<Volume> volumes = newHashSet(newVolumeWithAttachments()); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertTrue(volumeDetached.apply(attachment)); verify(client); }
@Test(dataProvider = "notDetachedStatuses") public void testWithDifferentStatus(Status attachmentStatus) { Attachment attachment = newAttachmentWithStatus(attachmentStatus); Set<Volume> volumes = newHashSet(newVolumeWithAttachments(attachment)); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertFalse(volumeDetached.apply(attachment)); verify(client); }
@Test public void testWithStatusDetached() { Attachment attachment = newAttachmentWithStatus(Status.DETACHED); Set<Volume> volumes = newHashSet(newVolumeWithAttachments(attachment)); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertTrue(volumeDetached.apply(attachment)); verify(client); } |
### Question:
DSAKeys { public static String fingerprintPublicKey(String publicKeyOpenSSH) { DSAPublicKeySpec publicKeySpec = publicKeySpecFromOpenSSH(publicKeyOpenSSH); return fingerprint(publicKeySpec.getP(), publicKeySpec.getQ(), publicKeySpec.getG(), publicKeySpec.getY()); } static String encodeAsOpenSSH(DSAPublicKey key); static DSAPublicKeySpec publicKeySpecFromOpenSSH(String idDsaPub); static DSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(BigInteger p, BigInteger q, BigInteger g, BigInteger y); }### Answer:
@Test public void testCanReadRsaAndCompareFingerprintOnPublicRSAKey() throws IOException { String dsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-dsa.pub")); String fingerPrint = DSAKeys.fingerprintPublicKey(dsa); assertEquals(fingerPrint, expectedFingerPrint); } |
### Question:
DSAKeys { public static String encodeAsOpenSSH(DSAPublicKey key) { DSAParams params = key.getParams(); byte[] keyBlob = keyBlob(params.getP(), params.getQ(), params.getG(), key.getY()); return "ssh-dss " + base64().encode(keyBlob); } static String encodeAsOpenSSH(DSAPublicKey key); static DSAPublicKeySpec publicKeySpecFromOpenSSH(String idDsaPub); static DSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(BigInteger p, BigInteger q, BigInteger g, BigInteger y); }### Answer:
@Test public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { String dsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-dsa.pub")); DSAPublicKeySpec spec = DSAKeys.publicKeySpecFromOpenSSH(dsa); DSAPublicKey key = (DSAPublicKey) KeyFactory.getInstance("DSA").generatePublic(spec); assertEquals(DSAKeys.encodeAsOpenSSH(key), dsa); } |
### Question:
EC2ComputeServiceContextModule extends BaseComputeServiceContextModule { protected Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader( final RegionAndIdToImage delegate) { return Suppliers.<CacheLoader<RegionAndName, Image>>ofInstance(new CacheLoader<RegionAndName, Image>() { private final AtomicReference<AuthorizationException> authException = Atomics.newReference(); @Override public Image load(final RegionAndName key) throws Exception { Supplier<Image> rawSupplier = new Supplier<Image>() { @Override public Image get() { try { return delegate.load(key); } catch (ExecutionException e) { throw Throwables.propagate(e); } } }; return new SetAndThrowAuthorizationExceptionSupplier<Image>(rawSupplier, authException).get(); } }); } }### Answer:
@Test public void testCacheLoaderDoesNotReloadAfterAuthorizationException() throws Exception { EC2ComputeServiceContextModule module = new EC2ComputeServiceContextModule() { public Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(RegionAndIdToImage delegate) { return super.provideRegionAndNameToImageSupplierCacheLoader(delegate); } }; RegionAndName regionAndName = new RegionAndName("myregion", "myname"); AuthorizationException authException = new AuthorizationException(); RegionAndIdToImage mockRegionAndIdToImage = createMock(RegionAndIdToImage.class); expect(mockRegionAndIdToImage.load(regionAndName)).andThrow(authException).once(); replay(mockRegionAndIdToImage); CacheLoader<RegionAndName, Image> cacheLoader = module.provideRegionAndNameToImageSupplierCacheLoader(mockRegionAndIdToImage).get(); for (int i = 0; i < 2; i++) { try { Image image = cacheLoader.load(regionAndName); fail("Expected Authorization exception, but got " + image); } catch (AuthorizationException e) { } } } |
### Question:
EC2SecurityGroupToSecurityGroup implements Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup> { @Override public SecurityGroup apply(org.jclouds.ec2.domain.SecurityGroup group) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); Location location = findLocationWithId(group.getRegion()); builder.location(location); builder.id(group.getRegion() + "/" + idOrName(group)); builder.providerId(group.getId()); builder.name(group.getName()); builder.ipPermissions(group); builder.ownerId(group.getOwnerId()); return builder.build(); } @Inject EC2SecurityGroupToSecurityGroup(@Memoized Supplier<Set<? extends Location>> locations); @Override SecurityGroup apply(org.jclouds.ec2.domain.SecurityGroup group); }### Answer:
@Test public void testApply() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); org.jclouds.ec2.domain.SecurityGroup origGroup = org.jclouds.ec2.domain.SecurityGroup.builder() .region("us-east-1") .id("some-id") .name("some-group") .ownerId("some-owner") .description("some-description") .ipPermission(authorization) .build(); EC2SecurityGroupToSecurityGroup parser = createGroupParser(ImmutableSet.of(provider)); SecurityGroup group = parser.apply(origGroup); assertEquals(group.getLocation(), provider); assertEquals(group.getId(), provider.getId() + "/" + origGroup.getName()); assertEquals(group.getProviderId(), origGroup.getId()); assertEquals(group.getName(), origGroup.getName()); assertEquals(group.getIpPermissions(), (Set<IpPermission>)origGroup); assertEquals(group.getOwnerId(), origGroup.getOwnerId()); } |
### Question:
CreateUniqueKeyPair implements Function<RegionAndName, KeyPair> { @Override public KeyPair apply(RegionAndName from) { return createNewKeyPairInRegion(from.getRegion(), from.getName()); } @Inject CreateUniqueKeyPair(EC2Api ec2Api, GroupNamingConvention.Factory namingConvention); @Override KeyPair apply(RegionAndName from); }### Answer:
@Test public void testApply() throws UnknownHostException { final EC2Api client = createMock(EC2Api.class); KeyPairApi keyClient = createMock(KeyPairApi.class); KeyPair pair = createMock(KeyPair.class); expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyClient)).atLeastOnce(); expect(keyClient.createKeyPairInRegion("region", "jclouds#group#1")).andReturn(pair); replay(client); replay(keyClient); CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), new EC2ApiMetadata().getDefaultProperties()); bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(EC2Api.class).toInstance(client); } }).getInstance(CreateUniqueKeyPair.class); assertEquals(parser.createNewKeyPairInRegion("region", "group"), pair); verify(client); verify(keyClient); } |
### Question:
PresentInstances implements Function<Set<RegionAndName>, Set<RunningInstance>> { @Override public Set<RunningInstance> apply(Set<RegionAndName> regionAndIds) { if (checkNotNull(regionAndIds, "regionAndIds").isEmpty()) return ImmutableSet.of(); Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder(); Multimap<String, String> regionToInstanceIds = transformValues(index(regionAndIds, regionFunction()), nameFunction()); for (Map.Entry<String, Collection<String>> entry : regionToInstanceIds.asMap().entrySet()) { String region = entry.getKey(); Collection<String> instanceIds = entry.getValue(); logger.trace("looking for instances %s in region %s", instanceIds, region); builder.addAll(concat(client.getInstanceApi().get().describeInstancesInRegion(region, toArray(instanceIds, String.class)))); } return builder.build(); } @Inject PresentInstances(EC2Api client); @Override Set<RunningInstance> apply(Set<RegionAndName> regionAndIds); @Override String toString(); }### Answer:
@SuppressWarnings("unchecked") @Test public void testWhenInstancesPresentSingleCall() { EC2Api client = createMock(EC2Api.class); InstanceApi instanceClient = createMock(InstanceApi.class); expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)); expect(instanceClient.describeInstancesInRegion("us-east-1", "i-aaaa", "i-bbbb")).andReturn( Set.class.cast(ImmutableSet.of(Reservation.builder().region("us-east-1") .instances(ImmutableSet.of(instance1, instance2)).build()))); replay(client, instanceClient); PresentInstances fn = new PresentInstances(client); assertEquals(fn.apply(ImmutableSet.of(new RegionAndName("us-east-1", "i-aaaa"), new RegionAndName("us-east-1", "i-bbbb"))), ImmutableSet.of(instance1, instance2)); verify(client, instanceClient); } |
### Question:
WindowsLoginCredentialsFromEncryptedData implements Function<PasswordDataAndPrivateKey, LoginCredentials> { @Override public LoginCredentials apply(@Nullable PasswordDataAndPrivateKey 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(dataAndKey.getPasswordData().getPasswordData()); byte[] plainText = cipher.doFinal(cipherText); String password = new String(plainText, Charsets.US_ASCII); return LoginCredentials.builder() .user("Administrator") .password(password) .noPrivateKey() .build(); } catch (Exception e) { throw Throwables.propagate(e); } } @Inject WindowsLoginCredentialsFromEncryptedData(Crypto crypto); @Override LoginCredentials apply(@Nullable PasswordDataAndPrivateKey dataAndKey); }### Answer:
@Test public void testApply() throws Exception { WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto()); PasswordData passwordData = PasswordData.builder() .instanceId("i-2574e22a") .timestamp(dateService.iso8601DateParse("2012-07-30T07:27:23.000+0000")) .passwordData(ENCRYPTED_PASSWORD).build(); LoginCredentials credentials = f.apply(new PasswordDataAndPrivateKey(passwordData, PRIVATE_KEY)); assertEquals(credentials.getUser(), "Administrator"); assertEquals(credentials.getOptionalPassword().get(), "u4.y9mb;nR."); assertFalse(credentials.getOptionalPrivateKey().isPresent()); } |
### Question:
PrivateKeySupplier implements Supplier<PrivateKey> { @Override public PrivateKey get() { try { return keyCache.getUnchecked(checkNotNull(creds.get(), "credential supplier returned null")); } catch (UncheckedExecutionException e) { AuthorizationException authorizationException = getFirstThrowableOfType(e, AuthorizationException.class); if (authorizationException != null) { throw authorizationException; } throw e; } } @Inject PrivateKeySupplier(@Provider Supplier<Credentials> creds, PrivateKeyForCredentials loader); @Override PrivateKey get(); }### Answer:
@Test(expectedExceptions = AuthorizationException.class) public void testAuthorizationExceptionIsThrownOnBadKeys() { PrivateKeySupplier supplier = new PrivateKeySupplier( Suppliers.ofInstance(new Credentials("MOMMA", "FileNotFoundCredential")), new PrivateKeyForCredentials()); supplier.get(); } |
### Question:
EndpointIfAlreadyExists implements Fallback<URI>, InvocationContext<EndpointIfAlreadyExists> { @Override public URI createOrPropagate(Throwable t) throws Exception { if (checkNotNull(t, "throwable") instanceof KeyAlreadyExistsException) { return endpoint; } throw propagate(t); } @Override URI createOrPropagate(Throwable t); @Override EndpointIfAlreadyExists setContext(HttpRequest request); }### Answer:
@Test public void testFoundIsNullWhenEndpointNotSet() throws Exception { assertNull(new EndpointIfAlreadyExists().createOrPropagate(new KeyAlreadyExistsException())); }
@Test(expectedExceptions = RuntimeException.class) public void testNotFoundPropagates() throws Exception { new EndpointIfAlreadyExists().createOrPropagate(new RuntimeException()); }
@Test(expectedExceptions = NullPointerException.class) public void testNullIsBad() throws Exception { new EndpointIfAlreadyExists().createOrPropagate(null); } |
### Question:
SignRequest implements HttpRequestFilter { public String createStringToSign(HttpRequest request) { utils.logRequest(signatureLog, request, ">>"); StringBuilder buffer = new StringBuilder(); appendMethod(request, buffer); appendPayloadMetadata(request, buffer); appendHttpHeaders(request, buffer); appendCanonicalizedResource(request, buffer); appendCanonicalizedHeaders(request, buffer); if (signatureWire.enabled()) signatureWire.output(buffer.toString()); return buffer.toString(); } @Inject SignRequest(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils); @Override HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String calculateSignature(String toSign); String signString(String toSign); }### Answer:
@Test void testCreateStringToSign() throws IOException { String expects = Strings2.toStringAndClose(getClass().getResourceAsStream("/hashstring.txt")); HttpRequest request = newRequest(preconstructedHeaders().build()); String toSign = filter.createStringToSign(request); assertEquals(toSign, expects); } |
### Question:
SignRequest implements HttpRequestFilter { public String signString(String toSign) { try { ByteProcessor<byte[]> hmacSHA1 = asByteProcessor(crypto.hmacSHA1(base64().decode(creds.get().credential))); return base64().encode(readBytes(toInputStream(toSign), hmacSHA1)); } catch (Exception e) { throw new HttpException("error signing request", e); } } @Inject SignRequest(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils); @Override HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String calculateSignature(String toSign); String signString(String toSign); }### Answer:
@Test void testSignString() throws IOException, NoSuchAlgorithmException, InvalidKeyException { HttpRequest request = newRequest(preconstructedHeaders().build()); String toSign = filter.createStringToSign(request); String signature = filter.signString(toSign); assertEquals(signature, EXPECTED_SIGNATURE); } |
### Question:
SignRequest implements HttpRequestFilter { @Override public HttpRequest filter(HttpRequest request) throws HttpException { Builder<String, String> builder = ImmutableMap.builder(); builder.put(AtmosHeaders.UID, creds.get().identity); String date = timeStampProvider.get(); builder.put(HttpHeaders.DATE, date); if (request.getHeaders().containsKey(AtmosHeaders.DATE)) builder.put(AtmosHeaders.DATE, date); request = request.toBuilder().replaceHeaders(Multimaps.forMap(builder.build())).build(); String signature = calculateSignature(createStringToSign(request)); request = request.toBuilder().replaceHeader(AtmosHeaders.SIGNATURE, signature).build(); utils.logRequest(signatureLog, request, "<<"); return request; } @Inject SignRequest(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils); @Override HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String calculateSignature(String toSign); String signString(String toSign); }### Answer:
@Test void testFilter() throws IOException, NoSuchAlgorithmException, InvalidKeyException { HttpRequest request = newRequest(inputHeaders().build()); request = filter.filter(request); assertEquals(request.getFirstHeaderOrNull(AtmosHeaders.SIGNATURE), EXPECTED_SIGNATURE); }
@Test void testFilterReplacesOldValues() throws IOException, NoSuchAlgorithmException, InvalidKeyException { HttpRequest request = newRequest(inputHeaders().put(AtmosHeaders.SIGNATURE, "foo") .put(HttpHeaders.DATE, "foo").put(AtmosHeaders.DATE, "foo").put(AtmosHeaders.UID, "foo") .build()); request = filter.filter(request); assertEquals(request.getFirstHeaderOrNull(AtmosHeaders.SIGNATURE), EXPECTED_SIGNATURE); } |
### Question:
CredentialTypes { public static <T> String credentialTypeOf(T input) { Class<?> authenticationType = input.getClass(); CredentialType credentialType = findCredentialType(authenticationType); checkArgument(credentialType != null, "programming error: %s should have annotation %s", authenticationType, CredentialType.class.getName()); return credentialType.value(); } static String credentialTypeOf(T input); static Map<String, T> indexByCredentialType(Iterable<T> iterable); static CredentialType findCredentialType(Class<?> input); static final String API_ACCESS_KEY_CREDENTIALS; static final String PASSWORD_CREDENTIALS; static final String TOKEN_CREDENTIALS; }### Answer:
@Test(expectedExceptions = IllegalArgumentException.class) public void testCredentialTypeOfWithoutAnnotation() { CredentialTypes.credentialTypeOf(""); } |
### Question:
CredentialTypes { public static <T> Map<String, T> indexByCredentialType(Iterable<T> iterable) { return Maps.uniqueIndex(iterable, new Function<T, String>() { @Override public String apply(T input) { return credentialTypeOf(input); } }); } static String credentialTypeOf(T input); static Map<String, T> indexByCredentialType(Iterable<T> iterable); static CredentialType findCredentialType(Class<?> input); static final String API_ACCESS_KEY_CREDENTIALS; static final String PASSWORD_CREDENTIALS; static final String TOKEN_CREDENTIALS; }### Answer:
@Test(expectedExceptions = IllegalArgumentException.class) public void testIndexByCredentialTypeWithoutAnnotation() { CredentialTypes.indexByCredentialType(ImmutableSet.of("")); } |
### Question:
UpdateCDNContainerOptions extends BaseHttpRequestOptions { public UpdateCDNContainerOptions ttl(int ttl) { checkState(ttl >= Integer.valueOf(CDN_TTL_MIN), "ttl must be >= " + CDN_TTL_MIN); checkState(ttl <= Integer.valueOf(CDN_TTL_MAX), "ttl must be <= " + CDN_TTL_MAX); headers.put(CDN_TTL, Integer.toString(ttl)); return this; } UpdateCDNContainerOptions ttl(int ttl); UpdateCDNContainerOptions logRetention(boolean logRetention); UpdateCDNContainerOptions enabled(boolean enabled); UpdateCDNContainerOptions staticWebsiteDirectoryType(MediaType directoryType); UpdateCDNContainerOptions staticWebsiteErrorPage(String errorPage); UpdateCDNContainerOptions staticWebsiteIndexPage(String indexPage); UpdateCDNContainerOptions staticWebsiteListings(boolean listings); UpdateCDNContainerOptions staticWebsiteListingsCSS(String listingsCSS); static final UpdateCDNContainerOptions NONE; }### Answer:
@SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void testTTLLessThanMin() { UpdateCDNContainerOptions options = new UpdateCDNContainerOptions().ttl(CDN_TTL_MIN - 1); options.buildRequestHeaders().get(CDN_TTL); }
@SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void testTTLGreaterThanMax() { UpdateCDNContainerOptions options = new UpdateCDNContainerOptions().ttl(CDN_TTL_MAX + 1); options.buildRequestHeaders().get(CDN_TTL); } |
### Question:
CreateNodeAndPopulateAutomaticAttributesImpl implements CreateNodeAndPopulateAutomaticAttributes { @Override public Node execute(Node node) { logger.trace("creating node %s", node.getName()); Node withAutomatic = Node.builder() .name(node.getName()) .normalAttributes(node.getNormalAttributes()) .overrideAttributes(node.getOverrideAttributes()) .defaultAttributes(node.getDefaultAttributes()) .automaticAttributes(node.getAutomaticAttributes()) .automaticAttributes(automaticSupplier.get()) .runList(node.getRunList()) .environment(node.getEnvironment()) .build(); chef.createNode(withAutomatic); logger.debug("created node %s", withAutomatic.getName()); return node; } @Inject CreateNodeAndPopulateAutomaticAttributesImpl(ChefApi chef,
@Automatic Supplier<Map<String, JsonBall>> automaticSupplier); @Override Node execute(Node node); @Override Node execute(String nodeName, Iterable<String> runList); }### Answer:
@Test public void testWithNoRunlist() { ChefApi chef = createMock(ChefApi.class); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(ImmutableMap.<String, JsonBall> of()); Node nodeWithAutomatic = Node.builder().name("name").environment("_default") .automaticAttributes(automaticSupplier.get()).build(); chef.createNode(nodeWithAutomatic); replay(chef); CreateNodeAndPopulateAutomaticAttributesImpl updater = new CreateNodeAndPopulateAutomaticAttributesImpl(chef, automaticSupplier); updater.execute("name", ImmutableSet.<String> of()); verify(chef); } |
### Question:
UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttributesOnNode { @Override public void execute(String nodeName) { logger.trace("updating node %s", nodeName); Node node = chef.getNode(nodeName); Node updated = Node.builder() .name(node.getName()) .normalAttributes(node.getNormalAttributes()) .overrideAttributes(node.getOverrideAttributes()) .defaultAttributes(node.getDefaultAttributes()) .automaticAttributes(automaticSupplier.get()) .runList(node.getRunList()) .environment(node.getEnvironment()) .build(); chef.updateNode(updated); logger.debug("updated node %s", nodeName); } @Inject UpdateAutomaticAttributesOnNodeImpl(ChefApi chef, @Automatic Supplier<Map<String, JsonBall>> automaticSupplier); @Override void execute(String nodeName); }### Answer:
@Test public void test() { ChefApi chef = createMock(ChefApi.class); Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of(); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); Node node = Node.builder().name("name").environment("_default").build(); Node nodeWithAutomatic = Node.builder().name("name").environment("_default").automaticAttributes(automatic) .build(); expect(chef.getNode("name")).andReturn(node); expect(chef.updateNode(nodeWithAutomatic)).andReturn(null); replay(chef); UpdateAutomaticAttributesOnNodeImpl updater = new UpdateAutomaticAttributesOnNodeImpl(chef, automaticSupplier); updater.execute("name"); verify(chef); } |
### Question:
UriForResource implements Function<Object, URI> { @Override public URI apply(Object input) { checkArgument(checkNotNull(input, "input") instanceof Resource, "This function can only be applied to Resource objects"); return ((Resource) input).getUrl(); } @Override URI apply(Object input); }### Answer:
@Test public void testWithValidResource() { Function<Object, URI> function = new UriForResource(); Resource res = Resource.builder().name("test").url(URI.create("http: URI result = function.apply(res); assertEquals(res.getUrl().toString(), result.toString()); }
@Test(expectedExceptions = NullPointerException.class) public void testWithNullInput() { Function<Object, URI> function = new UriForResource(); function.apply(null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testWithInvalidInput() { Function<Object, URI> function = new UriForResource(); function.apply(new Object()); }
@Test public void testWithValidResource() { Function<Object, URI> function = new UriForResource(); Resource res = new Resource("test", URI.create("http: URI result = function.apply(res); assertEquals(res.getUrl().toString(), result.toString()); } |
### Question:
SignedHeaderAuth implements HttpRequestFilter { @VisibleForTesting String canonicalPath(String path) { path = path.replaceAll("\\/+", "/"); return path.endsWith("/") && path.length() > 1 ? path.substring(0, path.length() - 1) : path; } @Inject SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils, Crypto crypto); HttpRequest filter(HttpRequest input); String createStringToSign(String request, String hashedPath, String contentHash, String timestamp); String sign(String toSign); static final String SIGNING_DESCRIPTION; }### Answer:
@Test void canonicalizedPathRemovesMultipleSlashes() { assertEquals(signing_obj.canonicalPath(" }
@Test void canonicalizedPathRemovesTrailingSlash() { assertEquals(signing_obj.canonicalPath("/path/"), "/path"); } |
### Question:
Role { public static Builder builder() { return new Builder(); } @ConstructorProperties({ "name", "description", "default_attributes", "run_list", "override_attributes", "env_run_lists" }) protected Role(String name, String description, @Nullable Map<String, JsonBall> defaultAttributes,
@Nullable List<String> runList, @Nullable Map<String, JsonBall> overrideAttributes,
@Nullable Map<String, List<String>> envRunList); static Builder builder(); String getName(); String getDescription(); Map<String, JsonBall> getOverrideAttributes(); Map<String, JsonBall> getDefaultAttributes(); List<String> getRunList(); Map<String, List<String>> getEnvRunList(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void canNotAddEnvRunListMapThatIsNull() { Role.builder().envRunList((Map<String, List<String>>) null); }
@Test(expectedExceptions = NullPointerException.class) public void canNotAddRunListForEnvironmentThatIsNull() { Role.builder().envRunList("does.not.matter", (List<String>) null); }
@Test(expectedExceptions = NullPointerException.class) public void canNotUseNullEnvNameWhenAddingEnvRunListEntry() { Role.builder().envRunListElement((String) null, "does.not.matter"); }
@Test(expectedExceptions = NullPointerException.class) public void canNotUseNullEntryWhenAddingEnvRunListEntry() { Role.builder().envRunListElement("does.not.matter", (String) null); } |
### Question:
ParseCredentialsFromJsonResponse implements
Function<HttpResponse, Credentials> { @Override public Credentials apply(HttpResponse input) { Map<String, Credentials> returnVal = parser.apply(input); checkState(!(returnVal.size() > 1), "expecting only 1 credential in response, but had more: " + returnVal.keySet()); return (!returnVal.isEmpty()) ? Iterables.getOnlyElement(returnVal.values()) : null; } @Inject ParseCredentialsFromJsonResponse(
ParseServerNameToCredentialsMapFromJsonResponse parser); @Override Credentials apply(HttpResponse input); }### Answer:
@Test(expectedExceptions = IllegalStateException.class) public void testFailWhenTooManyPasswords() throws UnknownHostException { InputStream is = getClass().getResourceAsStream("/test_credentials_list.json"); HttpResponse response = HttpResponse.builder().statusCode(200).message("ok").payload(is).build(); ParseCredentialsFromJsonResponse parser = i.getInstance(ParseCredentialsFromJsonResponse.class); parser.apply(response); }
@Test public void testValid() throws UnknownHostException { InputStream is = getClass().getResourceAsStream("/test_credential.json"); HttpResponse response = HttpResponse.builder().statusCode(200).message("ok").payload(is).build(); ParseCredentialsFromJsonResponse parser = i.getInstance(ParseCredentialsFromJsonResponse.class); Credentials creds = parser.apply(response); assertEquals(creds.identity, "root"); assertEquals(creds.credential, "zot40ced"); } |
### Question:
TagToJson implements Binder { @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(input instanceof Set); Set<String> tags = Set.class.cast(checkNotNull(input, "input")); request.setPayload(buildJson(tags)); return request; } @Inject TagToJson(Json json); @Override R bindToRequest(R request, Object input); }### Answer:
@Test public void testVirtualGuestWithOperatingSystem() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("https: TagToJson binder = new TagToJson(json); Set<String> tags = ImmutableSet.of("jclouds"); request = binder.bindToRequest(request, tags); assertEquals(request.getPayload().getRawContent(), "{\"parameters\":[\"jclouds\"]}"); } |
### Question:
OperatingSystems { public static Function<String, OsFamily> osFamily() { return new Function<String, OsFamily>() { @Override public OsFamily apply(final String description) { if (description != null) { if (description.startsWith(CENTOS)) return OsFamily.CENTOS; else if (description.startsWith(DEBIAN)) return OsFamily.DEBIAN; else if (description.startsWith(RHEL)) return OsFamily.RHEL; else if (description.startsWith(UBUNTU)) return OsFamily.UBUNTU; else if (description.startsWith(WINDOWS)) return OsFamily.WINDOWS; else if (description.startsWith(CLOUD_LINUX)) return OsFamily.CLOUD_LINUX; else if (description.startsWith(VYATTACE)) return OsFamily.LINUX; } return OsFamily.UNRECOGNIZED; } }; } static Function<String, OsFamily> osFamily(); static Function<String, Integer> bits(); static Function<String, String> version(); }### Answer:
@Test public void testOsFamily() { assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.CENTOS), OsFamily.CENTOS); assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.DEBIAN), OsFamily.DEBIAN); assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.RHEL), OsFamily.RHEL); assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.UBUNTU), OsFamily.UBUNTU); assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.WINDOWS), OsFamily.WINDOWS); assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.CLOUD_LINUX), OsFamily.CLOUD_LINUX); assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.VYATTACE), OsFamily.LINUX); } |
### Question:
OperatingSystems { public static Function<String, Integer> bits() { return new Function<String, Integer>() { @Override public Integer apply(String operatingSystemReferenceCode) { if (operatingSystemReferenceCode != null) { return Ints.tryParse(getLast(Splitter.on("_").split(operatingSystemReferenceCode))); } return null; } }; } static Function<String, OsFamily> osFamily(); static Function<String, Integer> bits(); static Function<String, String> version(); }### Answer:
@Test public void testOsBits() { assertEquals(OperatingSystems.bits().apply("UBUNTU_12_64").intValue(), 64); assertEquals(OperatingSystems.bits().apply("UBUNTU_12_32").intValue(), 32); } |
### Question:
OperatingSystems { public static Function<String, String> version() { return new Function<String, String>() { @Override public String apply(final String version) { return parseVersion(version); } }; } static Function<String, OsFamily> osFamily(); static Function<String, Integer> bits(); static Function<String, String> version(); }### Answer:
@Test public void testOsVersion() { assertEquals(OperatingSystems.version().apply("12.04-64 Minimal for VSI"), "12.04"); assertEquals(OperatingSystems.version().apply("STD 32 bit"), "STD"); } |
### Question:
VirtualGuestToHardware implements Function<VirtualGuest, Hardware> { @Override public Hardware apply(final VirtualGuest from) { HardwareBuilder builder = new HardwareBuilder().ids(from.getId() + "") .name(from.getHostname()) .hypervisor("XenServer") .processors(ImmutableList.of(new Processor(from.getStartCpus(), 2))) .ram(from.getMaxMemory()); if (from.getVirtualGuestBlockDevices() != null) { builder.volumes( FluentIterable.from(from.getVirtualGuestBlockDevices()).filter(new Predicate<VirtualGuestBlockDevice>() { @Override public boolean apply(VirtualGuestBlockDevice input) { return input.getMountType().equals("Disk"); } }) .transform(new Function<VirtualGuestBlockDevice, Volume>() { @Override public Volume apply(VirtualGuestBlockDevice item) { float volumeSize = -1; if (item.getVirtualDiskImage() != null) { volumeSize = item.getVirtualDiskImage().getCapacity(); } return new VolumeImpl( item.getId() + "", from.isLocalDiskFlag() ? Volume.Type.LOCAL : Volume.Type.SAN, volumeSize, null, item.getBootableFlag() == 1, false); } }).toSet()); } return builder.build(); } @Override Hardware apply(final VirtualGuest from); }### Answer:
@Test public void testVirtualGuestToHardware() { VirtualGuest virtualGuest = createVirtualGuest(); Hardware hardware = new VirtualGuestToHardware().apply(virtualGuest); assertNotNull(hardware); assertEquals(hardware.getRam(), virtualGuest.getMaxMemory()); assertTrue(hardware.getProcessors().size() == 1); assertEquals(Iterables.get(hardware.getProcessors(), 0).getCores(), (double) virtualGuest.getStartCpus()); } |
### Question:
DatacenterToLocation implements Function<Datacenter, Location> { @Inject public DatacenterToLocation(JustProvider provider) { this.provider = checkNotNull(provider, "provider"); } @Inject DatacenterToLocation(JustProvider provider); @Override Location apply(Datacenter datacenter); }### Answer:
@Test public void testDatacenterToLocation() { Address address = Address.builder().country("US").state("TX").description("This is Texas!").build(); Datacenter datacenter = Datacenter.builder().id(1).name("Texas").longName("Texas Datacenter") .locationAddress(address).build(); Location location = function.apply(datacenter); assertEquals(location.getId(), datacenter.getName()); Set<String> iso3166Codes = location.getIso3166Codes(); assertEquals(iso3166Codes.size(), 1); assertTrue(iso3166Codes.contains("US-TX")); } |
### Question:
Address { public static Builder<?> builder() { return new ConcreteBuilder(); } @ConstructorProperties({ "id", "country", "state", "description", "accountId", "address1", "city", "contactName", "isActive", "locationId", "postalCode" }) protected Address(int id, String country, @Nullable String state, @Nullable String description, int accountId,
@Nullable String address, @Nullable String city, @Nullable String contactName,
int isActive, int locationId, @Nullable String postalCode); static Builder<?> builder(); Builder<?> toBuilder(); int getId(); String getCountry(); @Nullable String getState(); @Nullable String getDescription(); int getAccountId(); @Nullable String getAddress1(); @Nullable String getCity(); @Nullable String getContactName(); int isActive(); int getLocationId(); @Nullable String getPostalCode(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test(expectedExceptions = java.lang.NullPointerException.class ) public void testConstructionWithEmpty() { Address.builder().country(null).build(); }
@Test(expectedExceptions = java.lang.NullPointerException.class ) public void testConstructionWithNoCountry() { Address.builder().country("").build(); } |
### Question:
ImportOrReturnExistingKeypair implements Function<RegionNameAndPublicKeyMaterial, KeyPair> { @Override public KeyPair apply(RegionNameAndPublicKeyMaterial from) { return importOrReturnExistingKeypair(from.getRegion(), from.getName(), from.getPublicKeyMaterial()); } @Inject ImportOrReturnExistingKeypair(AWSEC2Api ec2Api); @Override KeyPair apply(RegionNameAndPublicKeyMaterial from); KeyPair addFingerprintToKeyPair(String publicKeyMaterial, KeyPair keyPair); }### Answer:
@Test public void testApply() { AWSEC2Api client = createMock(AWSEC2Api.class); AWSKeyPairApi keyApi = createMock(AWSKeyPairApi.class); expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyApi)).atLeastOnce(); expect(keyApi.importKeyPairInRegion("region", "jclouds#group", PUBLIC_KEY)).andReturn(pair); replay(client); replay(keyApi); ImportOrReturnExistingKeypair parser = new ImportOrReturnExistingKeypair(client); assertEquals(parser.importOrReturnExistingKeypair("region", "group", PUBLIC_KEY), pairWithFingerprint); verify(client); verify(keyApi); } |
### Question:
AWSEC2IOExceptionRetryHandler extends BackoffLimitedRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, IOException error) { HttpRequest request = command.getCurrentRequest(); if ("POST".equals(request.getMethod())) { Payload payload = request.getPayload(); if (!payload.getRawContent().toString().contains(DESCRIBE_ACTION)){ logger.error("Command not considered safe to retry because request method is POST and action may not be idempotent: %1$s", command); return false; } } return super.shouldRetryRequest(command, error); } @Override boolean shouldRetryRequest(HttpCommand command, IOException error); }### Answer:
@Test public void testDescribeMethodIsRetried() throws Exception { AWSEC2IOExceptionRetryHandler handler = new AWSEC2IOExceptionRetryHandler(); IOException e = new IOException("test exception"); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: HttpCommand command = new HttpCommand(request); assertTrue(handler.shouldRetryRequest(command, e)); }
@Test public void testNonDescribeMethodIsNotRetried() throws Exception { AWSEC2IOExceptionRetryHandler handler = new AWSEC2IOExceptionRetryHandler(); IOException e = new IOException("test exception"); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: HttpCommand command = new HttpCommand(request); assertFalse(handler.shouldRetryRequest(command, e)); } |
### Question:
AWSEC2ComputeServiceContextModule extends BaseComputeServiceContextModule { protected Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader( final RegionAndIdToImage delegate) { return Suppliers.<CacheLoader<RegionAndName, Image>>ofInstance(new CacheLoader<RegionAndName, Image>() { private final AtomicReference<AuthorizationException> authException = Atomics.newReference(); @Override public Image load(final RegionAndName key) throws Exception { Supplier<Image> rawSupplier = new Supplier<Image>() { @Override public Image get() { try { return delegate.load(key); } catch (ExecutionException e) { throw Throwables.propagate(e); } } }; return new SetAndThrowAuthorizationExceptionSupplier<Image>(rawSupplier, authException).get(); } }); } }### Answer:
@Test public void testCacheLoaderDoesNotReloadAfterAuthorizationException() throws Exception { AWSEC2ComputeServiceContextModule module = new AWSEC2ComputeServiceContextModule() { public Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(RegionAndIdToImage delegate) { return super.provideRegionAndNameToImageSupplierCacheLoader(delegate); } }; RegionAndName regionAndName = new RegionAndName("myregion", "myname"); AuthorizationException authException = new AuthorizationException(); RegionAndIdToImage mockRegionAndIdToImage = createMock(RegionAndIdToImage.class); expect(mockRegionAndIdToImage.load(regionAndName)).andThrow(authException).once(); replay(mockRegionAndIdToImage); CacheLoader<RegionAndName, Image> cacheLoader = module.provideRegionAndNameToImageSupplierCacheLoader(mockRegionAndIdToImage).get(); for (int i = 0; i < 2; i++) { try { Image image = cacheLoader.load(regionAndName); fail("Expected Authorization exception, but got " + image); } catch (AuthorizationException e) { } } } |
### Question:
BindMapToHeadersWithPrefix 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 Maps!"); checkNotNull(request, "request"); Map<String, String> userMetadata = Maps2.transformKeys((Map<String, String>) input, fn); return (R) request.toBuilder().replaceHeaders(Multimaps.forMap(userMetadata)).build(); } @Inject BindMapToHeadersWithPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) final String metadataPrefix); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }### Answer:
@Test public void testCorrect() throws SecurityException, NoSuchMethodException { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); assertEquals( binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")), HttpRequest.builder().method("GET").endpoint("http: .addHeader("prefix:imagename", "foo") .addHeader("prefix:serverid", "2").build()); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeMap() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: binder.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:
IdReference { public static String extractResourceGroup(String uri) { if (uri == null) return null; Matcher m = RESOURCE_GROUP_PATTERN.matcher(uri); return m.matches() ? m.group(1) : null; } @Nullable abstract String id(); @Nullable String resourceGroup(); @Nullable String name(); @SerializedNames({"id"}) static IdReference create(final String id); static String extractName(String uri); static String extractResourceGroup(String uri); }### Answer:
@Test public void testExtractResourceGroup() { assertEquals(extractResourceGroup(null), null); assertEquals(extractResourceGroup(""), null); assertEquals( extractResourceGroup("/subscriptions/subscription/resourceGroups/jclouds-northeurope/providers/Microsoft.Compute/virtualMachines/resources-8c5"), "jclouds-northeurope"); assertEquals(extractResourceGroup("/subscriptions/subscription/resourceGroups/jclouds-west"), "jclouds-west"); assertEquals(extractResourceGroup("/resourceGroups/jclouds-west2"), "jclouds-west2"); assertEquals( extractResourceGroup("/resourceGroups/jclouds-northeurope2/providers/Microsoft.Compute/virtualMachines/resources-8c5"), "jclouds-northeurope2"); assertEquals(extractResourceGroup("resourceGroups/jclouds-west2"), null); assertEquals( extractResourceGroup("resourceGroups/jclouds-northeurope2/providers/Microsoft.Compute/virtualMachines/resources-8c5"), null); assertEquals( extractResourceGroup("/subscriptions/subscription/providers/Microsoft.Compute/virtualMachines/resources-8c5"), null); assertEquals( extractResourceGroup("/subscriptions/subscription/resourceGroups null); } |
### Question:
IdReference { public static String extractName(String uri) { if (uri == null) return null; String noSlashAtEnd = uri.replaceAll("/+$", ""); return noSlashAtEnd.substring(noSlashAtEnd.lastIndexOf('/') + 1); } @Nullable abstract String id(); @Nullable String resourceGroup(); @Nullable String name(); @SerializedNames({"id"}) static IdReference create(final String id); static String extractName(String uri); static String extractResourceGroup(String uri); }### Answer:
@Test public void testExtractName() { assertEquals(extractName(null), null); assertEquals(extractName(""), ""); assertEquals(extractName("foo"), "foo"); assertEquals(extractName("/foo/bar"), "bar"); assertEquals(extractName("/foo/bar/"), "bar"); assertEquals(extractName("/foo/bar assertEquals(extractName("/foo assertEquals(extractName(" } |
### Question:
Subnet { public static String extractVirtualNetwork(String id) { if (id == null) return null; Matcher m = NETWORK_PATTERN.matcher(id); m.matches(); return m.group(1); } Subnet(); @Nullable abstract String name(); @Nullable abstract String id(); @Nullable abstract String etag(); @Nullable abstract SubnetProperties properties(); @Nullable String virtualNetwork(); static String extractVirtualNetwork(String id); @SerializedNames({"name", "id", "etag", "properties"}) static Subnet create(final String name,
final String id,
final String etag,
final SubnetProperties properties); abstract Builder toBuilder(); static Builder builder(); static final String GATEWAY_SUBNET_NAME; }### Answer:
@Test public void testExtractVirtualNetwork() { assertEquals(Subnet.builder().build().virtualNetwork(), null); assertEquals( Subnet.builder() .id("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vn/subnets/subnet") .build().virtualNetwork(), "vn"); assertInvalidId("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks"); assertInvalidId("virtualNetworks/vn"); } |
### Question:
GleSYSTemplateOptions extends TemplateOptions implements Cloneable { public String getIp() { return ip; } @Override GleSYSTemplateOptions clone(); @Override void copyTo(TemplateOptions to); GleSYSTemplateOptions ip(String ip); String getIp(); GleSYSTemplateOptions rootPassword(String rootPassword); String getRootPassword(); boolean hasRootPassword(); GleSYSTemplateOptions transferGB(int transferGB); int getTransferGB(); @Override GleSYSTemplateOptions blockOnPort(int port, int seconds); @Override GleSYSTemplateOptions inboundPorts(int... ports); @Override GleSYSTemplateOptions authorizePublicKey(String publicKey); @Override GleSYSTemplateOptions installPrivateKey(String privateKey); @Override GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata); @Override GleSYSTemplateOptions userMetadata(String key, String value); @Override GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames); @Override GleSYSTemplateOptions networks(Iterable<String> networks); @Override ToStringHelper string(); }### Answer:
@Test public void testDefaultip() { TemplateOptions options = new GleSYSTemplateOptions(); assertEquals(options.as(GleSYSTemplateOptions.class).getIp(), "any"); } |
### Question:
GleSYSTemplateOptions extends TemplateOptions implements Cloneable { public GleSYSTemplateOptions ip(String ip) { checkNotNull(ip); checkArgument("any".equals(ip) || InetAddresses.isInetAddress(ip), "ip %s is not valid", ip); this.ip = ip; return this; } @Override GleSYSTemplateOptions clone(); @Override void copyTo(TemplateOptions to); GleSYSTemplateOptions ip(String ip); String getIp(); GleSYSTemplateOptions rootPassword(String rootPassword); String getRootPassword(); boolean hasRootPassword(); GleSYSTemplateOptions transferGB(int transferGB); int getTransferGB(); @Override GleSYSTemplateOptions blockOnPort(int port, int seconds); @Override GleSYSTemplateOptions inboundPorts(int... ports); @Override GleSYSTemplateOptions authorizePublicKey(String publicKey); @Override GleSYSTemplateOptions installPrivateKey(String privateKey); @Override GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata); @Override GleSYSTemplateOptions userMetadata(String key, String value); @Override GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames); @Override GleSYSTemplateOptions networks(Iterable<String> networks); @Override ToStringHelper string(); }### Answer:
@Test public void testip() { TemplateOptions options = new GleSYSTemplateOptions().ip("1.1.1.1"); assertEquals(options.as(GleSYSTemplateOptions.class).getIp(), "1.1.1.1"); }
@Test(expectedExceptions = NullPointerException.class) public void testNullIpThrowsNPE() { new GleSYSTemplateOptions().ip(null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidIpThrowsIllegalArgument() { new GleSYSTemplateOptions().ip("1.1.1"); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testipIsInvalidThrowsIllegalArgument() { new GleSYSTemplateOptions().ip("foo"); } |
### Question:
GleSYSTemplateOptions extends TemplateOptions implements Cloneable { public String getRootPassword() { return rootPassword; } @Override GleSYSTemplateOptions clone(); @Override void copyTo(TemplateOptions to); GleSYSTemplateOptions ip(String ip); String getIp(); GleSYSTemplateOptions rootPassword(String rootPassword); String getRootPassword(); boolean hasRootPassword(); GleSYSTemplateOptions transferGB(int transferGB); int getTransferGB(); @Override GleSYSTemplateOptions blockOnPort(int port, int seconds); @Override GleSYSTemplateOptions inboundPorts(int... ports); @Override GleSYSTemplateOptions authorizePublicKey(String publicKey); @Override GleSYSTemplateOptions installPrivateKey(String privateKey); @Override GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata); @Override GleSYSTemplateOptions userMetadata(String key, String value); @Override GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames); @Override GleSYSTemplateOptions networks(Iterable<String> networks); @Override ToStringHelper string(); }### Answer:
@Test public void testDefaultRootPassword() { TemplateOptions options = new GleSYSTemplateOptions(); assertEquals(options.as(GleSYSTemplateOptions.class).getRootPassword(), null); } |
### Question:
GleSYSTemplateOptions extends TemplateOptions implements Cloneable { public GleSYSTemplateOptions rootPassword(String rootPassword) { checkNotNull(rootPassword, "root password cannot be null"); this.rootPassword = rootPassword; return this; } @Override GleSYSTemplateOptions clone(); @Override void copyTo(TemplateOptions to); GleSYSTemplateOptions ip(String ip); String getIp(); GleSYSTemplateOptions rootPassword(String rootPassword); String getRootPassword(); boolean hasRootPassword(); GleSYSTemplateOptions transferGB(int transferGB); int getTransferGB(); @Override GleSYSTemplateOptions blockOnPort(int port, int seconds); @Override GleSYSTemplateOptions inboundPorts(int... ports); @Override GleSYSTemplateOptions authorizePublicKey(String publicKey); @Override GleSYSTemplateOptions installPrivateKey(String privateKey); @Override GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata); @Override GleSYSTemplateOptions userMetadata(String key, String value); @Override GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames); @Override GleSYSTemplateOptions networks(Iterable<String> networks); @Override ToStringHelper string(); }### Answer:
@Test public void testRootPassword() { TemplateOptions options = new GleSYSTemplateOptions().rootPassword("secret"); assertEquals(options.as(GleSYSTemplateOptions.class).getRootPassword(), "secret"); }
@Test(expectedExceptions = NullPointerException.class) public void testNullRootPasswordThrowsNPE() { new GleSYSTemplateOptions().rootPassword(null); } |
### Question:
GleSYSTemplateOptions extends TemplateOptions implements Cloneable { public int getTransferGB() { return transferGB; } @Override GleSYSTemplateOptions clone(); @Override void copyTo(TemplateOptions to); GleSYSTemplateOptions ip(String ip); String getIp(); GleSYSTemplateOptions rootPassword(String rootPassword); String getRootPassword(); boolean hasRootPassword(); GleSYSTemplateOptions transferGB(int transferGB); int getTransferGB(); @Override GleSYSTemplateOptions blockOnPort(int port, int seconds); @Override GleSYSTemplateOptions inboundPorts(int... ports); @Override GleSYSTemplateOptions authorizePublicKey(String publicKey); @Override GleSYSTemplateOptions installPrivateKey(String privateKey); @Override GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata); @Override GleSYSTemplateOptions userMetadata(String key, String value); @Override GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames); @Override GleSYSTemplateOptions networks(Iterable<String> networks); @Override ToStringHelper string(); }### Answer:
@Test public void testDefaultTranferGB() { TemplateOptions options = new GleSYSTemplateOptions(); assertEquals(options.as(GleSYSTemplateOptions.class).getTransferGB(), 50); } |
### Question:
GleSYSTemplateOptions extends TemplateOptions implements Cloneable { public GleSYSTemplateOptions transferGB(int transferGB) { checkArgument(transferGB >= 0, "transferGB value must be >= 0", transferGB); this.transferGB = transferGB; return this; } @Override GleSYSTemplateOptions clone(); @Override void copyTo(TemplateOptions to); GleSYSTemplateOptions ip(String ip); String getIp(); GleSYSTemplateOptions rootPassword(String rootPassword); String getRootPassword(); boolean hasRootPassword(); GleSYSTemplateOptions transferGB(int transferGB); int getTransferGB(); @Override GleSYSTemplateOptions blockOnPort(int port, int seconds); @Override GleSYSTemplateOptions inboundPorts(int... ports); @Override GleSYSTemplateOptions authorizePublicKey(String publicKey); @Override GleSYSTemplateOptions installPrivateKey(String privateKey); @Override GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata); @Override GleSYSTemplateOptions userMetadata(String key, String value); @Override GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames); @Override GleSYSTemplateOptions networks(Iterable<String> networks); @Override ToStringHelper string(); }### Answer:
@Test public void testTransferGB() { TemplateOptions options = new GleSYSTemplateOptions().transferGB(75); assertEquals(options.as(GleSYSTemplateOptions.class).getTransferGB(), 75); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testNegativeTransferGBThrowsException() { new GleSYSTemplateOptions().transferGB(-1); } |
### Question:
GleSYSTemplateOptions extends TemplateOptions implements Cloneable { @Override public GleSYSTemplateOptions clone() { GleSYSTemplateOptions options = new GleSYSTemplateOptions(); copyTo(options); return options; } @Override GleSYSTemplateOptions clone(); @Override void copyTo(TemplateOptions to); GleSYSTemplateOptions ip(String ip); String getIp(); GleSYSTemplateOptions rootPassword(String rootPassword); String getRootPassword(); boolean hasRootPassword(); GleSYSTemplateOptions transferGB(int transferGB); int getTransferGB(); @Override GleSYSTemplateOptions blockOnPort(int port, int seconds); @Override GleSYSTemplateOptions inboundPorts(int... ports); @Override GleSYSTemplateOptions authorizePublicKey(String publicKey); @Override GleSYSTemplateOptions installPrivateKey(String privateKey); @Override GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata); @Override GleSYSTemplateOptions userMetadata(String key, String value); @Override GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames); @Override GleSYSTemplateOptions networks(Iterable<String> networks); @Override ToStringHelper string(); }### Answer:
@Test public void testClone() { GleSYSTemplateOptions clone = transferGB(75).rootPassword("root").ip("1.1.1.1").clone(); assertEquals(clone.getTransferGB(), 75); assertEquals(clone.getRootPassword(), "root"); assertEquals(clone.getIp(), "1.1.1.1"); } |
### Question:
SharedKeyLiteAuthentication implements HttpRequestFilter { public HttpRequest filter(HttpRequest request) throws HttpException { request = this.isSAS ? filterSAS(request, this.credential) : filterKey(request); utils.logRequest(signatureLog, request, "<<"); return request; } @Inject SharedKeyLiteAuthentication(SignatureWire signatureWire,
@org.jclouds.location.Provider Supplier<Credentials> creds, @TimeStamp Provider<String> timeStampProvider,
Crypto crypto, HttpUtils utils, @Named("sasAuth") boolean sasAuthentication); HttpRequest filter(HttpRequest request); HttpRequest filterSAS(HttpRequest request, String credential); HttpRequest filterKey(HttpRequest request); String[] cutUri(URI uri); String createStringToSign(HttpRequest request); String calculateSignature(String toSign); String signString(String toSign); }### Answer:
@Test(threadPoolSize = 3, dataProvider = "dataProvider", timeOut = 3000) 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); iterations++; assertEquals(signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION)); request = filter.filter(request); } System.out.printf("%s: %d iterations before the timestamp updated %n", Thread.currentThread().getName(), iterations); }
@Test(dataProvider = "auth-sas-data") void testFilter(HttpRequest request, SharedKeyLiteAuthentication filter, String expected) { request = filter.filter(request); assertEquals(request.getEndpoint().toString(), expected); } |
### Question:
AzureBlobHttpApiModule extends HttpApiModule<AzureBlobClient> { @Named("sasAuth") @Provides protected boolean authSAS(@org.jclouds.location.Provider Supplier<Credentials> creds) { String credential = creds.get().credential; String formattedCredential = credential.startsWith("?") ? credential.substring(1) : credential; List<String> required = ImmutableList.of("sv", "sig"); try { Map<String, String> tokens = Splitter.on('&').withKeyValueSeparator('=').split(formattedCredential); return all(required, in(tokens.keySet())); } catch (Exception ex) { return false; } } }### Answer:
@Test(dataProvider = "auth-sas-tokens") void testAuthSasNonSufficientParametersSvSe(boolean expected, String credential){ AzureBlobHttpApiModule module = new AzureBlobHttpApiModule(); Credentials creds = new Credentials("identity", credential); assertEquals(module.authSAS(Suppliers.ofInstance(creds)), expected); } |
### Question:
HttpHealthCheckCreationBinder extends BindToJsonPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { HttpHealthCheckCreationOptions options = (HttpHealthCheckCreationOptions) postParams.get("options"); String name = postParams.get("name").toString(); HttpHealthCheckBinderHelper helper = new HttpHealthCheckBinderHelper(name, options); return super.bindToRequest(request, helper); } @Inject HttpHealthCheckCreationBinder(Json jsonBinder); @Override R bindToRequest(R request, Map<String, Object> postParams); }### Answer:
@Test public void testMap() throws SecurityException, NoSuchMethodException { HttpHealthCheckCreationBinder binder = new HttpHealthCheckCreationBinder(json); HttpHealthCheckCreationOptions httpHealthCheckCreationOptions = new HttpHealthCheckCreationOptions.Builder() .timeoutSec(TIMEOUTSEC) .unhealthyThreshold(UNHEALTHYTHRESHOLD) .healthyThreshold(HEALTHYTHRESHOLD) .description(DESCRIPTION) .buildWithDefaults(); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: Map<String, Object> postParams = ImmutableMap.of("name", NAME, "options", httpHealthCheckCreationOptions); binder.bindToRequest(request, postParams); assertEquals(request.getPayload().getRawContent(), "{" + "\"name\":\"" + NAME + "\"," + "\"requestPath\":\"/\"," + "\"port\":80," + "\"checkIntervalSec\":5," + "\"timeoutSec\":" + TIMEOUTSEC + "," + "\"unhealthyThreshold\":" + UNHEALTHYTHRESHOLD + "," + "\"healthyThreshold\":" + HEALTHYTHRESHOLD + "," + "\"description\":\"" + DESCRIPTION + "\"" + "}"); assertEquals(request.getPayload().getContentMetadata().getContentType(), "application/json"); } |
### Question:
DiskCreationBinder implements MapBinder { @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { DiskCreationOptions options = (DiskCreationOptions) postParams.get("options"); Writer out = new StringWriter(); JsonWriter json = new JsonWriter(out); json.setSerializeNulls(false); try { json.beginObject(); json.name("name").value(postParams.get("name").toString()); json.name("sizeGb").value(options.sizeGb()); json.name("type").value(options.type() != null ? options.type().toString() : null); json.name("sourceSnapshot") .value(options.sourceSnapshot() != null ? options.sourceSnapshot().toString() : null); json.name("description").value(options.description()); json.endObject(); json.close(); } catch (IOException e) { throw new AssertionError(e); } request.setPayload(out.toString()); request.getPayload().getContentMetadata().setContentType("application/json"); return request; } @Override R bindToRequest(R request, Map<String, Object> postParams); @Override R bindToRequest(R request, Object input); }### Answer:
@Test public void testMap() throws SecurityException, NoSuchMethodException { DiskCreationOptions diskCreationOptions = new DiskCreationOptions.Builder() .sourceSnapshot(URI.create(FAKE_SOURCE_SNAPSHOT)).sizeGb(15).description(null).build(); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: Map<String, Object> postParams = ImmutableMap.of("name", "testName", "options", diskCreationOptions); request = binder.bindToRequest(request, postParams); assertEquals(request.getPayload().getRawContent(), "{\"name\":\"testName\",\"sizeGb\":15,\"sourceSnapshot\":\"" + FAKE_SOURCE_SNAPSHOT + "\"}"); assertEquals(request.getPayload().getContentMetadata().getContentType(), "application/json"); } |
### Question:
ForwardingRuleCreationBinder extends BindToJsonPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { ForwardingRuleCreationOptions options = (ForwardingRuleCreationOptions) postParams.get("options"); String name = postParams.get("name").toString(); ForwardingRuleCreationBinderHelper forwardingRuleCreationBinderHelper = new ForwardingRuleCreationBinderHelper(name, options); return super.bindToRequest(request, forwardingRuleCreationBinderHelper); } @Inject ForwardingRuleCreationBinder(Json jsonBinder); @Override R bindToRequest(R request, Map<String, Object> postParams); }### Answer:
@Test public void testMap() throws SecurityException, NoSuchMethodException { ForwardingRuleCreationBinder binder = new ForwardingRuleCreationBinder(json); ForwardingRuleCreationOptions forwardingRuleCreationOptions = new ForwardingRuleCreationOptions.Builder() .description(DESCRIPTION) .ipAddress(IP_ADDRESS) .ipProtocol(ForwardingRule.IPProtocol.SCTP) .portRange(PORT_RANGE) .target(TARGET) .build(); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: Map<String, Object> postParams = ImmutableMap.of("name", "testForwardingRuleName", "options", forwardingRuleCreationOptions); binder.bindToRequest(request, postParams); assertEquals(request.getPayload().getRawContent(), "{\"" + "name\":\"testForwardingRuleName\"," + "\"description\":\"" + DESCRIPTION + "\"," + "\"ipAddress\":\"" + IP_ADDRESS + "\"," + "\"ipProtocol\":\"SCTP\"," + "\"portRange\":\"" + PORT_RANGE + "\"," + "\"target\":\"" + TARGET + "\"" + "}"); assertEquals(request.getPayload().getContentMetadata().getContentType(), "application/json"); } |
### Question:
InstanceToNodeMetadata implements Function<Instance, NodeMetadata> { public static boolean isCustomMachineTypeURI(URI machineType) { return machineType.toString().contains("machineTypes/custom"); } @Inject InstanceToNodeMetadata(Map<Instance.Status, NodeMetadata.Status> toPortableNodeStatus,
GroupNamingConvention.Factory namingConvention,
LoadingCache<URI, Optional<Image>> diskURIToImage,
@Memoized Supplier<Map<URI, Hardware>> hardwares,
@Memoized Supplier<Map<URI, Location>> locationsByUri); @Override NodeMetadata apply(Instance input); static boolean isCustomMachineTypeURI(URI machineType); static Hardware machineTypeURIToCustomHardware(URI machineType); }### Answer:
@Test public void isCustomMachineTypeTest() { URI uri = URI.create("https: assertThat(isCustomMachineTypeURI(uri)).isTrue(); URI uri2 = URI.create("https: assertThat(isCustomMachineTypeURI(uri2)).isFalse(); } |
### Question:
InstanceToNodeMetadata implements Function<Instance, NodeMetadata> { public static Hardware machineTypeURIToCustomHardware(URI machineType) { String uri = machineType.toString(); String values = uri.substring(uri.lastIndexOf('/') + 8); List<String> hardwareValues = Splitter.on('-') .trimResults() .splitToList(values); return new HardwareBuilder() .id(uri) .providerId(uri) .processor(new Processor(Double.parseDouble(hardwareValues.get(0)), 1.0)) .ram(Integer.parseInt(hardwareValues.get(1))) .uri(machineType) .build(); } @Inject InstanceToNodeMetadata(Map<Instance.Status, NodeMetadata.Status> toPortableNodeStatus,
GroupNamingConvention.Factory namingConvention,
LoadingCache<URI, Optional<Image>> diskURIToImage,
@Memoized Supplier<Map<URI, Hardware>> hardwares,
@Memoized Supplier<Map<URI, Location>> locationsByUri); @Override NodeMetadata apply(Instance input); static boolean isCustomMachineTypeURI(URI machineType); static Hardware machineTypeURIToCustomHardware(URI machineType); }### Answer:
@Test public void machineTypeParserTest() { URI uri = URI.create("https: Hardware hardware = machineTypeURIToCustomHardware(uri); assertThat(hardware.getRam()).isEqualTo(1024); assertThat(hardware.getProcessors().get(0).getCores()).isEqualTo(1); assertThat(hardware.getUri()) .isEqualTo(URI.create("https: assertThat(hardware.getId()) .isEqualTo("https: } |
### Question:
InputParamValidator { public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) { try { performMethodValidation(checkNotNull(invocation, "invocation")); performParameterValidation(invocation, checkNotNull(parameters, "parameters")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Validation on '%s' didn't pass:%n Reason: %s.", parameters, e.getMessage()), e); } } @Inject InputParamValidator(Injector injector); InputParamValidator(); void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters); }### Answer:
@Test(expectedExceptions = ClassCastException.class) public void testWrongPredicateTypeLiteral() throws Exception { Invocation invocation = Invocation.create(method(WrongValidator.class, "method", Integer.class), ImmutableList.<Object> of(55)); new InputParamValidator(injector).validateMethodParametersOrThrow(invocation, invocation.getInvokable().getParameters()); } |
### Question:
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier,
@Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }### Answer:
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "^Invalid PEM: no parsers for marker -----BEGIN FOO PRIVATE KEY----- .*") public void testPrivateKeySpecFromPemWithInvalidMarker() throws IOException { Pems.privateKeySpec(ByteSource.wrap(INVALID_PRIVATE_KEY.getBytes(Charsets.UTF_8))); }
@Test public void testPrivateKeySpecFromPem() throws IOException { Pems.privateKeySpec(ByteSource.wrap(PRIVATE_KEY.getBytes(Charsets.UTF_8))); } |
### Question:
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier,
@Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }### Answer:
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "^Invalid PEM: no parsers for marker -----BEGIN FOO PUBLIC KEY----- .*") public void testPublicKeySpecFromPemWithInvalidMarker() throws IOException { Pems.publicKeySpec(ByteSource.wrap(INVALID_PUBLIC_KEY.getBytes(Charsets.UTF_8))); }
@Test public void testPublicKeySpecFromPem() throws IOException { Pems.publicKeySpec(ByteSource.wrap(PUBLIC_KEY.getBytes(Charsets.UTF_8))); } |
### Question:
GetOptions extends BaseHttpRequestOptions { public String getRange() { return (!ranges.isEmpty()) ? String.format("bytes=%s", Joiner.on(",").join(ranges)) : null; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }### Answer:
@Test public void testNullRange() { GetOptions options = new GetOptions(); assertNull(options.getRange()); } |
### Question:
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }### Answer:
@Test public void testIfETagMatches() { GetOptions options = new GetOptions(); options.ifETagMatches(etag); matchesHex(options.getIfMatch()); }
@Test(expectedExceptions = NullPointerException.class) public void testIfETagMatchesNPE() { ifETagMatches(null); } |
### Question:
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }### Answer:
@Test public void testIfETagDoesntMatch() { GetOptions options = new GetOptions(); options.ifETagDoesntMatch(etag); matchesHex(options.getIfNoneMatch()); }
@Test(expectedExceptions = NullPointerException.class) public void testIfETagDoesntMatchNPE() { ifETagDoesntMatch(null); } |
### Question:
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>,
InvocationContext<ParseSystemAndUserMetadataFromHeaders> { @VisibleForTesting void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry<String, String> header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().toLowerCase().startsWith(metadataPrefix)) metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), header.getValue()); } } @Inject ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser,
@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); MutableBlobMetadata apply(HttpResponse from); ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request); ParseSystemAndUserMetadataFromHeaders setName(String name); }### Answer:
@Test public void testAddUserMetadataTo() { HttpResponse from = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader("prefix" + "key", "value").build(); MutableBlobMetadata metadata = blobMetadataProvider.get(); parser.addUserMetadataTo(from, metadata); assertEquals(metadata.getUserMetadata().get("key"), "value"); } |
### Question:
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } String apply(Blob input); }### Answer:
@Test public void testCorrect() throws SecurityException, NoSuchMethodException { Blob blob = BLOB_FACTORY.create(null); blob.getMetadata().setName("foo"); assertEquals(fn.apply(blob), "foo"); }
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { fn.apply(null); } |
### Question:
Suppliers2 { public static <K, V> Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input) { return new Supplier<V>() { @Override public V get() { Supplier<V> last = Iterables.getLast(input.get().values()); return last != null ? last.get() : null; } @Override public String toString() { return "getLastValueInMap()"; } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); }### Answer:
@Test public void testGetLastValueInMap() { assertEquals( Suppliers2.<String, String> getLastValueInMap( Suppliers.<Map<String, Supplier<String>>> ofInstance(ImmutableMap.of("foo", Suppliers.ofInstance("bar")))).get(), "bar"); } |
### Question:
Suppliers2 { public static <K, V> Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue) { return new Supplier<V>() { @Override public V get() { Map<K, Supplier<V>> map = input.get(); return map.containsKey(keyValue) ? map.get(keyValue).get() : null; } @Override public String toString() { return String.format("getValueInMapOrNull('%1$s')", keyValue); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); }### Answer:
@Test public void testGetSpecificValueInMap() { Supplier<Map<String, Supplier<String>>> testMap = Suppliers.<Map<String, Supplier<String>>> ofInstance( ImmutableMap.of("foo", Suppliers.ofInstance("bar"))); assertEquals(Suppliers2.<String, String> getValueInMapOrNull(testMap, "foo").get(), "bar"); assertEquals(Suppliers2.<String, String> getValueInMapOrNull(testMap, "baz").get(), null); } |
### Question:
Suppliers2 { public static <X> Function<X, Supplier<X>> ofInstanceFunction() { return new Function<X, Supplier<X>>() { @Override public Supplier<X> apply(X arg0) { return Suppliers.ofInstance(arg0); } @Override public String toString() { return "Suppliers.ofInstance()"; } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); }### Answer:
@Test public void testOfInstanceFunction() { assertEquals(Suppliers2.ofInstanceFunction().apply("foo").get(), "foo"); } |
### Question:
Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); }### Answer:
@Test public void testOrWhenFirstNull() { assertEquals(Suppliers2.or(Suppliers.<String> ofInstance(null), Suppliers.ofInstance("foo")).get(), "foo"); }
@Test public void testOrWhenFirstNotNull() { assertEquals(Suppliers2.or(Suppliers.<String> ofInstance("foo"), Suppliers.ofInstance("bar")).get(), "foo"); } |
### Question:
PasswordGenerator { public String generate() { StringBuilder sb = new StringBuilder(); sb.append(lower.fragment()); sb.append(upper.fragment()); sb.append(numbers.fragment()); sb.append(symbols.fragment()); return shuffleAndJoin(sb.toString().toCharArray()); } Config lower(); Config upper(); Config numbers(); Config symbols(); String generate(); }### Answer:
@Test public void defaultGeneratorContainsAll() { String password = new PasswordGenerator().generate(); assertTrue(password.matches(".*[a-z].*[a-z].*")); assertTrue(password.matches(".*[A-Z].*[A-Z].*")); assertTrue(password.matches(".*[0-9].*[0-9].*")); assertTrue(password.replaceAll("[a-zA-Z0-9]", "").length() > 0); } |
### Question:
BindLoggersAnnotatedWithResource implements TypeListener { public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type); if (loggerFields.isEmpty()) return; Logger logger = loggerFactory.getLogger(type.getName()); for (Field field : loggerFields) { if (field.isAnnotationPresent(Named.class)) { Named name = field.getAnnotation(Named.class); encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field)); } else { encounter.register(new AssignLoggerToField<I>(logger, field)); } } } @Inject BindLoggersAnnotatedWithResource(LoggerFactory loggerFactory); void hear(TypeLiteral<I> injectableType,
TypeEncounter<I> encounter); }### Answer:
@Test void testHear() { Injector i = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(any(), blawr); } }); assertEquals(i.getInstance(A.class).logger.getCategory(), getClass().getName() + "$A"); assertEquals(i.getInstance(B.class).logger.getCategory(), getClass().getName() + "$B"); assertEquals(i.getInstance(B.class).blogger.getCategory(), "blogger"); } |
### Question:
ContextLinking { public static Module linkView(final String id, final Supplier<View> view) { return new AbstractModule() { @Override protected void configure() { bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view); bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view)); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); }### Answer:
@Test public void testLinkedViewBindsViewAndContextSuppliers() { Injector injector = Guice.createInjector(linkView(new DummyView(contextFor(IntegrationTestClient.class)))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); assertNotNull(injector.getExistingBinding(Key.get(VIEW_SUPPLIER, Names.named("IntegrationTestClient")))); } |
### Question:
ContextLinking { public static Module linkContext(final String id, final Supplier<Context> context) { return new AbstractModule() { @Override protected void configure() { bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); }### Answer:
@Test public void testLinkedContextBindsContextSupplier() { Injector injector = Guice.createInjector(linkContext(contextFor(IntegrationTestClient.class))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); } |
### Question:
ExecutorServiceModule extends AbstractModule { static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } ExecutorServiceModule(); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor,
ExecutorService ioExecutor); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ListeningExecutorService ioExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); static SimpleTimeLimiter createSimpleTimeLimiter(ExecutorService executorService); }### Answer:
@Test public void testShutdownOnClose() throws IOException { Injector i = Guice.createInjector(); Closer closer = i.getInstance(Closer.class); ListeningExecutorService executor = createMock(ListeningExecutorService.class); ExecutorServiceModule.shutdownOnClose(executor, closer); expect(executor.shutdownNow()).andReturn(ImmutableList.<Runnable> of()).atLeastOnce(); replay(executor); closer.close(); verify(executor); } |
### Question:
JodaDateService implements DateService { public final String rfc822DateFormat(Date dateTime) { return rfc822DateFormatter.print(new DateTime(dateTime)); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); }### Answer:
@Override @Test public void testRfc822DateFormat() { String dsString = dateService.rfc822DateFormat(testData[0].date); assertEquals(dsString, testData[0].rfc822DateString); } |
### Question:
ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); }### Answer:
@Test public void testCorrect() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: assertEquals(fn.apply("1"), URI.create("http: }
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeString() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: fn.apply(new File("foo")); }
@Test(expectedExceptions = IllegalStateException.class) public void testMustHaveEndpoints() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap .<String, Supplier<URI>> of())); fn.apply("1"); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testNullIsIllegal() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: fn.apply(null); } |
### Question:
RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); }### Answer:
@Test public void testWhenRegionNameIsSameAsProviderName() throws SecurityException, NoSuchMethodException { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: assertEquals(fn.apply("leader"), URI.create("http: }
@Test public void testWhenFindsRegion() throws SecurityException, NoSuchMethodException { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: assertEquals(fn.apply("1"), URI.create("http: }
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeString() { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: fn.apply(new File("foo")); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeInRegionMapIfSpecified() { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: fn.apply("2"); } |
### Question:
RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); @Override URI apply(Object from); }### Answer:
@Test public void testCorrect() { RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: assertEquals(fn.apply("1"), URI.create("http: }
@Test(expectedExceptions = IllegalStateException.class) public void testMustHaveEndpoints() { RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap .<String, Supplier<URI>> of())); fn.apply("1"); } |
### Question:
JodaDateService implements DateService { public final Date rfc822DateParse(String toParse) { return rfc822DateFormatter.parseDateTime(toParse).toDate(); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); }### Answer:
@Override @Test(enabled = false) public void testRfc822DateParse() { Date dsDate = dateService.rfc822DateParse(testData[0].rfc822DateString); assertEquals(dsDate, testData[0].date); } |
### Question:
ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } @Override Properties apply(final Properties properties); }### Answer:
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "properties cannot be null") public void testPropertiesMandatory() { new ExpandProperties().apply(null); }
@Test public void testNoLeafs() { Properties props = new Properties(); props.put("one", "${two}"); props.put("two", "${one}"); Properties resolved = new ExpandProperties().apply(props); assertEquals(resolved.size(), props.size()); assertEquals(resolved.get("one"), "${two}"); assertEquals(resolved.get("two"), "${one}"); } |
### Question:
JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); }### Answer:
@Test public void testIterableLong() { String list = new JoinOnComma().apply(ImmutableList.of(1L, 2L)); assertEquals(list, "1,2"); }
@Test public void testLongArray() { String list = new JoinOnComma().apply(new long[] { 1L, 2L }); assertEquals(list, "1,2"); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyArrayIllegalArgumentException() { new JoinOnComma().apply(new long[] {}); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyIterableIllegalArgumentException() { new JoinOnComma().apply(ImmutableList.of()); }
@Test(expectedExceptions = NullPointerException.class) public void testNullPointer() { new JoinOnComma().apply(null); } |
### Question:
SshjSshClient implements SshClient { @VisibleForTesting SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); logger.error(e, "<< " + message); if (e instanceof UserAuthException) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } SshjSshClient(BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket,
LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); @Override void put(String path, String contents); void connect(); Payload get(String path); @Override void put(String path, Payload contents); @Override String toString(); @PreDestroy void disconnect(); @Override boolean isConnected(); ExecResponse exec(String command); @Override ExecChannel execChannel(String command); @Override String getHostAddress(); @Override String getUsername(); }### Answer:
@Test(expectedExceptions = AuthorizationException.class) public void testPropateConvertsAuthException() { ssh.propagate(new UserAuthException(""), ""); } |
### Question:
Apis { public static ApiMetadata withId(String id) throws NoSuchElementException { return find(all(), ApiPredicates.id(id)); } static Function<ApiMetadata, String> idFunction(); static Iterable<ApiMetadata> all(); static ApiMetadata withId(String id); static Iterable<ApiMetadata> contextAssignableFrom(TypeToken<?> type); static Iterable<ApiMetadata> viewableAs(TypeToken<? extends View> type); static Iterable<ApiMetadata> viewableAs(Class<? extends View> type); static TypeToken<?> findView(final ApiMetadata apiMetadata, final TypeToken<?> view); }### Answer:
@Test public void testWithId() { ApiMetadata apiMetadata; try { apiMetadata = Apis.withId("fake-id"); fail("Looking for a api with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { } apiMetadata = Apis.withId(testBlobstoreApi.getId()); assertEquals(testBlobstoreApi, apiMetadata); }
@Test public void testWithId() { ApiMetadata apiMetadata; try { apiMetadata = Apis.withId("fake-id"); fail("Looking for a api with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { ; } apiMetadata = Apis.withId(testBlobstoreApi.getId()); assertEquals(testBlobstoreApi, apiMetadata); } |
### Question:
InitScriptConfigurationForTasks { @Inject(optional = true) public InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) { this.initScriptPattern = checkNotNull(initScriptPattern, "initScriptPattern ex. /tmp/init-%s"); checkArgument(this.initScriptPattern.startsWith("/"), "initScriptPattern must be a UNIX-style path starting at the root (/)"); int lastSlash = initScriptPattern.lastIndexOf('/'); if (lastSlash == 0) { this.basedir = "/"; } else { this.basedir = initScriptPattern.substring(0, lastSlash); } return this; } protected InitScriptConfigurationForTasks(); static InitScriptConfigurationForTasks create(); @Inject(optional = true) InitScriptConfigurationForTasks initScriptPattern(
@Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern); InitScriptConfigurationForTasks appendCurrentTimeMillisToAnonymousTaskNames(); InitScriptConfigurationForTasks appendIncrementingNumberToAnonymousTaskNames(); String getBasedir(); String getInitScriptPattern(); Supplier<String> getAnonymousTaskSuffixSupplier(); static final String PROPERTY_INIT_SCRIPT_PATTERN; }### Answer:
@Test public void testInitScriptPattern() throws Exception { InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create(); config.initScriptPattern("/var/tmp/jclouds-%s"); assertEquals(config.getBasedir(), "/var/tmp"); assertEquals(config.getInitScriptPattern(), "/var/tmp/jclouds-%s"); } |
### Question:
ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void registerImage(Image image) { checkNotNull(image, "image"); imageCache.put(image.getId(), image); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testRegisterNullImageIsNotAllowed() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); imageCache.registerImage(null); } |
### Question:
ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testRemoveNullImageIsNotAllowed() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); imageCache.removeImage(null); }
@Test public void testRemoveImage() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); imageCache.removeImage(image.getId()); assertEquals(imageCache.get().size(), 0); } |
### Question:
ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }### Answer:
@Test public void testLoadImage() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); }
@Test public void testSupplierExpirationReloadsTheCache() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 3, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); Uninterruptibles.sleepUninterruptibly(4, TimeUnit.SECONDS); assertEquals(imageCache.get().size(), 1); assertFalse(any(imageCache.get(), idEquals("foo"))); } |
### Question:
ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); }### Answer:
@Test public void testSocketFinderAllowedInterfacesAll() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.ALL); assertTrue(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); }
@Test public void testSocketFinderAllowedInterfacesPrivate() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PRIVATE); assertFalse(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); }
@Test public void testSocketFinderAllowedInterfacesPublic() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PUBLIC); assertTrue(ips.contains(PUBLIC_IP)); assertFalse(ips.contains(PRIVATE_IP)); } |
### Question:
AutomaticHardwareIdSpec { public static boolean isAutomaticId(String id) { return id.startsWith("automatic:"); } static boolean isAutomaticId(String id); static AutomaticHardwareIdSpec parseId(String hardwareId); static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk); @Override String toString(); double getCores(); int getRam(); Optional<Float> getDisk(); }### Answer:
@Test public void isAutomaticIdTest() { assertThat(AutomaticHardwareIdSpec.isAutomaticId("automatic:cores=2;ram=256")).isTrue(); }
@Test public void isNotAutomaticId() { assertThat(AutomaticHardwareIdSpec.isAutomaticId("Hi, I'm a non automatic id.")).isFalse(); } |
### Question:
AutomaticHardwareIdSpec { public static AutomaticHardwareIdSpec parseId(String hardwareId) { AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec(); String hardwareSpec = hardwareId.substring(10); Map<String, String> specValues = Splitter.on(';') .trimResults() .omitEmptyStrings() .withKeyValueSeparator('=') .split(hardwareSpec); if (!specValues.containsKey("ram") || !specValues.containsKey("cores")) { throw new IllegalArgumentException(String.format("Omitted keys on hardwareId: %s. Please set number " + "of cores and ram amount.", hardwareId)); } if (specValues.containsKey("disk")) { float disk = Float.parseFloat(specValues.get("disk")); if (disk > 0.0f) { spec.disk = Optional.of(disk); } else { throw new IllegalArgumentException(String.format("Invalid disk value: %s", hardwareId)); } } spec.ram = Integer.parseInt(specValues.get("ram")); spec.cores = Double.parseDouble(specValues.get("cores")); return spec; } static boolean isAutomaticId(String id); static AutomaticHardwareIdSpec parseId(String hardwareId); static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk); @Override String toString(); double getCores(); int getRam(); Optional<Float> getDisk(); }### Answer:
@Test(expectedExceptions = IllegalArgumentException.class) public void parseAutomaticIdMissingValuesTest() { AutomaticHardwareIdSpec.parseId("automatic:cores=2"); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Invalid disk value: automatic:cores=2;ram=4096;disk=-100") public void parseAutomaticIdInvalidDiskTest() { AutomaticHardwareIdSpec.parseId("automatic:cores=2;ram=4096;disk=-100"); } |
### Question:
TemplateOptions extends RunScriptOptions implements Cloneable { public String getPrivateKey() { return privateKey; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer:
@Test public void testNullinstallPrivateKey() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getPrivateKey(), null); } |
### Question:
TemplateOptions extends RunScriptOptions implements Cloneable { public String getPublicKey() { return publicKey; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer:
@Test public void testNullauthorizePublicKey() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getPublicKey(), null); } |