src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
SoftLayerTemplateOptions extends TemplateOptions implements Cloneable { public SoftLayerTemplateOptions domainName(String domainName) { checkNotNull(domainName, "domainName was null"); checkArgument(InternetDomainName.from(domainName).hasPublicSuffix(), "domainName %s has no public suffix", domainName); this.domainName = domainName; return this; } @Override SoftLayerTemplateOptions clone(); @Override void copyTo(TemplateOptions to); SoftLayerTemplateOptions domainName(String domainName); SoftLayerTemplateOptions blockDevices(Iterable<Integer> capacities); SoftLayerTemplateOptions blockDevices(Integer... capacities); SoftLayerTemplateOptions diskType(@Nullable String diskType); SoftLayerTemplateOptions portSpeed(@Nullable Integer portSpeed); SoftLayerTemplateOptions userData(@Nullable String userData); SoftLayerTemplateOptions primaryNetworkComponentNetworkVlanId(@Nullable Integer primaryNetworkComponentNetworkVlanId); SoftLayerTemplateOptions primaryBackendNetworkComponentNetworkVlanId(@Nullable Integer primaryBackendNetworkComponentNetworkVlanId); SoftLayerTemplateOptions hourlyBillingFlag(@Nullable Boolean hourlyBillingFlag); SoftLayerTemplateOptions dedicatedAccountHostOnlyFlag(@Nullable Boolean dedicatedAccountHostOnlyFlag); SoftLayerTemplateOptions privateNetworkOnlyFlag(@Nullable Boolean privateNetworkOnlyFlag); SoftLayerTemplateOptions postInstallScriptUri(@Nullable String postInstallScriptUri); SoftLayerTemplateOptions sshKeys(Iterable<Integer> sshKeys); SoftLayerTemplateOptions sshKeys(Integer... sshKeys); String getDomainName(); List<Integer> getBlockDevices(); String getDiskType(); Integer getPortSpeed(); String getUserData(); Integer getPrimaryNetworkComponentNetworkVlanId(); Integer getPrimaryBackendNetworkComponentNetworkVlanId(); Boolean isHourlyBillingFlag(); Boolean isDedicatedAccountHostOnlyFlag(); Boolean isPrivateNetworkOnlyFlag(); String getPostInstallScriptUri(); List<Integer> getSshKeys(); @Override SoftLayerTemplateOptions blockOnPort(int port, int seconds); @Override SoftLayerTemplateOptions inboundPorts(int... ports); @Override SoftLayerTemplateOptions authorizePublicKey(String publicKey); @Override SoftLayerTemplateOptions installPrivateKey(String privateKey); @Override SoftLayerTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override SoftLayerTemplateOptions dontAuthorizePublicKey(); @Override SoftLayerTemplateOptions nameTask(String name); @Override SoftLayerTemplateOptions runAsRoot(boolean runAsRoot); @Override SoftLayerTemplateOptions runScript(Statement script); @Override SoftLayerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override SoftLayerTemplateOptions overrideLoginPassword(String password); @Override SoftLayerTemplateOptions overrideLoginPrivateKey(String privateKey); @Override SoftLayerTemplateOptions overrideLoginUser(String loginUser); @Override SoftLayerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override SoftLayerTemplateOptions userMetadata(Map<String, String> userMetadata); @Override SoftLayerTemplateOptions userMetadata(String key, String value); @Override SoftLayerTemplateOptions nodeNames(Iterable<String> nodeNames); @Override SoftLayerTemplateOptions networks(Iterable<String> networks); } | @Test public void testDomainName() { TemplateOptions options = new SoftLayerTemplateOptions().domainName("me.com"); assertEquals(options.as(SoftLayerTemplateOptions.class).getDomainName(), "me.com"); }
@Test public void testDomainNameNullHasDecentMessage() { try { new SoftLayerTemplateOptions().domainName(null); fail("should NPE"); } catch (NullPointerException e) { assertEquals(e.getMessage(), "domainName was null"); } }
@Test(expectedExceptions = IllegalArgumentException.class) public void testDomainNameIsInvalidThrowsIllegalArgument() { new SoftLayerTemplateOptions().domainName("notapublicsuffix"); } |
VirtualGuestToNodeMetadata implements Function<VirtualGuest, NodeMetadata> { @Inject VirtualGuestToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations, GroupNamingConvention.Factory namingConvention, VirtualGuestToImage virtualGuestToImage, VirtualGuestToHardware virtualGuestToHardware) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); this.locations = checkNotNull(locations, "locations"); this.virtualGuestToImage = checkNotNull(virtualGuestToImage, "virtualGuestToImage"); this.virtualGuestToHardware = checkNotNull(virtualGuestToHardware, "virtualGuestToHardware"); } @Inject VirtualGuestToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
GroupNamingConvention.Factory namingConvention, VirtualGuestToImage virtualGuestToImage,
VirtualGuestToHardware virtualGuestToHardware); @Override NodeMetadata apply(VirtualGuest from); static final Map<VirtualGuest.State, Status> serverStateToNodeStatus; } | @Test public void testVirtualGuestToNodeMetadata() { VirtualGuest virtualGuest = createVirtualGuest(); NodeMetadata nodeMetadata = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, virtualGuestToImage, virtualGuestToHardware).apply(virtualGuest); assertNotNull(nodeMetadata); assertEquals(nodeMetadata.getName(), virtualGuest.getHostname()); assertNotNull(nodeMetadata.getLocation()); assertEquals(nodeMetadata.getLocation().getId(), location.getId()); assertEquals(nodeMetadata.getHostname(), virtualGuest.getFullyQualifiedDomainName()); assertEquals(nodeMetadata.getHardware().getRam(), virtualGuest.getMaxMemory()); assertTrue(nodeMetadata.getHardware().getProcessors().size() == 1); assertEquals(Iterables.get(nodeMetadata.getHardware().getProcessors(), 0).getCores(), (double) virtualGuest.getStartCpus()); assertEquals(nodeMetadata.getOperatingSystem().getFamily(), OsFamily.UBUNTU); assertEquals(nodeMetadata.getOperatingSystem().getVersion(), "12.04"); assertEquals(nodeMetadata.getOperatingSystem().is64Bit(), true); } |
VirtualGuestToNodeMetadata implements Function<VirtualGuest, NodeMetadata> { @VisibleForTesting Password getBestPassword(Set<Password> passwords, VirtualGuest context) { if (passwords == null || passwords.isEmpty()) { throw new IllegalStateException("No credentials declared for " + context); } if (passwords.size() == 1) { return Iterables.getOnlyElement(passwords); } Password bestPassword = null; Set<Password> alternates = Sets.newLinkedHashSet(); int bestScore = -1; for (Password p : passwords) { int score = -1; if ("root".equals(p.getUsername())) score = 10; else if ("root".equalsIgnoreCase(p.getUsername())) score = 4; else if ("ubuntu".equals(p.getUsername())) score = 8; else if ("ubuntu".equalsIgnoreCase(p.getUsername())) score = 3; else if ("administrator".equals(p.getUsername())) score = 5; else if ("administrator".equalsIgnoreCase(p.getUsername())) score = 2; else if (p.getUsername() != null && p.getUsername().length() > 1) score = 1; if (score > 0) { if (score > bestScore) { bestPassword = p; alternates.clear(); bestScore = score; } else if (score == bestScore) { alternates.add(p); } } } if (bestPassword == null) { throw new IllegalStateException("No valid credentials available for " + context + "; found: " + passwords); } if (!alternates.isEmpty()) { logger.warn("Multiple credentials for " + bestPassword.getUsername() + "@" + context + "; using first declared " + bestPassword + " and ignoring " + alternates); } else { logger.debug("Multiple credentials for " + context + "; using preferred username " + bestPassword.getUsername()); } return bestPassword; } @Inject VirtualGuestToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
GroupNamingConvention.Factory namingConvention, VirtualGuestToImage virtualGuestToImage,
VirtualGuestToHardware virtualGuestToHardware); @Override NodeMetadata apply(VirtualGuest from); static final Map<VirtualGuest.State, Status> serverStateToNodeStatus; } | @Test(expectedExceptions = { IllegalStateException.class }) public void testGetBestPasswordNone() { Set<Password> passwords = Sets.newLinkedHashSet(); VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, virtualGuestToImage, virtualGuestToHardware); f.getBestPassword(passwords, null); }
@Test public void testGetBestPasswordOneRoot() { Set<Password> passwords = Sets.newLinkedHashSet(); passwords.add(new Password(1, "root", "pass")); VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, virtualGuestToImage, virtualGuestToHardware); Password best = f.getBestPassword(passwords, null); assertEquals(best.getUsername(), "root"); }
@Test public void testGetBestPasswordOneNonRoot() { Set<Password> passwords = Sets.newLinkedHashSet(); passwords.add(new Password(1, "nonroot", "word")); VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, virtualGuestToImage, virtualGuestToHardware); Password best = f.getBestPassword(passwords, null); assertEquals(best.getUsername(), "nonroot"); }
@Test public void testGetBestPasswordTwoDifferent() { Set<Password> passwords = Sets.newLinkedHashSet(); passwords.add(new Password(1, "nonroot", "word")); passwords.add(new Password(2, "root", "pass")); VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, virtualGuestToImage, virtualGuestToHardware); Password best = f.getBestPassword(passwords, null); assertEquals(best.getUsername(), "root"); }
@Test public void testGetBestPasswordTwoSame() { Set<Password> passwords = Sets.newLinkedHashSet(); passwords.add(new Password(1, "root", "word")); passwords.add(new Password(2, "root", "pass")); VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, virtualGuestToImage, virtualGuestToHardware); Password best = f.getBestPassword(passwords, null); assertEquals(best.getUsername(), "root"); assertEquals(best.getPassword(), "word"); } |
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(); } | @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); } |
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(); } | @Test public void testOsBits() { assertEquals(OperatingSystems.bits().apply("UBUNTU_12_64").intValue(), 64); assertEquals(OperatingSystems.bits().apply("UBUNTU_12_32").intValue(), 32); } |
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(); } | @Test public void testOsVersion() { assertEquals(OperatingSystems.version().apply("12.04-64 Minimal for VSI"), "12.04"); assertEquals(OperatingSystems.version().apply("STD 32 bit"), "STD"); } |
VirtualGuestToImage implements Function<VirtualGuest, Image> { @Override public Image apply(VirtualGuest from) { checkNotNull(from, "from"); if (from.getOperatingSystem() == null) { return new ImageBuilder().ids(getReferenceCodeOrId(from)) .name(from.getHostname()) .status(Image.Status.UNRECOGNIZED) .operatingSystem(OperatingSystem.builder() .family(OsFamily.UNRECOGNIZED) .version(UNRECOGNIZED) .description(UNRECOGNIZED) .build()) .build(); } else { return operatingSystemToImage.apply(from.getOperatingSystem()); } } @Inject protected VirtualGuestToImage(OperatingSystemToImage operatingSystemToImage); @Override Image apply(VirtualGuest from); String getReferenceCodeOrId(VirtualGuest from); } | @Test public void testVirtualGuestToImageWhenOperatingSystemIsNull() { VirtualGuest virtualGuest = createVirtualGuestWithoutOperatingSystem(); Image image = new VirtualGuestToImage(operatingSystemToImage).apply(virtualGuest); assertNotNull(image); assertEquals(image.getStatus(), Image.Status.UNRECOGNIZED); assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UNRECOGNIZED); assertEquals(image.getOperatingSystem().getVersion(), "UNRECOGNIZED"); }
@Test public void testVirtualGuestToImageWhenVirtualGuestIsSoftwareLicense() { VirtualGuest virtualGuest = createVirtualGuestWithoutSoftwareLicenseDetails(); Image image = new VirtualGuestToImage(operatingSystemToImage).apply(virtualGuest); assertNotNull(image); assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UNRECOGNIZED); assertEquals(image.getOperatingSystem().getVersion(), "UNRECOGNIZED"); }
@Test public void testVirtualGuestToImageWithSoftwareLicense() { VirtualGuest virtualGuest = createVirtualGuestWithSoftwareLicenseDetails(); Image image = new VirtualGuestToImage(operatingSystemToImage).apply(virtualGuest); assertNotNull(image); assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU); assertEquals(image.getOperatingSystem().getVersion(), "12.04"); assertEquals(image.getOperatingSystem().is64Bit(), true); } |
OperatingSystemToImage implements Function<OperatingSystem, Image> { @Override public Image apply(OperatingSystem operatingSystem) { checkNotNull(operatingSystem, "operatingSystem"); final SoftwareLicense defaultSoftwareLicense = SoftwareLicense.builder().softwareDescription(SoftwareDescription.builder().build()).build(); SoftwareLicense softwareLicense = fromNullable(operatingSystem.getSoftwareLicense()).or(defaultSoftwareLicense); Optional<String> optOSReferenceCode = fromNullable(softwareLicense.getSoftwareDescription().getReferenceCode()); Optional<String> optVersion = fromNullable(softwareLicense.getSoftwareDescription().getVersion()); Optional<String> optLongDescription = fromNullable(softwareLicense.getSoftwareDescription().getLongDescription()); OsFamily osFamily = OsFamily.UNRECOGNIZED; String osVersion = UNRECOGNIZED; Integer bits = null; if (optOSReferenceCode.isPresent()) { String operatingSystemReferenceCode = optOSReferenceCode.get(); osFamily = OperatingSystems.osFamily().apply(operatingSystemReferenceCode); bits = OperatingSystems.bits().apply(operatingSystemReferenceCode); } if (optVersion.isPresent()) { osVersion = OperatingSystems.version().apply(optVersion.get()); } if (osFamily == OsFamily.UNRECOGNIZED) { logger.debug("Cannot determine os family for item: %s", operatingSystem); } if (osVersion == null) { logger.debug("Cannot determine os version for item: %s", operatingSystem); } if (bits == null) { logger.debug("Cannot determine os bits for item: %s", operatingSystem); } org.jclouds.compute.domain.OperatingSystem os = org.jclouds.compute.domain.OperatingSystem.builder() .description(optLongDescription.or(UNRECOGNIZED)) .family(osFamily) .version(osVersion) .is64Bit(Objects.equal(bits, 64)) .build(); return new ImageBuilder() .ids(optOSReferenceCode.or(operatingSystem.getId())) .description(optOSReferenceCode.or(UNRECOGNIZED)) .operatingSystem(os) .status(Image.Status.AVAILABLE) .build(); } @Override Image apply(OperatingSystem operatingSystem); } | @Test public void testOperatingSystemToImage() { OperatingSystem operatingSystem = OperatingSystem.builder() .id("UBUNTU_12_64") .softwareLicense(SoftwareLicense.builder() .softwareDescription(SoftwareDescription.builder() .version("12.04-64 Minimal for CCI") .referenceCode("UBUNTU_12_64") .longDescription("Ubuntu Linux 12.04 LTS Precise Pangolin - Minimal Install (64 bit)") .build()) .build()) .build(); Image image = new OperatingSystemToImage().apply(operatingSystem); assertEquals(image.getId(), operatingSystem.getId()); String referenceCode = operatingSystem.getSoftwareLicense().getSoftwareDescription().getReferenceCode(); assertEquals(image.getDescription(), referenceCode); assertTrue(image.getOperatingSystem().getFamily().toString().equalsIgnoreCase("UBUNTU")); assertEquals(image.getOperatingSystem().getVersion(), "12.04"); assertEquals(image.getOperatingSystem().is64Bit(), true); assertEquals(image.getStatus(), Image.Status.AVAILABLE); } |
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); } | @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()); } |
DatacenterToLocation implements Function<Datacenter, Location> { @Inject public DatacenterToLocation(JustProvider provider) { this.provider = checkNotNull(provider, "provider"); } @Inject DatacenterToLocation(JustProvider provider); @Override Location apply(Datacenter datacenter); } | @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")); } |
DatacenterToLocation implements Function<Datacenter, Location> { @Override public Location apply(Datacenter datacenter) { return new LocationBuilder().id(datacenter.getName()) .description(datacenter.getLongName()) .scope(LocationScope.ZONE) .iso3166Codes(createIso3166Codes(datacenter.getLocationAddress())) .parent(Iterables.getOnlyElement(provider.get())) .metadata(ImmutableMap.<String, Object>of("name", datacenter.getName())) .build(); } @Inject DatacenterToLocation(JustProvider provider); @Override Location apply(Datacenter datacenter); } | @Test public void testGetIso3166CodeNoCountryAndState() { Datacenter datacenter = Datacenter.builder().id(1).name("Nowhere").longName("No where").build(); Location location = function.apply(datacenter); assertEquals(location.getId(), datacenter.getName()); Set<String> iso3166Codes = location.getIso3166Codes(); assertEquals(iso3166Codes.size(), 0); }
@Test public void testGetIso3166CodeCountryOnly() { Address address = Address.builder().country("US").description("This is North America!").build(); Datacenter datacenter = Datacenter.builder().id(1).name("Nowhere").longName("No where").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")); }
@Test public void testGetIso3166CodeWhitespaceTrimmer() { Address address = Address.builder().country(" US ").state(" TX ").description("This is spaced out Texas") .build(); Datacenter datacenter = Datacenter.builder().id(1).name("NoWhere").longName("Nowhere").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")); } |
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(); } | @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(); } |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withKeyName(String keyName) { launchSpecificationBuilder.keyName(keyName); return AWSRunInstancesOptions.class.cast(super.withKeyName(keyName)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithKeyName() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withKeyName("test"); assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of("test")); }
@Test public void testWithKeyNameStatic() { AWSRunInstancesOptions options = withKeyName("test"); assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithKeyNameNPE() { withKeyName(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withSecurityGroup(String securityGroup) { launchSpecificationBuilder.securityGroupName(securityGroup); return AWSRunInstancesOptions.class.cast(super.withSecurityGroup(securityGroup)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithSecurityGroup() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withSecurityGroup("test"); assertEquals(options.buildFormParameters().get("SecurityGroup.1"), ImmutableList.of("test")); }
@Test public void testWithSecurityGroupStatic() { AWSRunInstancesOptions options = withSecurityGroup("test"); assertEquals(options.buildFormParameters().get("SecurityGroup.1"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithSecurityGroupNPE() { withSecurityGroup(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions withSecurityGroupId(String securityGroup) { return withSecurityGroupIds(securityGroup); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithSecurityGroupId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withSecurityGroupId("test"); assertEquals(options.buildFormParameters().get("SecurityGroupId.1"), ImmutableList.of("test")); }
@Test public void testWithSecurityGroupIdStatic() { AWSRunInstancesOptions options = withSecurityGroupId("test"); assertEquals(options.buildFormParameters().get("SecurityGroupId.1"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithSecurityGroupIdNPE() { withSecurityGroupId(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withUserData(byte[] unencodedData) { launchSpecificationBuilder.userData(unencodedData); return AWSRunInstancesOptions.class.cast(super.withUserData(unencodedData)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithUserData() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withUserData("test".getBytes()); assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); }
@Test public void testWithUserDataStatic() { AWSRunInstancesOptions options = withUserData("test".getBytes()); assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithUserDataNPE() { withUserData(null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testWithUserDataEmpty() { withUserData("".getBytes()); } |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions asType(String type) { launchSpecificationBuilder.instanceType(type); return AWSRunInstancesOptions.class.cast(super.asType(type)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithInstanceType() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.asType(InstanceType.C1_XLARGE); assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); }
@Test public void testWithInstanceTypeStatic() { AWSRunInstancesOptions options = asType(InstanceType.C1_XLARGE); assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithInstanceTypeNPE() { asType(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withKernelId(String kernelId) { launchSpecificationBuilder.kernelId(kernelId); return AWSRunInstancesOptions.class.cast(super.withKernelId(kernelId)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithKernelId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); }
@Test public void testWithKernelIdStatic() { AWSRunInstancesOptions options = withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithKernelIdNPE() { withKernelId(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions enableMonitoring() { formParameters.put("Monitoring.Enabled", "true"); launchSpecificationBuilder.monitoringEnabled(true); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithMonitoringEnabled() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.enableMonitoring(); assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), ImmutableList.of("true")); }
@Test public void testWithMonitoringEnabledStatic() { AWSRunInstancesOptions options = enableMonitoring(); assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), ImmutableList.of("true")); } |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions withSubnetId(String subnetId) { formParameters.put("SubnetId", checkNotNull(subnetId, "subnetId")); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithSubnetId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withSubnetId("test"); assertEquals(options.buildFormParameters().get("SubnetId"), ImmutableList.of("test")); }
@Test public void testWithSubnetIdStatic() { AWSRunInstancesOptions options = withSubnetId("test"); assertEquals(options.buildFormParameters().get("SubnetId"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithSubnetIdNPE() { withSubnetId(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { @SinceApiVersion("2012-06-01") public AWSRunInstancesOptions withIAMInstanceProfileArn(String arn) { formParameters.put("IamInstanceProfile.Arn", checkNotNull(arn, "arn")); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithIAMInstanceProfileArn() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options .withIAMInstanceProfileArn("arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver"); assertEquals(options.buildFormParameters().get("IamInstanceProfile.Arn"), ImmutableList.of("arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver")); }
@Test public void testWithIAMInstanceProfileArnStatic() { AWSRunInstancesOptions options = withIAMInstanceProfileArn("arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver"); assertEquals(options.buildFormParameters().get("IamInstanceProfile.Arn"), ImmutableList.of("arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithIAMInstanceProfileArnNPE() { withIAMInstanceProfileArn(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { @SinceApiVersion("2012-06-01") public AWSRunInstancesOptions withIAMInstanceProfileName(String name) { formParameters.put("IamInstanceProfile.Name", checkNotNull(name, "name")); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithIAMInstanceProfileName() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withIAMInstanceProfileName("Webserver"); assertEquals(options.buildFormParameters().get("IamInstanceProfile.Name"), ImmutableList.of("Webserver")); }
@Test public void testWithIAMInstanceProfileNameStatic() { AWSRunInstancesOptions options = withIAMInstanceProfileName("Webserver"); assertEquals(options.buildFormParameters().get("IamInstanceProfile.Name"), ImmutableList.of("Webserver")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithIAMInstanceProfileNameNPE() { withIAMInstanceProfileName(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withRamdisk(String ramDiskId) { launchSpecificationBuilder.ramdiskId(ramDiskId); return AWSRunInstancesOptions.class.cast(super.withRamdisk(ramDiskId)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithRamdisk() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); }
@Test public void testWithRamdiskStatic() { AWSRunInstancesOptions options = withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithRamdiskNPE() { withRamdisk(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings) { launchSpecificationBuilder.blockDeviceMappings(mappings); return AWSRunInstancesOptions.class.cast(super.withBlockDeviceMappings(mappings)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithBlockDeviceMapping() { BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice("/dev/sda1", 120, true, "gp2", 10, true); AWSRunInstancesOptions options = new AWSRunInstancesOptions().withBlockDeviceMappings(ImmutableSet .<BlockDeviceMapping> of(mapping)); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), ImmutableList.of("/dev/sda1")); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), ImmutableList.of("120")); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), ImmutableList.of("true")); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeType"), ImmutableList.of("gp2")); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.Iops"), ImmutableList.of("10")); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.Encrypted"), ImmutableList.of("true")); }
@Test public void testWithBlockDeviceMappingStatic() { BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice("/dev/sda1", 120, true, null, null, false); AWSRunInstancesOptions options = withBlockDeviceMappings(ImmutableSet.<BlockDeviceMapping> of(mapping)); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), ImmutableList.of("/dev/sda1")); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), ImmutableList.of("120")); assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), ImmutableList.of("true")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithBlockDeviceMappingNPE() { withBlockDeviceMappings(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions withTenancy(Tenancy tenancy) { formParameters.put("Placement.Tenancy", checkNotNull(tenancy, "tenancy").toString()); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithTenancy() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withTenancy(Tenancy.DEDICATED); assertEquals(options.buildFormParameters().get("Placement.Tenancy"), ImmutableList.of("dedicated")); }
@Test public void testWithTenancyStatic() { AWSRunInstancesOptions options = withTenancy(Tenancy.HOST); assertEquals(options.buildFormParameters().get("Placement.Tenancy"), ImmutableList.of("host")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithTenancyStaticNPE() { withTenancy(null); } |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions withDedicatedHostId(String hostId) { formParameters.put("Placement.HostId", checkNotNull(hostId, "hostId")); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDedicatedHostId(String hostId); AWSRunInstancesOptions enableMonitoring(); AWSRunInstancesOptions withSubnetId(String subnetId); AWSRunInstancesOptions withSecurityGroupId(String securityGroup); AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds); AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileArn(String arn); @SinceApiVersion("2012-06-01") AWSRunInstancesOptions withIAMInstanceProfileName(String name); AWSRunInstancesOptions withPrivateIpAddress(String address); @Override AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); @Override AWSRunInstancesOptions withKernelId(String kernelId); @Override AWSRunInstancesOptions withKeyName(String keyName); @Override AWSRunInstancesOptions withRamdisk(String ramDiskId); @Override AWSRunInstancesOptions withSecurityGroup(String securityGroup); @Override AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); @Override AWSRunInstancesOptions withSecurityGroups(String... securityGroups); @Override AWSRunInstancesOptions withUserData(byte[] unencodedData); @Override AWSRunInstancesOptions asType(String type); synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder(); static final AWSRunInstancesOptions NONE; } | @Test public void testWithDedicatedHostId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withDedicatedHostId("hostId-1234"); assertEquals(options.buildFormParameters().get("Placement.HostId"), ImmutableList.of("hostId-1234")); }
@Test public void testWithDedicatedHostIdStatic() { AWSRunInstancesOptions options = withDedicatedHostId("hostId-5678"); assertEquals(options.buildFormParameters().get("Placement.HostId"), ImmutableList.of("hostId-5678")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithDedicatedHostIdStaticNPE() { withDedicatedHostId(null); } |
BindLaunchSpecificationToFormParams implements Binder, Function<LaunchSpecification, Map<String, String>> { @Override public Map<String, String> apply(LaunchSpecification launchSpec) { Builder<String, String> builder = ImmutableMap.builder(); builder.put("LaunchSpecification.ImageId", checkNotNull(launchSpec.getImageId(), "imageId")); if (launchSpec.getAvailabilityZone() != null) builder.put("LaunchSpecification.Placement.AvailabilityZone", launchSpec.getAvailabilityZone()); AWSRunInstancesOptions options = new AWSRunInstancesOptions(); if (!launchSpec.getBlockDeviceMappings().isEmpty()) options.withBlockDeviceMappings(launchSpec.getBlockDeviceMappings()); if (!launchSpec.getSecurityGroupNames().isEmpty()) options.withSecurityGroups(launchSpec.getSecurityGroupNames()); if (!launchSpec.getSecurityGroupIds().isEmpty()) options.withSecurityGroupIds(launchSpec.getSecurityGroupIds()); options.asType(checkNotNull(launchSpec.getInstanceType(), "instanceType")); if (launchSpec.getSubnetId() != null) options.withSubnetId(launchSpec.getSubnetId()); if (launchSpec.getKernelId() != null) options.withKernelId(launchSpec.getKernelId()); if (launchSpec.getKeyName() != null) options.withKeyName(launchSpec.getKeyName()); if (launchSpec.getRamdiskId() != null) options.withRamdisk(launchSpec.getRamdiskId()); if (Boolean.TRUE.equals(launchSpec.isMonitoringEnabled())) options.enableMonitoring(); if (launchSpec.getUserData() != null) options.withUserData(launchSpec.getUserData()); if (launchSpec.getIAMInstanceProfile().isPresent()) { IAMInstanceProfileRequest profile = launchSpec.getIAMInstanceProfile().get(); if (profile.getArn().isPresent()) options.withIAMInstanceProfileArn(profile.getArn().get()); if (profile.getName().isPresent()) options.withIAMInstanceProfileName(profile.getName().get()); } for (Entry<String, String> entry : options.buildFormParameters().entries()) { builder.put("LaunchSpecification." + entry.getKey(), entry.getValue()); } return builder.build(); } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); @Override Map<String, String> apply(LaunchSpecification launchSpec); } | @Test public void testApplyWithBlockDeviceMappings() throws UnknownHostException { LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId("ami-123") .mapNewVolumeToDevice("/dev/sda1", 120, true).build(); assertEquals(binder.apply(spec), ImmutableMap.of("LaunchSpecification.InstanceType", "t1.micro", "LaunchSpecification.ImageId", "ami-123", "LaunchSpecification.BlockDeviceMapping.1.DeviceName", "/dev/sda1", "LaunchSpecification.BlockDeviceMapping.1.Ebs.VolumeSize", "120", "LaunchSpecification.BlockDeviceMapping.1.Ebs.DeleteOnTermination", "true")); }
@Test public void testApplyWithUserData() throws UnknownHostException { LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId("ami-123") .userData("hello".getBytes()).build(); assertEquals(binder.apply(spec), ImmutableMap.of("LaunchSpecification.InstanceType", "t1.micro", "LaunchSpecification.ImageId", "ami-123", "LaunchSpecification.UserData", base64().encode("hello".getBytes(UTF_8)))); }
@Test public void testApplyWithSecurityId() throws UnknownHostException { LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId("ami-123") .securityGroupId("sid-foo").build(); assertEquals(binder.apply(spec), ImmutableMap.of("LaunchSpecification.InstanceType", "t1.micro", "LaunchSpecification.ImageId", "ami-123", "LaunchSpecification.SecurityGroupId.1", "sid-foo")); }
@Test public void testApplyWithSubnetId() throws UnknownHostException { LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId("ami-123") .subnetId("subnet-xyz").build(); assertEquals(binder.apply(spec), ImmutableMap.of("LaunchSpecification.InstanceType", "t1.micro", "LaunchSpecification.ImageId", "ami-123", "LaunchSpecification.SubnetId", "subnet-xyz")); }
@Test public void testApplyWithIAMInstanceProfileArn() { LaunchSpecification spec = LaunchSpecification.builder() .instanceType(InstanceType.T1_MICRO) .imageId("ami-123") .iamInstanceProfileArn("arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver") .build(); assertEquals(binder.apply(spec), ImmutableMap.of("LaunchSpecification.InstanceType", "t1.micro", "LaunchSpecification.ImageId", "ami-123", "LaunchSpecification.IamInstanceProfile.Arn", "arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver")); }
@Test public void testApplyWithIAMInstanceProfileName() { LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId("ami-123") .iamInstanceProfileName("Webserver").build(); assertEquals(binder.apply(spec), ImmutableMap.of("LaunchSpecification.InstanceType", "t1.micro", "LaunchSpecification.ImageId", "ami-123", "LaunchSpecification.IamInstanceProfile.Name", "Webserver")); } |
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); } | @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); } |
ImportOrReturnExistingKeypair implements Function<RegionNameAndPublicKeyMaterial, KeyPair> { @Inject public ImportOrReturnExistingKeypair(AWSEC2Api ec2Api) { this.ec2Api = ec2Api; } @Inject ImportOrReturnExistingKeypair(AWSEC2Api ec2Api); @Override KeyPair apply(RegionNameAndPublicKeyMaterial from); KeyPair addFingerprintToKeyPair(String publicKeyMaterial, KeyPair keyPair); } | @Test public void testApplyWithIllegalStateExceptionReturnsExistingKey() { 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)).andThrow( new IllegalStateException()); expect(keyApi.describeKeyPairsInRegion("region", "jclouds#group")).andReturn(ImmutableSet.of(pair)); replay(client); replay(keyApi); ImportOrReturnExistingKeypair parser = new ImportOrReturnExistingKeypair(client); assertEquals(parser.importOrReturnExistingKeypair("region", "group", PUBLIC_KEY), pairWithFingerprint); verify(client); verify(keyApi); }
@Test public void testApplyWithIllegalStateExceptionRetriesWhenExistingKeyNotFound() { 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)).andThrow( new IllegalStateException()); expect(keyApi.describeKeyPairsInRegion("region", "jclouds#group")).andReturn(ImmutableSet.<KeyPair> of()); expect(keyApi.importKeyPairInRegion("region", "jclouds#group", PUBLIC_KEY)).andThrow( new IllegalStateException()); expect(keyApi.describeKeyPairsInRegion("region", "jclouds#group")).andReturn(ImmutableSet.<KeyPair> of(pair)); replay(client); replay(keyApi); ImportOrReturnExistingKeypair parser = new ImportOrReturnExistingKeypair(client); assertEquals(parser.importOrReturnExistingKeypair("region", "group", PUBLIC_KEY), pairWithFingerprint); verify(client); verify(keyApi); } |
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); } | @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)); } |
CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions extends
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions { @Override public String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) { RegionAndName key = new RegionAndName(region, group); KeyPair pair; if (and(hasPublicKeyMaterial, or(doesntNeedSshAfterImportingPublicKey, hasLoginCredential)).apply(options)) { pair = importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, options.getPublicKey())); options.dontAuthorizePublicKey(); if (hasLoginCredential.apply(options)) pair = pair.toBuilder().keyMaterial(options.getLoginPrivateKey()).build(); credentialsMap.put(key, pair); } else { if (hasPublicKeyMaterial.apply(options)) { logger.warn("to avoid creating temporary keys in aws-ec2, use templateOption overrideLoginCredentialWith(id_rsa)"); } return super.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options); } return pair.getKeyName(); } @Inject CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions(
Function<RegionAndName, KeyPair> makeKeyPair, ConcurrentMap<RegionAndName, KeyPair> credentialsMap,
@Named("SECURITY") LoadingCache<RegionAndName, String> securityGroupMap,
Provider<RunInstancesOptions> optionsProvider,
@Named("PLACEMENT") LoadingCache<RegionAndName, String> placementGroupMap,
CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded,
Function<RegionNameAndPublicKeyMaterial, KeyPair> importExistingKeyPair,
GroupNamingConvention.Factory namingConvention,
AWSEC2Api awsEC2Api); AWSRunInstancesOptions execute(String region, String group, Template template); @Override String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options); static final Predicate<TemplateOptions> hasPublicKeyMaterial; static final Predicate<TemplateOptions> doesntNeedSshAfterImportingPublicKey; static final Predicate<TemplateOptions> hasLoginCredential; } | @Test(expectedExceptions = IllegalArgumentException.class) public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptButNoCredentials() { String region = Region.AP_SOUTHEAST_1; String group = "group"; String userSuppliedKeyPair = "myKeyPair"; CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy(); EC2TemplateOptions options = createMock(EC2TemplateOptions.class); KeyPair keyPair = createMock(KeyPair.class); expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); expect(options.getPublicKey()).andReturn(null).times(2); expect(options.getLoginPrivateKey()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false); replay(options); replay(keyPair); replayStrategy(strategy); assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair); verify(options); verify(keyPair); verifyStrategy(strategy); }
@Test public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_importsKeyPairAndUnsetsTemplateInstructionWhenPublicKeySuppliedAndAddsCredentialToMapWhenOverridingCredsAreSet() { String region = Region.AP_SOUTHEAST_1; String group = "group"; CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy(); AWSEC2TemplateOptions options = keyPair(group).authorizePublicKey("ssh-rsa").overrideLoginCredentials( LoginCredentials.builder().user("foo").privateKey(CREDENTIALS.credential).build()); KeyPair keyPair = new KeyPair(region, group, " expect( strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, CREDENTIALS.credential))).andReturn(keyPair); expect( strategy.credentialsMap.put(new RegionAndName(region, group), keyPair.toBuilder().keyMaterial(CREDENTIALS.credential).build())).andReturn(null); replayStrategy(strategy); assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), group); verifyStrategy(strategy); }
@Test public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_importsKeyPairAndUnsetsTemplateInstructionWhenPublicKeySupplied() { String region = Region.AP_SOUTHEAST_1; String group = "group"; AWSEC2TemplateOptions options = keyPair(group).authorizePublicKey("ssh-rsa"); CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy(); KeyPair keyPair = new KeyPair(region, "jclouds#" + group, "fingerprint", null, null); expect(strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, "ssh-rsa"))) .andReturn(keyPair); expect(strategy.credentialsMap.put(new RegionAndName(region, group), keyPair)).andReturn(null); replayStrategy(strategy); assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), "jclouds#" + group); verifyStrategy(strategy); } |
AWSEC2ReviseParsedImage implements ReviseParsedImage { @Override public void reviseParsedImage(org.jclouds.ec2.domain.Image from, ImageBuilder builder, OsFamily family, OperatingSystem.Builder osBuilder) { try { Matcher matcher = getMatcherAndFind(from.getImageLocation()); if (matcher.pattern() == AMZN_PATTERN) { osBuilder.family(OsFamily.AMZN_LINUX); osBuilder.version(matcher.group(2)); builder.version(matcher.group(2)); } else if (matcher.pattern() == AMAZON_PATTERN) { family = OsFamily.fromValue(matcher.group(1)); osBuilder.family(family); osBuilder.version(ComputeServiceUtils.parseVersionOrReturnEmptyString(family, matcher.group(2), osVersionMap)); } else { family = OsFamily.fromValue(matcher.group(1)); osBuilder.family(family); osBuilder.version(ComputeServiceUtils.parseVersionOrReturnEmptyString(family, matcher.group(2), osVersionMap)); builder.version(matcher.group(3).replace(".manifest.xml", "")); } } catch (IllegalArgumentException e) { logger.debug("<< didn't match os(%s)", from.getImageLocation()); } catch (NoSuchElementException e) { logger.trace("<< didn't match at all(%s)", from.getImageLocation()); } } @Inject AWSEC2ReviseParsedImage(Map<OsFamily, Map<String, String>> osVersionMap); @Override void reviseParsedImage(org.jclouds.ec2.domain.Image from, ImageBuilder builder, OsFamily family,
OperatingSystem.Builder osBuilder); static final Pattern AMZN_PATTERN; static final Pattern AMAZON_PATTERN; static final Pattern AMAZON_WINDOWS_PATTERN; static final Pattern CENTOS_MARKETPLACE_PATTERN; static final Pattern CANONICAL_PATTERN; static final Pattern RIGHTSCALE_PATTERN; static final Pattern RIGHTIMAGE_PATTERN; } | @Test public void testNewWindowsName() throws Exception { ReviseParsedImage rpi = new AWSEC2ReviseParsedImage(osVersionMap); Image from = newImage("amazon", "Windows_Server-2008-R2_SP1-English-64Bit-Base-2012.03.13"); OperatingSystem.Builder osBuilder = OperatingSystem.builder().description("test"); ImageBuilder builder = new ImageBuilder().id("1").operatingSystem(osBuilder.build()).status( org.jclouds.compute.domain.Image.Status.AVAILABLE).description("test"); OsFamily family = OsFamily.WINDOWS; rpi.reviseParsedImage(from, builder, family, osBuilder); OperatingSystem os = osBuilder.build(); assertEquals(os.getFamily(), OsFamily.WINDOWS); assertEquals(os.getVersion(), "2008"); assertEquals(builder.build().getVersion(), "2012.03.13"); }
@Test public void testOldWindowsName() throws Exception { ReviseParsedImage rpi = new AWSEC2ReviseParsedImage(osVersionMap); Image from = newImage("amazon", "Windows-2008R2-SP1-English-Base-2012.01.12"); OperatingSystem.Builder osBuilder = OperatingSystem.builder().description("test"); ImageBuilder builder = new ImageBuilder().id("1").operatingSystem(osBuilder.build()).status( org.jclouds.compute.domain.Image.Status.AVAILABLE).description("test"); OsFamily family = OsFamily.WINDOWS; rpi.reviseParsedImage(from, builder, family, osBuilder); OperatingSystem os = osBuilder.build(); assertEquals(os.getFamily(), OsFamily.WINDOWS); assertEquals(os.getVersion(), "2008"); assertEquals(builder.build().getVersion(), "2012.01.12"); } |
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(); } }); } } | @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) { } } } |
PresentSpotRequestsAndInstances extends PresentInstances { @Override public Set<RunningInstance> apply(Set<RegionAndName> regionAndIds) { if (checkNotNull(regionAndIds, "regionAndIds").isEmpty()) return ImmutableSet.of(); if (any(regionAndIds, Predicates.compose(containsPattern("sir-"), nameFunction()))) return getSpots(regionAndIds); return super.apply(regionAndIds); } @Inject PresentSpotRequestsAndInstances(AWSEC2Api client, Function<SpotInstanceRequest, AWSRunningInstance> spotConverter); @Override Set<RunningInstance> apply(Set<RegionAndName> regionAndIds); @Override String toString(); } | @SuppressWarnings("unchecked") @Test public void testWhenInstancesPresentSingleCall() { AWSEC2Api client = createMock(AWSEC2Api.class); AWSInstanceApi instanceApi = createMock(AWSInstanceApi.class); Function<SpotInstanceRequest, AWSRunningInstance> converter = createMock(Function.class); expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceApi)); expect(instanceApi.describeInstancesInRegion("us-east-1", "i-aaaa", "i-bbbb")).andReturn( Set.class.cast(ImmutableSet.of(Reservation.<AWSRunningInstance> builder().region("us-east-1") .instances(ImmutableSet.of(instance1, instance2)).build()))); replay(client, instanceApi, converter); PresentSpotRequestsAndInstances fn = new PresentSpotRequestsAndInstances(client, converter); 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, instanceApi, converter); }
@Test public void testWhenSpotsPresentSingleCall() { Function<SpotInstanceRequest, AWSRunningInstance> converter = Functions.forMap(ImmutableMap.of(spot1, instance1, spot2, instance2)); AWSEC2Api client = createMock(AWSEC2Api.class); SpotInstanceApi spotApi = createMock(SpotInstanceApi.class); expect(client.getSpotInstanceApi()).andReturn((Optional) Optional.of(spotApi)); expect(spotApi.describeSpotInstanceRequestsInRegion("us-east-1", "sir-aaaa", "sir-bbbb")).andReturn( ImmutableSet.of(spot1, spot2)); replay(client, spotApi); PresentSpotRequestsAndInstances fn = new PresentSpotRequestsAndInstances(client, converter); assertEquals(fn.apply(ImmutableSet.of(new RegionAndName("us-east-1", "sir-aaaa"), new RegionAndName("us-east-1", "sir-bbbb"))), ImmutableSet.of(instance1, instance2)); verify(client, spotApi); } |
AWSEC2CreateSecurityGroupIfNeeded extends CacheLoader<RegionAndName, String> { @Override public String load(RegionAndName from) { RegionNameAndIngressRules realFrom = RegionNameAndIngressRules.class.cast(from); return createSecurityGroupInRegion(from.getRegion(), from.getName(), realFrom.getVpcId(), realFrom.getPorts()); } @Inject AWSEC2CreateSecurityGroupIfNeeded(AWSEC2Api ec2Api,
@Named("SECGROUP_NAME_TO_ID") Function<String, String> groupNameToId,
@Named("SECURITY") Predicate<RegionAndName> securityGroupEventualConsistencyDelay); AWSEC2CreateSecurityGroupIfNeeded(AWSSecurityGroupApi securityApi,
@Named("SECGROUP_NAME_TO_ID") Function<String, String> groupNameToId,
@Named("SECURITY") Predicate<RegionAndName> securityGroupEventualConsistencyDelay); @Override String load(RegionAndName from); } | @SuppressWarnings("unchecked") @Test public void testWhenPort22AndToItselfAuthorizesIngressOnce() throws ExecutionException { AWSSecurityGroupApi client = createMock(AWSSecurityGroupApi.class); Predicate<RegionAndName> tester = Predicates.alwaysTrue(); SecurityGroup group = createNiceMock(SecurityGroup.class); Set<SecurityGroup> groups = ImmutableSet.<SecurityGroup> of(group); EC2SecurityGroupIdFromName groupIdFromName = createMock(EC2SecurityGroupIdFromName.class); ImmutableSet.Builder<IpPermission> permissions = ImmutableSet.builder(); permissions.add(IpPermission.builder() .fromPort(22) .toPort(22) .ipProtocol(IpProtocol.TCP) .cidrBlock("0.0.0.0/0") .build()); permissions.add(IpPermission.builder() .fromPort(0) .toPort(65535) .ipProtocol(IpProtocol.TCP) .tenantIdGroupNamePair("ownerId", "sg-123456") .build()); permissions.add(IpPermission.builder() .fromPort(0) .toPort(65535) .ipProtocol(IpProtocol.UDP) .tenantIdGroupNamePair("ownerId", "sg-123456") .build()); expect( client.createSecurityGroupInRegionAndReturnId("region", "group", "group", new CreateSecurityGroupOptions().vpcId("vpc"))).andReturn("sg-123456"); expect(group.getOwnerId()).andReturn("ownerId"); client.authorizeSecurityGroupIngressInRegion("region", "sg-123456", permissions.build()); expect(client.describeSecurityGroupsInRegionById("region", "sg-123456")) .andReturn(Set.class.cast(groups)); replay(client); replay(group); replay(groupIdFromName); AWSEC2CreateSecurityGroupIfNeeded function = new AWSEC2CreateSecurityGroupIfNeeded(client, groupIdFromName, tester); assertEquals("sg-123456", function.load(new RegionNameAndIngressRules("region", "group", new int[] { 22 }, true, "vpc"))); verify(client); verify(group); verify(groupIdFromName); } |
AzureRetryableErrorHandler extends BackoffLimitedRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { if (response.getStatusCode() != 429 || isRateLimitError(response)) { return false; } try { Error error = parseError.apply(response); logger.debug("processing error: %s", error); boolean isRetryable = RETRYABLE_ERROR_CODE.equals(error.details().code()); return isRetryable ? super.shouldRetryRequest(command, response) : false; } catch (Exception ex) { logger.warn("could not parse error. Request won't be retried: %s", ex.getMessage()); return false; } } @Inject AzureRetryableErrorHandler(ParseJson<Error> parseError); @Override boolean shouldRetryRequest(HttpCommand command, HttpResponse response); } | @Test public void testDoesNotRetryWhenNot429() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(400).build(); assertFalse(handler.shouldRetryRequest(command, response)); }
@Test public void testDoesNotRetryWhenRateLimitError() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(HttpHeaders.RETRY_AFTER, "15").build(); assertFalse(handler.shouldRetryRequest(command, response)); }
@Test public void testDoesNotRetryWhenCannotParseError() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).payload("foo").build(); assertFalse(handler.shouldRetryRequest(command, response)); }
@Test public void testDoesNotRetryWhenErrorNotRetryable() { String nonRetryable = "{\"error\":{\"code\":\"ReferencedResourceNotProvisioned\",\"message\":\"Not provisioned\"}}"; HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).payload(nonRetryable).build(); assertFalse(handler.shouldRetryRequest(command, response)); }
@Test public void testRetriesWhenRetryableError() { String retryable = "{\"error\":{\"code\":\"RetryableError\",\"message\":\"Resource busy\"}}"; HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).payload(retryable).build(); assertTrue(handler.shouldRetryRequest(command, response)); } |
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); } | @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); } |
ApiVersionFilter implements HttpRequestFilter { @Override public HttpRequest filter(HttpRequest request) throws HttpException { checkArgument(request instanceof GeneratedHttpRequest, "This filter can only be applied to GeneratedHttpRequest objects"); GeneratedHttpRequest generatedRequest = (GeneratedHttpRequest) request; String commandName = config.getCommandName(generatedRequest.getInvocation()); String customApiVersion = versions.get(commandName); if (customApiVersion == null) { Invokable<?, ?> invoked = generatedRequest.getInvocation().getInvokable(); String className = invoked.getOwnerType().getRawType().getSimpleName(); customApiVersion = versions.get(className); } if (customApiVersion != null) { return request.toBuilder().replaceQueryParam("api-version", customApiVersion).build(); } return request; } @Inject ApiVersionFilter(InvocationConfig config, Function<Predicate<String>, Map<String, String>> filterStringsBoundByName); @Override HttpRequest filter(HttpRequest request); } | @Test(expectedExceptions = IllegalArgumentException.class) public void testFailIfNoGeneratedHttpRequest() { ApiVersionFilter filter = new ApiVersionFilter(config, filterStringsBoundToInjectorByName(new Properties())); filter.filter(HttpRequest.builder().method("GET").endpoint("http: }
@Test public void testOverrideMethodVersion() { Properties props = new Properties(); props.setProperty(API_VERSION_PREFIX + "named:get", "namedversion"); props.setProperty(API_VERSION_PREFIX + "VersionedApi.noName", "noNameversion"); ApiVersionFilter filter = new ApiVersionFilter(config, filterStringsBoundToInjectorByName(props)); HttpRequest request = GeneratedHttpRequest.builder().method("GET").endpoint("http: .invocation(noName).addQueryParam("api-version", "original", "original2").build(); HttpRequest filtered = filter.filter(request); assertEquals(filtered.getEndpoint().getQuery(), "api-version=noNameversion"); request = GeneratedHttpRequest.builder().method("GET").endpoint("http: .addQueryParam("api-version", "original", "original2").build(); filtered = filter.filter(request); assertEquals(filtered.getEndpoint().getQuery(), "api-version=namedversion"); }
@Test public void testFallbackToClassName() { Properties props = new Properties(); props.setProperty(API_VERSION_PREFIX + "VersionedApi", "classversion"); ApiVersionFilter filter = new ApiVersionFilter(config, filterStringsBoundToInjectorByName(props)); HttpRequest request = GeneratedHttpRequest.builder().method("GET").endpoint("http: .invocation(noName).addQueryParam("api-version", "original", "original2").build(); HttpRequest filtered = filter.filter(request); assertEquals(filtered.getEndpoint().getQuery(), "api-version=classversion"); request = GeneratedHttpRequest.builder().method("GET").endpoint("http: .addQueryParam("api-version", "original", "original2").build(); filtered = filter.filter(request); assertEquals(filtered.getEndpoint().getQuery(), "api-version=classversion"); }
@Test public void testNothingChangesIfNoCustomVersion() { ApiVersionFilter filter = new ApiVersionFilter(config, filterStringsBoundToInjectorByName(new Properties())); HttpRequest request = GeneratedHttpRequest.builder().method("GET").endpoint("http: .addQueryParam("api-version", "foo").build(); HttpRequest filtered = filter.filter(request); assertEquals(filtered.getEndpoint().getQuery(), "api-version=foo"); } |
CreateResourcesThenCreateNodes extends CreateNodesWithGroupEncodedIntoNameThenAddToSet { @VisibleForTesting void normalizeNetworkOptions(AzureTemplateOptions options) { if (!options.getNetworks().isEmpty() && !options.getIpOptions().isEmpty()) { throw new IllegalArgumentException("The options.networks and options.ipOptions are exclusive"); } if (!options.getNetworks().isEmpty()) { ImmutableList.Builder<IpOptions> ipOptions = ImmutableList.builder(); for (String subnetId : options.getNetworks()) { ipOptions.add(IpOptions.builder().subnet(subnetId).allocateNewPublicIp(true).build()); } options.ipOptions(ipOptions.build()); } if (!options.getIpOptions().isEmpty()) { for (IpOptions ipConfig : options.getIpOptions()) { if (ipConfig.allocateNewPublicIp() && ipConfig.publicIpId() != null) { throw new IllegalArgumentException("The allocateNewPublicIps and publicIpId are exclusive"); } String resourceGroup = extractResourceGroup(ipConfig.subnet()); String networkName = extractVirtualNetwork(ipConfig.subnet()); String subnetName = extractName(ipConfig.subnet()); Subnet subnet = api.getSubnetApi(resourceGroup, networkName).get(subnetName); checkState(subnet != null, "Configured subnet %s does not exist", ipConfig.subnet()); if (ipConfig.publicIpId() != null) { PublicIPAddress publicIp = api.getPublicIPAddressApi(extractResourceGroup(ipConfig.publicIpId())).get( extractName(ipConfig.publicIpId())); checkState(publicIp != null, "Configured public ip %s does not exist", ipConfig.publicIpId()); } } } } @Inject protected CreateResourcesThenCreateNodes(
CreateNodeWithGroupEncodedIntoName addNodeWithGroupStrategy,
ListNodesStrategy listNodesStrategy,
GroupNamingConvention.Factory namingConvention,
@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,
AzureComputeApi api, @Named(DEFAULT_VNET_ADDRESS_SPACE_PREFIX) String defaultVnetAddressPrefix,
@Named(DEFAULT_SUBNET_ADDRESS_PREFIX) String defaultSubnetAddressPrefix,
LoadingCache<ResourceGroupAndNameAndIngressRules, String> securityGroupMap,
TemplateToAvailabilitySet templateToAvailabilitySet, PasswordGenerator.Config passwordGenerator,
NetworkAvailablePredicateFactory networkAvailable); @Override Map<?, ListenableFuture<Void>> execute(String group, int count, Template template,
Set<NodeMetadata> goodNodes, Map<NodeMetadata, Exception> badNodes,
Multimap<NodeMetadata, CustomizationResponse> customizationResponses); } | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "The options.networks and options.ipOptions are exclusive") public void testNormalizeNetworkOptionsWithConflictingConfig() { AzureTemplateOptions options = new AzureTemplateOptions(); options.ipOptions(IpOptions.builder().subnet(netResource("/virtualNetworks/vn/subnets/foo")).build()); options.networks(netResource("/virtualNetworks/vn/subnets/bar")); strategy(null).normalizeNetworkOptions(options); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "The allocateNewPublicIps and publicIpId are exclusive") public void testNormalizeNetworkOptionsExclusivePublicIps() { AzureTemplateOptions options = new AzureTemplateOptions(); options.ipOptions(IpOptions.builder().subnet(netResource("/virtualNetworks/vn/subnets/foo")) .allocateNewPublicIp(true).publicIpId(netResource("/publicIPAddresses/pub")).build()); strategy(null).normalizeNetworkOptions(options); } |
VirtualMachineToStatus implements Function<VirtualMachine, StatusAndBackendStatus> { @Override public StatusAndBackendStatus apply(VirtualMachine virtualMachine) { String resourceGroup = extractResourceGroup(virtualMachine.id()); ProvisioningState provisioningState = virtualMachine.properties().provisioningState(); NodeMetadata.Status status = PROVISIONINGSTATE_TO_NODESTATUS.apply(provisioningState); String backendStatus = provisioningState.name(); if (ProvisioningState.SUCCEEDED.equals(provisioningState)) { VirtualMachineInstance instanceDetails = api.getVirtualMachineApi(resourceGroup).getInstanceDetails( virtualMachine.name()); if (instanceDetails != null && instanceDetails.powerState() != null) { status = POWERSTATE_TO_NODESTATUS.apply(instanceDetails.powerState()); backendStatus = Joiner.on(',').join(transform(instanceDetails.statuses(), new Function<Status, String>() { @Override public String apply(Status input) { return input.code(); } })); } else { status = NodeMetadata.Status.PENDING; } } return StatusAndBackendStatus.create(status, backendStatus); } @Inject VirtualMachineToStatus(AzureComputeApi api); @Override StatusAndBackendStatus apply(VirtualMachine virtualMachine); } | @Test public void testPendingWhenInstanceNotFound() { AzureComputeApi api = createMock(AzureComputeApi.class); VirtualMachineApi vmApi = createMock(VirtualMachineApi.class); VirtualMachine vm = createMock(VirtualMachine.class); VirtualMachineProperties props = createMock(VirtualMachineProperties.class); expect(vm.id()).andReturn("/resourceGroups/test/virtualMachines/vm"); expect(vm.properties()).andReturn(props); expect(vm.name()).andReturn("vm"); expect(props.provisioningState()).andReturn(ProvisioningState.SUCCEEDED); expect(api.getVirtualMachineApi("test")).andReturn(vmApi); expect(vmApi.getInstanceDetails("vm")).andReturn(null); replay(props, vm, vmApi, api); assertEquals(new VirtualMachineToStatus(api).apply(vm).status(), NodeMetadata.Status.PENDING); verify(props, vm, vmApi, api); }
@Test public void testPendingWhenInstanceHasNoPowerState() { AzureComputeApi api = createMock(AzureComputeApi.class); VirtualMachineApi vmApi = createMock(VirtualMachineApi.class); VirtualMachine vm = createMock(VirtualMachine.class); VirtualMachineProperties props = createMock(VirtualMachineProperties.class); VirtualMachineInstance instance = createMock(VirtualMachineInstance.class); expect(vm.id()).andReturn("/resourceGroups/test/virtualMachines/vm"); expect(vm.properties()).andReturn(props); expect(vm.name()).andReturn("vm"); expect(props.provisioningState()).andReturn(ProvisioningState.SUCCEEDED); expect(api.getVirtualMachineApi("test")).andReturn(vmApi); expect(vmApi.getInstanceDetails("vm")).andReturn(instance); expect(instance.powerState()).andReturn(null); replay(props, vm, vmApi, api, instance); assertEquals(new VirtualMachineToStatus(api).apply(vm).status(), NodeMetadata.Status.PENDING); verify(props, vm, vmApi, api, instance); } |
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); } | @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); } |
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); } | @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(" } |
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; } | @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"); } |
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(); } | @Test public void testDefaultip() { TemplateOptions options = new GleSYSTemplateOptions(); assertEquals(options.as(GleSYSTemplateOptions.class).getIp(), "any"); } |
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(); } | @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"); } |
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(); } | @Test public void testDefaultRootPassword() { TemplateOptions options = new GleSYSTemplateOptions(); assertEquals(options.as(GleSYSTemplateOptions.class).getRootPassword(), null); } |
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(); } | @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); } |
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(); } | @Test public void testDefaultTranferGB() { TemplateOptions options = new GleSYSTemplateOptions(); assertEquals(options.as(GleSYSTemplateOptions.class).getTransferGB(), 50); } |
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(); } | @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); } |
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(); } | @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"); } |
ServerDetailsToNodeMetadata implements Function<ServerDetails, NodeMetadata> { @Override public NodeMetadata apply(ServerDetails from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getHostname()); builder.hostname(from.getHostname()); Location location = FluentIterable.from(locations.get()).firstMatch(idEquals(from.getDatacenter())).orNull(); checkState(location != null, "no location matched ServerDetails %s", from); Map<String, String> metadataMap; if (!isNullOrEmpty(from.getDescription()) && from.getDescription().matches("^[0-9A-Fa-f]+$")) { String decoded = new String(base16().lowerCase().decode(from.getDescription()), UTF_8); metadataMap = Splitter.on('\n').withKeyValueSeparator("=").split(decoded); addMetadataAndParseTagsFromCommaDelimitedValue(builder, metadataMap); } else { metadataMap = ImmutableMap.of(); } builder.group(groupFromMapOrName(metadataMap, from.getHostname(), nodeNamingConvention)); builder.imageId(from.getTemplateName() + ""); builder.operatingSystem(parseOperatingSystem(from)); builder.hardware(new HardwareBuilder().ids(from.getId() + "").ram(from.getMemorySizeMB()) .processors(ImmutableList.of(new Processor(from.getCpuCores(), 1.0))) .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) from.getDiskSizeGB(), true, true))) .hypervisor(from.getPlatform()).build()); builder.status(serverStateToNodeStatus.get(from.getState())); Iterable<String> addresses = Iterables.filter(Iterables.transform(from.getIps(), new Function<Ip, String>() { @Override public String apply(Ip arg0) { return Strings.emptyToNull(arg0.getIp()); } }), Predicates.notNull()); builder.publicAddresses(Iterables.filter(addresses, Predicates.not(IsPrivateIPAddress.INSTANCE))); builder.privateAddresses(Iterables.filter(addresses, IsPrivateIPAddress.INSTANCE)); return builder.build(); } @Inject ServerDetailsToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images, GroupNamingConvention.Factory namingConvention); @Override NodeMetadata apply(ServerDetails from); static final Map<ServerDetails.State, Status> serverStateToNodeStatus; } | @Test public void testServerDetailsRequest() { ServerDetailsToNodeMetadata toTest = injectorForKnownArgumentsAndConstantPassword( ImmutableMap .<HttpRequest, HttpResponse> builder() .put(HttpRequest .builder() .method("POST") .endpoint("https: .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .payload( newUrlEncodedFormPayload(ImmutableMultimap.<String, String> builder() .put("serverid", "xm3276891").build())).build(), HttpResponse .builder() .statusCode(200) .payload(payloadFromResource("/server_details.json")) .build()).build() ).getInstance(ServerDetailsToNodeMetadata.class); NodeMetadata actual = toTest.apply(ServerApiExpectTest.expectedServerDetails()); assertNotNull(actual); assertEquals( actual.toString(), new NodeMetadataBuilder() .ids("vz1840356") .name("glesys-s") .hostname("glesys-s") .group("glesys") .imageId("Ubuntu 10.04 LTS 32-bit") .operatingSystem( OperatingSystem.builder().name("Ubuntu 10.04 LTS 32-bit").family(OsFamily.UBUNTU).version("10.04") .is64Bit(false).description("Ubuntu 10.04 LTS 32-bit").build()) .publicAddresses(ImmutableSet.of("31.192.231.254")) .hardware( new HardwareBuilder().ids("vz1840356").ram(512) .processors(ImmutableList.of(new Processor(1, 1.0))) .volumes(ImmutableList.<Volume> of(new VolumeImpl(5f, true, true))).hypervisor("OpenVZ") .build()).status(Status.RUNNING).build().toString()); } |
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); } | @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); } |
SharedKeyLiteAuthentication implements HttpRequestFilter { @VisibleForTesting void appendUriPath(HttpRequest request, StringBuilder toSign) { toSign.append(request.getEndpoint().getRawPath()); if (request.getEndpoint().getQuery() != null) { StringBuilder paramsToSign = new StringBuilder("?"); String[] params = request.getEndpoint().getQuery().split("&"); for (String param : params) { String[] paramNameAndValue = param.split("="); if ("comp".equals(paramNameAndValue[0])) { paramsToSign.append(param); } } if (paramsToSign.length() > 1) { toSign.append(paramsToSign); } } } @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); } | @Test void testAclQueryStringRoot() { URI host = URI.create("http: HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(host).build(); StringBuilder builder = new StringBuilder(); filter.appendUriPath(request, builder); assertEquals(builder.toString(), "/?comp=list"); }
@Test void testAclQueryStringResTypeNotSignificant() { URI host = URI.create("http: HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(host).build(); StringBuilder builder = new StringBuilder(); filter.appendUriPath(request, builder); assertEquals(builder.toString(), "/mycontainer"); }
@Test void testAclQueryStringComp() { URI host = URI.create("http: HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(host).build(); StringBuilder builder = new StringBuilder(); filter.appendUriPath(request, builder); assertEquals(builder.toString(), "/mycontainer?comp=list"); }
@Test void testAclQueryStringRelativeWithExtraJunk() { URI host = URI.create("http: + ".blob.core.windows.net/mycontainer?comp=list&marker=marker&maxresults=1&prefix=prefix"); HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(host).build(); StringBuilder builder = new StringBuilder(); filter.appendUriPath(request, builder); assertEquals(builder.toString(), "/mycontainer?comp=list"); } |
BindAzureBlobMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof AzureBlob, "this binder is only valid for AzureBlobs!"); checkNotNull(request, "request"); AzureBlob blob = AzureBlob.class.cast(input); checkArgument(blob.getPayload().getContentMetadata().getContentLength() != null && blob.getPayload().getContentMetadata().getContentLength() >= 0, "size must be set"); Builder<String, String> headers = ImmutableMap.builder(); String cacheControl = blob.getPayload().getContentMetadata().getCacheControl(); if (cacheControl != null) { headers.put(AzureStorageHeaders.CACHE_CONTROL, cacheControl); } headers.put("x-ms-blob-type", blob.getProperties().getType().toString()); String contentDisposition = blob.getPayload().getContentMetadata().getContentDisposition(); if (contentDisposition != null) { headers.put("x-ms-blob-content-disposition", contentDisposition); } switch (blob.getProperties().getType()) { case PAGE_BLOB: headers.put(HttpHeaders.CONTENT_LENGTH, "0"); headers.put("x-ms-blob-content-length", blob.getPayload().getContentMetadata().getContentLength().toString()); break; case BLOCK_BLOB: checkArgument( checkNotNull(blob.getPayload().getContentMetadata().getContentLength(), "blob.getContentLength()") <= 256L * 1024 * 1024, "maximum size for put Blob is 256MB"); break; } request = (R) request.toBuilder().replaceHeaders(Multimaps.forMap(headers.build())).build(); return blobBinder.bindToRequest(request, azureBlob2Blob.apply(blob)); } @Inject BindAzureBlobMetadataToRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | @Test public void testPassWithMinimumDetailsAndPayload256MB() { AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(256 * 1024 * 1024L); blob.setPayload(payload); blob.getProperties().setName("foo"); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); assertEquals( binder.bindToRequest(request, blob), HttpRequest.builder().method("PUT").endpoint("http: .addHeader("x-ms-blob-type", "BlockBlob").build()); }
@Test public void testExtendedPropertiesBind() { AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(256 * 1024 * 1024L); blob.setPayload(payload); blob.getProperties().setName("foo"); blob.getProperties().setMetadata(ImmutableMap.of("foo", "bar")); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); assertEquals( binder.bindToRequest(request, blob), HttpRequest.builder().method("PUT").endpoint("http: .addHeader("x-ms-blob-type", "BlockBlob") .addHeader("x-ms-meta-foo", "bar").build()); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testNoContentLengthIsBad() { AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(null); blob.setPayload(payload); blob.getProperties().setName("foo"); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); binder.bindToRequest(request, blob); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testNoNameIsBad() { AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(5368709120000L); blob.setPayload(payload); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); binder.bindToRequest(request, blob); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testOver256MBIsBad() { AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(256 * 1024 * 1024L + 1); blob.setPayload(payload); blob.getProperties().setName("foo"); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); binder.bindToRequest(request, blob); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeAzureBlob() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: injector.getInstance(BindAzureBlobMetadataToRequest.class).bindToRequest(request, new File("foo")); }
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); } |
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; } } } | @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); } |
ContainerNameValidator extends DnsNameValidator { public void validate(String containerName) { super.validate(containerName); if (containerName.contains("--")) throw exception(containerName, "Every dash must be followed by letter or number"); if (containerName.endsWith("-")) throw exception(containerName, "Shouldn't end with a dash"); } @Inject ContainerNameValidator(); void validate(String containerName); } | @Test public void testInvalidNames() { ContainerNameValidator validator = new ContainerNameValidator(); try { validator.validate("adasd-ab--baba"); throw new RuntimeException("to be converted to TestException later"); } catch (IllegalArgumentException e) { } try { validator.validate("abc.zz.la"); throw new RuntimeException("to be converted to TestException later"); } catch (IllegalArgumentException e) { } try { validator.validate("abcZZla"); throw new RuntimeException("to be converted to TestException later"); } catch (IllegalArgumentException e) { } try { validator.validate("zz"); throw new RuntimeException("to be converted to TestException later"); } catch (IllegalArgumentException e) { } try { validator.validate("a????"); throw new RuntimeException("to be converted to TestException later"); } catch (IllegalArgumentException e) { } try { validator.validate("-adasd"); throw new RuntimeException("to be converted to TestException later"); } catch (IllegalArgumentException e) { } try { validator.validate("adasd-"); throw new RuntimeException("to be converted to TestException later"); } catch (IllegalArgumentException e) { } }
@Test public void testNamesValidity() { ContainerNameValidator validator = new ContainerNameValidator(); validator.validate("adasd"); validator.validate("adasd-ab"); validator.validate("zzz"); validator.validate("abcefghjlkmnop"); }
@Test public void testInvalidNames() { ContainerNameValidator validator = new ContainerNameValidator(); try { validator.validate("adasd-ab--baba"); throw new RuntimeException("to be converted to TestException later"); } catch(IllegalArgumentException e) { } try { validator.validate("abc.zz.la"); throw new RuntimeException("to be converted to TestException later"); } catch(IllegalArgumentException e) { } try { validator.validate("abcZZla"); throw new RuntimeException("to be converted to TestException later"); } catch(IllegalArgumentException e) { } try { validator.validate("zz"); throw new RuntimeException("to be converted to TestException later"); } catch(IllegalArgumentException e) { } try { validator.validate("a????"); throw new RuntimeException("to be converted to TestException later"); } catch(IllegalArgumentException e) { } try { validator.validate("-adasd"); throw new RuntimeException("to be converted to TestException later"); } catch(IllegalArgumentException e) { } try { validator.validate("adasd-"); throw new RuntimeException("to be converted to TestException later"); } catch(IllegalArgumentException e) { } } |
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); } | @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"); } |
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); } | @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"); } |
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); } | @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"); } |
InstanceToNodeMetadata implements Function<Instance, NodeMetadata> { @Override public NodeMetadata apply(Instance input) { String group = groupFromMapOrName(input.metadata().asMap(), input.name(), nodeNamingConvention); NodeMetadataBuilder builder = new NodeMetadataBuilder(); Location zone = locationsByUri.get().get(input.zone()); if (zone == null) { throw new IllegalStateException( String.format("zone %s not present in %s", input.zone(), locationsByUri.get().keySet())); } URI diskSource = input.disks().get(0).source(); Optional<Image> image = diskURIToImage.getUnchecked(diskSource); Hardware hardware; if (isCustomMachineTypeURI(input.machineType())) { hardware = machineTypeURIToCustomHardware(input.machineType()); } else { hardware = hardwares.get().get(input.machineType()); } builder.id(input.selfLink().toString()) .name(input.name()) .providerId(input.id()) .hostname(input.name()) .location(zone) .imageId(image.isPresent() ? image.get().selfLink().toString() : null) .hardware(hardware) .status(input.status() != null ? toPortableNodeStatus.get(input.status()) : Status.UNRECOGNIZED) .tags(input.tags().items()) .uri(input.selfLink()) .userMetadata(input.metadata().asMap()) .group(group) .privateAddresses(collectPrivateAddresses(input)) .publicAddresses(collectPublicAddresses(input)); return builder.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); } | @Test public void imageUrl() { NodeMetadata nodeMetadata = groupNullNodeParser.apply(instance); assertEquals(nodeMetadata.getImageId(), imageUrl.toString()); }
@Test public final void testInstanceWithGroupNull() { NodeMetadata nodeMetadata = groupNullNodeParser.apply(instance); assertEquals(nodeMetadata.getId(), instance.selfLink().toString()); assertEquals(nodeMetadata.getTags(), ImmutableSet.of("aTag", "Group-port-42")); } |
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); } | @Test public void isCustomMachineTypeTest() { URI uri = URI.create("https: assertThat(isCustomMachineTypeURI(uri)).isTrue(); URI uri2 = URI.create("https: assertThat(isCustomMachineTypeURI(uri2)).isFalse(); } |
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); } | @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: } |
OrphanedGroupsFromDeadNodes implements Function<Set<? extends NodeMetadata>, Set<String>> { @Override public Set<String> apply(Set<? extends NodeMetadata> deadNodes) { Set<String> groups = Sets.newLinkedHashSet(); for (NodeMetadata deadNode : deadNodes) { groups.add(deadNode.getGroup()); } Set<String> orphanedGroups = Sets.newLinkedHashSet(); for (String group : groups) { if (isOrphanedGroupPredicate.apply(group)) { orphanedGroups.add(group); } } return orphanedGroups; } @Inject OrphanedGroupsFromDeadNodes(Predicate<String> isOrphanedGroupPredicate); @Override Set<String> apply(Set<? extends NodeMetadata> deadNodes); } | @Test public void testDetectsNoOrphanedGroupsWhenAllNodesArePresentAndTerminated() { Set<NodeMetadata> deadNodesGroup1 = ImmutableSet.<NodeMetadata>builder() .add(new IdAndGroupOnlyNodeMetadata("a", "1", NodeMetadata.Status.TERMINATED)).build(); Set<NodeMetadata> deadNodesGroup2 = ImmutableSet.<NodeMetadata> builder() .add(new IdAndGroupOnlyNodeMetadata("b", "2", NodeMetadata.Status.SUSPENDED)).build(); Set<NodeMetadata> allDeadNodes = Sets.union(deadNodesGroup1, deadNodesGroup2); ComputeService mock = createMock(ComputeService.class); expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject())) .andReturn((Set) deadNodesGroup1).once(); expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject())) .andReturn((Set) deadNodesGroup2).once(); replay(mock); OrphanedGroupsFromDeadNodes orphanedGroupsFromDeadNodes = new OrphanedGroupsFromDeadNodes( allNodesInGroupTerminated(mock)); Set<String> orphanedGroups = orphanedGroupsFromDeadNodes.apply(allDeadNodes); assertTrue(orphanedGroups.isEmpty()); }
@Test public void testDetectsOneOrphanedGroupWhenSomeNodesTerminatedAndOtherMissing() { Set<NodeMetadata> deadNodesGroup1 = ImmutableSet.<NodeMetadata> builder() .add(new IdAndGroupOnlyNodeMetadata("a", "1", NodeMetadata.Status.TERMINATED)).build(); Set<NodeMetadata> deadNodesGroup2 = ImmutableSet.<NodeMetadata> builder() .add(new IdAndGroupOnlyNodeMetadata("b", "2", NodeMetadata.Status.TERMINATED)).build(); Set<NodeMetadata> allDeadNodes = Sets.union(deadNodesGroup1, deadNodesGroup2); ComputeService mock = createMock(ComputeService.class); expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject())) .andReturn((Set) deadNodesGroup1).once(); expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject())) .andReturn((Set) ImmutableSet.of()).once(); replay(mock); OrphanedGroupsFromDeadNodes orphanedGroupsFromDeadNodes = new OrphanedGroupsFromDeadNodes( allNodesInGroupTerminated(mock)); Set<String> orphanedGroups = orphanedGroupsFromDeadNodes.apply(allDeadNodes); assertSame(orphanedGroups.size(), 1); assertTrue(orphanedGroups.contains("2")); }
@Test public void testDetectsOneOrphanedGroupWhenSomeNodesAreAliveAndOtherMissing() { Set<NodeMetadata> deadNodesGroup1 = ImmutableSet.<NodeMetadata> builder() .add(new IdAndGroupOnlyNodeMetadata("a", "1", NodeMetadata.Status.RUNNING)).build(); Set<NodeMetadata> deadNodesGroup2 = ImmutableSet.<NodeMetadata> builder() .add(new IdAndGroupOnlyNodeMetadata("b", "2", NodeMetadata.Status.TERMINATED)).build(); Set<NodeMetadata> allDeadNodes = Sets.union(deadNodesGroup1, deadNodesGroup2); ComputeService mock = createMock(ComputeService.class); expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject())) .andReturn((Set) deadNodesGroup1).once(); expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject())) .andReturn((Set) ImmutableSet.of()).once(); replay(mock); OrphanedGroupsFromDeadNodes orphanedGroupsFromDeadNodes = new OrphanedGroupsFromDeadNodes( allNodesInGroupTerminated(mock)); Set<String> orphanedGroups = orphanedGroupsFromDeadNodes.apply(allDeadNodes); assertSame(orphanedGroups.size(), 1); assertTrue(orphanedGroups.contains("2")); }
@Test public void testDetectsAllOrphanedGroupsWhenAllNodesArerMissing() { Set<NodeMetadata> deadNodesGroup1 = ImmutableSet.<NodeMetadata> builder() .add(new IdAndGroupOnlyNodeMetadata("a", "1", NodeMetadata.Status.RUNNING)).build(); Set<NodeMetadata> deadNodesGroup2 = ImmutableSet.<NodeMetadata> builder() .add(new IdAndGroupOnlyNodeMetadata("b", "2", NodeMetadata.Status.TERMINATED)).build(); Set<NodeMetadata> allDeadNodes = Sets.union(deadNodesGroup1, deadNodesGroup2); ComputeService mock = createMock(ComputeService.class); expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject())) .andReturn((Set) ImmutableSet.of()).once(); expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject())) .andReturn((Set) ImmutableSet.of()).once(); replay(mock); OrphanedGroupsFromDeadNodes orphanedGroupsFromDeadNodes = new OrphanedGroupsFromDeadNodes( allNodesInGroupTerminated(mock)); Set<String> orphanedGroups = orphanedGroupsFromDeadNodes.apply(allDeadNodes); assertSame(orphanedGroups.size(), 2); assertTrue(orphanedGroups.contains("1")); assertTrue(orphanedGroups.contains("2")); } |
RetryOnRenew implements HttpRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { boolean retry = false; switch (response.getStatusCode()) { case 401: Multimap<String, String> headers = command.getCurrentRequest().getHeaders(); if (headers != null && headers.containsKey(AuthHeaders.AUTH_USER) && headers.containsKey(AuthHeaders.AUTH_KEY) && !headers.containsKey(AuthHeaders.AUTH_TOKEN)) { retry = false; } else { Integer count = retryCountMap.getIfPresent(command); if (count == null) { logger.debug("invalidating authentication token - first time for %s", command); retryCountMap.put(command, 1); authenticationResponseCache.invalidateAll(); retry = true; } else { if (count + 1 >= NUM_RETRIES) { logger.debug("too many 401s - giving up after: %s for %s", count, command); retry = false; } else { logger.debug("invalidating authentication token - retry %s for %s", count, command); retryCountMap.put(command, count + 1); authenticationResponseCache.invalidateAll(); Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); retry = true; } } } break; } return retry; } @Inject protected RetryOnRenew(LoadingCache<Credentials, AuthenticationResponse> authenticationResponseCache); @Override boolean shouldRetryRequest(HttpCommand command, HttpResponse response); } | @Test public void test401ShouldRetry() { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = createMock(HttpRequest.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, AuthenticationResponse> cache = createMock(LoadingCache.class); expect(command.getCurrentRequest()).andReturn(request); cache.invalidateAll(); expectLastCall(); expect(response.getPayload()).andReturn(Payloads.newStringPayload("")) .anyTimes(); expect(response.getStatusCode()).andReturn(401).atLeastOnce(); replay(command); replay(response); replay(cache); RetryOnRenew retry = new RetryOnRenew(cache); assertTrue(retry.shouldRetryRequest(command, response)); verify(command); verify(response); verify(cache); }
@Test public void test401ShouldRetry4Times() { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = createMock(HttpRequest.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, AuthenticationResponse> cache = createMock(LoadingCache.class); expect(command.getCurrentRequest()).andReturn(request).anyTimes(); expect(request.getHeaders()).andStubReturn(null); cache.invalidateAll(); expectLastCall().anyTimes(); expect(response.getPayload()).andReturn(Payloads.newStringPayload("")) .anyTimes(); expect(response.getStatusCode()).andReturn(401).anyTimes(); replay(command, request, response, cache); RetryOnRenew retry = new RetryOnRenew(cache); for (int n = 0; n < RetryOnRenew.NUM_RETRIES - 1; n++) { assertTrue(retry.shouldRetryRequest(command, response), "Expected retry to succeed"); } assertFalse(retry.shouldRetryRequest(command, response), "Expected retry to fail on attempt 5"); verify(command, response, cache); } |
RetryOnRenew implements HttpRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { boolean retry = false; switch (response.getStatusCode()) { case 401: Multimap<String, String> headers = command.getCurrentRequest().getHeaders(); if (headers != null && headers.containsKey(AuthHeaders.AUTH_USER) && headers.containsKey(AuthHeaders.AUTH_KEY) && !headers.containsKey(AuthHeaders.AUTH_TOKEN)) { retry = false; } else { Integer count = retryCountMap.getIfPresent(command); if (count == null) { logger.debug("invalidating authentication token - first time for %s", command); retryCountMap.put(command, 1); authenticationResponseCache.invalidateAll(); retry = true; } else { if (count + 1 >= NUM_RETRIES) { logger.debug("too many 401s - giving up after: %s for %s", count, command); retry = false; } else { logger.debug("invalidating authentication token - retry %s for %s", count, command); retryCountMap.put(command, count + 1); authenticationResponseCache.invalidateAll(); Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); retry = true; } } } break; case 408: return backoffHandler.shouldRetryRequest(command, response); } return retry; } @Inject protected RetryOnRenew(LoadingCache<Credentials, Auth> authenticationResponseCache,
BackoffLimitedRetryHandler backoffHandler); @Override boolean shouldRetryRequest(HttpCommand command, HttpResponse response); } | @Test public void test401ShouldRetry() { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = createMock(HttpRequest.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, Auth> cache = createMock(LoadingCache.class); BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class); expect(command.getCurrentRequest()).andReturn(request); cache.invalidateAll(); expectLastCall(); expect(response.getPayload()).andReturn(Payloads.newStringPayload("token expired, please renew")).anyTimes(); expect(response.getStatusCode()).andReturn(401).atLeastOnce(); replay(command); replay(response); replay(cache); replay(backoffHandler); RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler); assertTrue(retry.shouldRetryRequest(command, response)); verify(command); verify(response); verify(cache); verify(backoffHandler); }
@Test public void test401ShouldRetry4Times() { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = createMock(HttpRequest.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, Auth> cache = createMock(LoadingCache.class); BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class); expect(command.getCurrentRequest()).andReturn(request).anyTimes(); expect(request.getHeaders()).andStubReturn(null); cache.invalidateAll(); expectLastCall().anyTimes(); expect(response.getPayload()).andReturn(Payloads.newStringPayload("")) .anyTimes(); expect(response.getStatusCode()).andReturn(401).anyTimes(); replay(command, request, response, cache); RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler); for (int i = 0; i < RetryOnRenew.NUM_RETRIES - 1; ++i) { assertTrue(retry.shouldRetryRequest(command, response), "Expected retry to succeed"); } assertFalse(retry.shouldRetryRequest(command, response), "Expected retry to fail on attempt " + RetryOnRenew.NUM_RETRIES); verify(command, response, cache); }
@Test public void test408ShouldRetry() { HttpCommand command = createMock(HttpCommand.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, Auth> cache = createMock(LoadingCache.class); BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class); expect(backoffHandler.shouldRetryRequest(command, response)).andReturn(true).once(); expect(response.getStatusCode()).andReturn(408).once(); replay(command); replay(response); replay(cache); replay(backoffHandler); RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler); assertTrue(retry.shouldRetryRequest(command, response)); verify(command); verify(response); verify(cache); verify(backoffHandler); }
@Test public void test404ShouldNotRetry() { HttpCommand command = createMock(HttpCommand.class); HttpRequest request = createMock(HttpRequest.class); HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") LoadingCache<Credentials, Auth> cache = createMock(LoadingCache.class); BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class); expect(response.getStatusCode()).andReturn(404).once(); replay(command); replay(response); replay(cache); replay(backoffHandler); RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler); assertTrue(!retry.shouldRetryRequest(command, response)); verify(command); verify(response); verify(cache); verify(backoffHandler); } |
SimpleDateFormatDateService implements DateService { @Override public final Date iso8601DateParse(String toParse) { if (toParse.length() < 10) throw new IllegalArgumentException("incorrect date format " + toParse); String tz = findTZ(toParse); toParse = trimToMillis(toParse); toParse = trimTZ(toParse); toParse += tz; if (toParse.charAt(10) == ' ') toParse = new StringBuilder(toParse).replace(10, 11, "T").toString(); synchronized (iso8601SimpleDateFormat) { try { return iso8601SimpleDateFormat.parse(toParse); } catch (ParseException pe) { throw new IllegalArgumentException("Error parsing data at " + pe.getErrorOffset(), pe); } } } @Override final String cDateFormat(Date date); @Override final String cDateFormat(); @Override final Date cDateParse(String toParse); @Override final String rfc822DateFormat(Date date); @Override final String rfc822DateFormat(); @Override final Date rfc822DateParse(String toParse); @Override final String iso8601SecondsDateFormat(); @Override final String iso8601DateFormat(Date date); @Override final String iso8601DateFormat(); @Override final Date iso8601DateParse(String toParse); @Override final Date iso8601SecondsDateParse(String toParse); @Override @SuppressWarnings("UnusedException") Date iso8601DateOrSecondsDateParse(String toParse); @Override String iso8601SecondsDateFormat(Date date); @Override final String rfc1123DateFormat(Date date); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); } | @Test(enabled = false) public void testCorrectHandlingOfMillis() { Date date = new SimpleDateFormatDateService().iso8601DateParse("2011-11-07T11:19:13.38225Z"); assertEquals("Mon Nov 07 11:19:13 GMT 2011", date.toString()); }
@Test(enabled = false) public void testCorrectHandlingOfMillisWithNoTimezone() { Date date = new SimpleDateFormatDateService().iso8601DateParse("2009-02-03T05:26:32.612278"); assertEquals("Tue Feb 03 05:26:32 GMT 2009", date.toString()); } |
MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier extends ForwardingObject implements
Supplier<T> { @Override public T get() { try { return cache.get("FOO").orNull(); } catch (UncheckedExecutionException e) { throw propagate(e.getCause()); } catch (ExecutionException e) { throw propagate(e.getCause()); } } MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier(AtomicReference<AuthorizationException> authException,
Supplier<T> delegate, long duration, TimeUnit unit, ValueLoadedCallback<T> valueLoadedCallback); static MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<T> create(
AtomicReference<AuthorizationException> authException, Supplier<T> delegate, long duration, TimeUnit unit); static MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<T> create(
AtomicReference<AuthorizationException> authException, Supplier<T> delegate, long duration, TimeUnit unit,
ValueLoadedCallback<T> valueLoadedCallback); @Override T get(); @Override String toString(); } | @Test public void testLoaderNormal() { AtomicReference<AuthorizationException> authException = newReference(); assertEquals(new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(ofInstance("foo"), authException, new ValueLoadedCallback.NoOpCallback<String>()).load("KEY").get(), "foo"); assertEquals(authException.get(), null); }
@Test(expectedExceptions = AuthorizationException.class) public void testLoaderThrowsAuthorizationExceptionAndAlsoSetsExceptionType() { AtomicReference<AuthorizationException> authException = newReference(); try { new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(new Supplier<String>() { public String get() { throw new AuthorizationException(); } }, authException, new ValueLoadedCallback.NoOpCallback<String>()).load("KEY"); } finally { assertEquals(authException.get().getClass(), AuthorizationException.class); } }
@Test(expectedExceptions = AuthorizationException.class) public void testLoaderThrowsAuthorizationExceptionAndAlsoSetsExceptionTypeWhenNested() { AtomicReference<AuthorizationException> authException = newReference(); try { new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(new Supplier<String>() { public String get() { throw new RuntimeException(new ExecutionException(new AuthorizationException())); } }, authException, new ValueLoadedCallback.NoOpCallback<String>()).load("KEY"); } finally { assertEquals(authException.get().getClass(), AuthorizationException.class); } }
@Test(expectedExceptions = AuthorizationException.class) public void testLoaderThrowsAuthorizationExceptionAndAlsoSetsExceptionTypeWhenInUncheckedExecutionException() { AtomicReference<AuthorizationException> authException = newReference(); try { new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(new Supplier<String>() { public String get() { throw new UncheckedExecutionException(new AuthorizationException()); } }, authException, new ValueLoadedCallback.NoOpCallback<String>()).load("KEY"); } finally { assertEquals(authException.get().getClass(), AuthorizationException.class); } }
@Test(expectedExceptions = RuntimeException.class) public void testLoaderThrowsOriginalExceptionAndAlsoSetsExceptionTypeWhenNestedAndNotAuthorizationException() { AtomicReference<AuthorizationException> authException = newReference(); try { new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(new Supplier<String>() { public String get() { throw new RuntimeException(new IllegalArgumentException("foo")); } }, authException, new ValueLoadedCallback.NoOpCallback<String>()).load("KEY"); } finally { assertEquals(authException.get().getClass(), RuntimeException.class); } } |
BindMapToStringPayload implements MapBinder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { checkNotNull(postParams, "postParams"); GeneratedHttpRequest r = GeneratedHttpRequest.class.cast(checkNotNull(request, "request")); Invokable<?, ?> invoked = r.getInvocation().getInvokable(); checkArgument(invoked.isAnnotationPresent(Payload.class), "method %s must have @Payload annotation to use this binder", invoked); String payload = invoked.getAnnotation(Payload.class).value(); if (!postParams.isEmpty()) { payload = urlDecode(expand(payload, postParams)); } return (R) request.toBuilder().payload(payload).build(); } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Map<String, Object> postParams); @Override R bindToRequest(R request, Object payload); } | @Test public void testCorrect() throws SecurityException, NoSuchMethodException { Invokable<?, Object> testPayload = method(TestPayload.class, "testPayload", String.class); GeneratedHttpRequest request = GeneratedHttpRequest.builder() .invocation(Invocation.create(testPayload, ImmutableList.<Object> of("robot"))) .method("POST").endpoint("http: GeneratedHttpRequest newRequest = binder().bindToRequest(request, ImmutableMap.<String, Object> of("fooble", "robot")); assertEquals(newRequest.getRequestLine(), request.getRequestLine()); assertEquals(newRequest.getPayload().getRawContent(), "name robot"); }
@Test public void testDecodes() throws SecurityException, NoSuchMethodException { Invokable<?, Object> testPayload = method(TestPayload.class, "changeAdminPass", String.class); GeneratedHttpRequest request = GeneratedHttpRequest.builder() .invocation(Invocation.create(testPayload, ImmutableList.<Object> of("foo"))) .method("POST").endpoint("http: GeneratedHttpRequest newRequest = binder() .bindToRequest(request, ImmutableMap.<String, Object>of("adminPass", "foo")); assertEquals(newRequest.getRequestLine(), request.getRequestLine()); assertEquals(newRequest.getPayload().getRawContent(), "{\"changePassword\":{\"adminPass\":\"foo\"}}"); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustHavePayloadAnnotation() throws SecurityException, NoSuchMethodException { Invokable<?, Object> noPayload = method(TestPayload.class, "noPayload", String.class); GeneratedHttpRequest request = GeneratedHttpRequest.builder() .invocation(Invocation.create(noPayload, ImmutableList.<Object> of("robot"))) .method("POST").endpoint("http: binder().bindToRequest(request, ImmutableMap.<String, Object>of("fooble", "robot")); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeMap() { BindMapToStringPayload binder = binder(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: binder.bindToRequest(request, new File("foo")); }
@Test(expectedExceptions = NullPointerException.class) public void testNullIsBad() { BindMapToStringPayload binder = binder(); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); } |
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector,
@Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion,
HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator,
GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller,
@Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader,
@Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); } | @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "param\\{robbie\\} for invocation TestQuery.foo3") public void testNiceNPEQueryParam() throws Exception { processor.apply(Invocation.create(method(TestQuery.class, "foo3", String.class), Lists.<Object> newArrayList((String) null))); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "postNonnull parameter 1") public void testCreatePostRequestNullNotOk2() throws Exception { Invokable<?, ?> method = method(TestPost.class, "postNonnull", String.class); processor.apply(Invocation.create(method, Lists.<Object> newArrayList((String) null))); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "fooble") public void testMultipartWithStringPartNullNotOkay() throws Exception { Invokable<?, ?> method = method(TestMultipartForm.class, "withStringPart", String.class); processor.apply(Invocation.create(method, Lists.<Object> newArrayList((String) null))); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "param\\{name\\} for invocation TestMultipartForm.withParamStringPart") public void testMultipartWithParamStringPartNullNotOk() throws Exception { Invokable<?, ?> method = method(TestMultipartForm.class, "withParamStringPart", String.class, String.class); processor.apply(Invocation.create(method, Lists.<Object> newArrayList(null, "foobledata"))); }
@Test public void testRequestFilter() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestRequestFilter.class, "get"); GeneratedHttpRequest request = processor.apply(Invocation.create(method)); assertEquals(request.getFilters().size(), 2); assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter1.class); assertEquals(request.getFilters().get(1).getClass(), TestRequestFilter2.class); }
@Test public void testRequestFilterAddConnection() { Invokable<?, ?> method = method(TestRequestFilter.class, "post"); Invocation invocation = Invocation.create(method, ImmutableList.<Object>of(HttpRequest.builder().method("POST").endpoint("http: GeneratedHttpRequest request = processor.apply(invocation); assertEquals(request.getFilters().size(), 1); assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter1.class); Properties overrides = new Properties(); overrides.setProperty(Constants.PROPERTY_CONNECTION_CLOSE_HEADER, "true"); Injector injector = ContextBuilder.newBuilder(forApiOnEndpoint(Callee.class, "http: .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), new AbstractModule() { protected void configure() { bind(new TypeLiteral<Supplier<URI>>() { }).annotatedWith(Localhost2.class).toInstance( Suppliers.ofInstance(URI.create("http: }})) .overrides(overrides).buildInjector(); RestAnnotationProcessor newProcessor = injector.getInstance(RestAnnotationProcessor.class); request = newProcessor.apply(invocation); assertEquals(request.getFilters().size(), 2); assertEquals(request.getFilters().get(1).getClass(), ConnectionCloseHeader.class); }
@Test public void testSkipEncoding() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestEncoding.class, "twoPaths", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("1", "localhost"))); assertEquals(request.getEndpoint().getPath(), "/1/localhost"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 0); }
@Test public void testEncodingPath() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestEncoding.class, "twoPaths", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("/", "localhost"))); assertEquals(request.getEndpoint().getPath(), " assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 0); }
@Test(enabled = false) public void testConstantPathParam() throws Exception { Invokable<?, ?> method = method(TestConstantPathParam.class, "twoPaths", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("1", "localhost"))); assertRequestLineEquals(request, "GET http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "param\\{path\\} for invocation TestPath.onePath") public void testNiceNPEPathParam() throws Exception { Invokable<?, ?> method = method(TestPath.class, "onePath", String.class); processor.apply(Invocation.create(method, Lists.<Object> newArrayList((String) null))); }
@Test public void testPathParamExtractor() throws Exception { Invokable<?, ?> method = method(TestPath.class, "onePathParamExtractor", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("localhost"))); assertRequestLineEquals(request, "GET http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); }
@Test public void testPathParamEncoding() throws Exception { Invokable<?, ?> method = method(TestPath.class, "onePath", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("foo/bar"))); assertRequestLineEquals(request, "GET http: request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("foo%2Fbar"))); assertRequestLineEquals(request, "GET http: method = method(TestPath.class, "encodedParams", String.class, String.class, String.class); request = processor.apply(Invocation.create(method, ImmutableList.<Object>of("encoded%2Fparam", "encode%2Fdouble", "foo%20bar"))); assertRequestLineEquals(request, "GET http: }
@Test public void testQueryParamExtractor() throws Exception { Invokable<?, ?> method = method(TestPath.class, "oneQueryParamExtractor", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("localhost"))); assertRequestLineEquals(request, "GET http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); }
@Test public void testEncodedQueryParam() throws Exception { Invokable<?, ?> method = method(TestPath.class, "encodedQueryParam", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("foo%20bar"))); assertRequestLineEquals(request, "GET http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); method = method(TestPath.class, "encodedQueryListParam", List.class); String [] args = {"foo%20bar", "foo/bar"}; request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(ImmutableList.of("foo%20bar", "foo/bar")))); assertRequestLineEquals(request, "GET http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); }
@Test(dataProvider = "queryStrings") public void testQueryParam(String val) { Invokable<?, ?> method = method(TestPath.class, "oneQueryParam", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(val))); assertRequestLineEquals(request, String.format("GET http: urlEncode(val, '/', ','))); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); }
@Test public void testFormParamExtractor() throws Exception { Invokable<?, ?> method = method(TestPath.class, "oneFormParamExtractor", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("localhost"))); assertRequestLineEquals(request, "POST http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "one=l", "application/x-www-form-urlencoded", false); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "param\\{one\\} for invocation TestPath.oneFormParamExtractor") public void testNiceNPEFormParam() throws Exception { Invokable<?, ?> method = method(TestPath.class, "oneFormParamExtractor", String.class); processor.apply(Invocation.create(method, Lists.<Object> newArrayList((String) null))); }
@Test public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestHeader.class, "twoHeader", String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))).getHeaders(); assertEquals(headers.size(), 2); assertEquals(headers.get("slash"), ImmutableList.of("/robot")); assertEquals(headers.get("hyphen"), ImmutableList.of("-robot")); }
@Test public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestClassHeader.class, "oneHeader", String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/robot")); }
@Test public void testBuildOneHeader() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestHeader.class, "oneHeader", String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/robot")); }
@Test public void testBuildOneHeaderUnencoded() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestHeader.class, "oneHeader", String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("apples#?:$&'\"<>čॐ"))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/apples#?:$&'\"<>čॐ")); }
@Test public void testBuildOneHeaderEncoded() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestHeader.class, "oneHeaderEncoded", String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("apples#?:$&'\"<>čॐ"))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/apples%23%3F%3A%24%26%27%22%3C%3E%C4%8D%E0%A5%90")); }
@Test public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestHeader.class, "twoHeaders", String.class, String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "eggs"))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/robot/eggs")); }
@Test public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestHeader.class, "twoHeadersOutOfOrder", String.class, String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "eggs"))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/eggs/robot")); }
@Test public void testBuildTwoHeadersMixedEncoding() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestHeader.class, "twoHeadersMixedEncoding", String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("apples#?:$&'\"<>čॐ"))).getHeaders(); assertEquals(headers.size(), 2); assertEquals(headers.get("unencoded"), ImmutableList.of("/apples#?:$&'\"<>čॐ")); assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/apples%23%3F%3A%24%26%27%22%3C%3E%C4%8D%E0%A5%90")); }
@Test public void testQueryInOptions() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestQueryReplace.class, "queryInOptions", String.class, TestReplaceQueryOptions.class); String query = processor .apply(Invocation.create(method, ImmutableList.<Object> of("robot", new TestReplaceQueryOptions()))).getEndpoint() .getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); }
@Test public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestQueryReplace.class, "twoQuery", String.class); String query = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getEndpoint().getQuery(); assertEquals(query, "slash=/robot&hyphen=-robot"); }
@Test public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestClassQuery.class, "oneQuery", String.class); String query = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); }
@Test public void testBuildOneQuery() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestQueryReplace.class, "oneQuery", String.class); String query = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); }
@Test public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestQueryReplace.class, "twoQuerys", String.class, String.class); String query = processor .apply(Invocation.create(method, ImmutableList.<Object> of("robot", "eggs"))).getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/robot/eggs"); }
@Test public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestQueryReplace.class, "twoQuerysOutOfOrder", String.class, String.class); String query = processor .apply(Invocation.create(method, ImmutableList.<Object> of("robot", "eggs"))).getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/eggs/robot"); }
@Test(dataProvider = "strings") public void testCreateGetRequest(String key) throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Invokable<?, ?> method = method(TestRequest.class, "get", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(key, "localhost"))); assertEquals(request.getEndpoint().getHost(), "localhost"); String expectedPath = "/" + URLEncoder.encode(key, "UTF-8").replaceAll("\\+", "%20"); assertEquals(request.getEndpoint().getRawPath(), expectedPath); assertEquals(request.getEndpoint().getPath(), "/" + key); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of("localhost")); }
@Test public void testVirtualHostMethod() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestVirtualHostMethod.class, "get", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("1", "localhost"))); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of("localhost:9999")); }
@Test public void testVirtualHost() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestVirtualHost.class, "get", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("1", "localhost"))); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of("localhost:9999")); }
@Test public void testHostPrefix() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestVirtualHost.class, "getPrefix", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("1", "holy"))); assertEquals(request.getEndpoint().getHost(), "holy.localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 0); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testHostPrefixEmpty() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestVirtualHost.class, "getPrefix", String.class, String.class); processor.apply(Invocation.create(method, ImmutableList.<Object> of("1", ""))); }
@Test public void testOneHeader() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestHeaders.class, "oneHeader", String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("header"), ImmutableList.of("robot")); }
@Test public void testOneIntHeader() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestHeaders.class, "oneIntHeader", int.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of(1))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("header"), ImmutableList.of("1")); }
@Test public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestHeaders.class, "twoDifferentHeaders", String.class, String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "egg"))).getHeaders(); assertEquals(headers.size(), 2); assertEquals(headers.get("header1"), ImmutableList.of("robot")); assertEquals(headers.get("header2"), ImmutableList.of("egg")); }
@Test public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestHeaders.class, "twoSameHeaders", String.class, String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "egg"))).getHeaders(); assertEquals(headers.size(), 2); Collection<String> values = headers.get("header"); assert values.contains("robot"); assert values.contains("egg"); }
@Test public void testPut() throws Exception { Invokable<?, ?> method = method(TestPayload.class, "put", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("test"))); assertRequestLineEquals(request, "PUT http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "test", "application/unknown", false); }
@Test public void putWithPath() throws Exception { Invokable<?, ?> method = method(TestPayload.class, "putWithPath", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("rabble", "test"))); assertRequestLineEquals(request, "PUT http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "test", "application/unknown", false); }
@Test public void testBuildTwoForm() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestFormReplace.class, "twoForm", String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getPayload().getRawContent(); assertEquals(form, "slash=/robot&hyphen=-robot"); }
@Test public void testBuildOneClassForm() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestClassForm.class, "oneForm", String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot"); }
@Test public void testBuildOneForm() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestFormReplace.class, "oneForm", String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot"); }
@Test public void testBuildTwoForms() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestFormReplace.class, "twoForms", String.class, String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "eggs"))) .getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot/eggs"); }
@Test public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestFormReplace.class, "twoFormsOutOfOrder", String.class, String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "eggs"))) .getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/eggs/robot"); } |
ParseBlobFromHeadersAndHttpContent implements Function<HttpResponse, Blob>,
InvocationContext<ParseBlobFromHeadersAndHttpContent> { public Blob apply(HttpResponse from) { checkNotNull(from, "request"); MutableBlobMetadata metadata = metadataParser.apply(from); Blob blob = blobFactory.create(metadata); blob.getAllHeaders().putAll(from.getHeaders()); blob.setPayload(from.getPayload()); return blob; } @Inject ParseBlobFromHeadersAndHttpContent(ParseSystemAndUserMetadataFromHeaders metadataParser,
Blob.Factory blobFactory); Blob apply(HttpResponse from); @Override ParseBlobFromHeadersAndHttpContent setContext(HttpRequest request); } | @Test public void testParseContentLengthWhenContentRangeSet() throws HttpException { ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class); ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider); HttpResponse response = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader("Content-Range", "0-10485759/20232760").build(); response.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); response.getPayload().getContentMetadata().setContentLength(10485760L); MutableBlobMetadata meta = blobMetadataProvider.get(); expect(metadataParser.apply(response)).andReturn(meta); replay(metadataParser); Blob object = callable.apply(response); assertEquals(object.getPayload().getContentMetadata().getContentLength(), Long.valueOf(10485760)); assertEquals(object.getAllHeaders().get("Content-Range"), ImmutableList.of("0-10485759/20232760")); }
@Test(expectedExceptions = NullPointerException.class) public void testCall() throws HttpException { ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class); ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider); HttpResponse response = HttpResponse.builder() .statusCode(200).message("ok") .addHeader("Content-Range", (String) null).build(); callable.apply(response); }
@Test public void testParseContentLengthWhenContentRangeSet() throws HttpException { ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class); ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider); HttpResponse response = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader("Content-Range", "0-10485759/20232760").build(); response.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); response.getPayload().getContentMetadata().setContentLength(10485760l); MutableBlobMetadata meta = blobMetadataProvider.get(); expect(metadataParser.apply(response)).andReturn(meta); replay(metadataParser); Blob object = callable.apply(response); assertEquals(object.getPayload().getContentMetadata().getContentLength(), Long.valueOf(10485760)); assertEquals(object.getAllHeaders().get("Content-Range"), ImmutableList.of("0-10485759/20232760")); } |
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } @Inject private RestAnnotationProcessor(Injector injector,
@Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion,
HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator,
GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller,
@Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader,
@Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); } | @Test public void testOneEndpointParam() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestEndpointParams.class, "oneEndpointParam", String.class); URI uri = RestAnnotationProcessor.getEndpointInParametersOrNull( Invocation.create(method, ImmutableList.<Object> of("robot")), injector); assertEquals(uri, URI.create("robot")); }
@Test(expectedExceptions = IllegalStateException.class) public void testTwoDifferentEndpointParams() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestEndpointParams.class, "twoEndpointParams", String.class, String.class); RestAnnotationProcessor.getEndpointInParametersOrNull( Invocation.create(method, ImmutableList.<Object> of("robot", "egg")), injector); } |
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>,
InvocationContext<ParseSystemAndUserMetadataFromHeaders> { public MutableBlobMetadata apply(HttpResponse from) { checkNotNull(from, "request"); checkState(name != null, "name must be initialized by now"); MutableBlobMetadata to = metadataFactory.get(); to.setName(name); to.setUri(endpoint); if (from.getPayload() != null) HttpUtils.copy(from.getPayload().getContentMetadata(), to.getContentMetadata()); addETagTo(from, to); parseLastModifiedOrThrowException(from, to); addUserMetadataTo(from, to); return to; } @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); } | @Test public void testApplySetsName() { HttpResponse from = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader(HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT").build(); from.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); from.getPayload().getContentMetadata().setContentLength(100L); BlobMetadata metadata = parser.apply(from); assertEquals(metadata.getName(), "key"); }
@Test public void testApplySetsName() { HttpResponse from = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader(HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT").build(); from.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); from.getPayload().getContentMetadata().setContentLength(100l); BlobMetadata metadata = parser.apply(from); assertEquals(metadata.getName(), "key"); }
@Test public void testNoContentOn204IsOk() { HttpResponse from = HttpResponse.builder() .statusCode(204).message("ok") .addHeader(HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT").build(); parser.apply(from); } |
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector,
@Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion,
HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator,
GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller,
@Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader,
@Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); } | @Test(expectedExceptions = NullPointerException.class) public void testAddHostNullWithHost() throws Exception { assertNull(RestAnnotationProcessor.addHostIfMissing(null, null)); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddHostWithHostHasNoHost() throws Exception { assertNull(RestAnnotationProcessor.addHostIfMissing(null, new URI("/no/host"))); }
@Test public void testAddHostNullOriginal() throws Exception { assertNull(RestAnnotationProcessor.addHostIfMissing(null, new URI("http: }
@Test public void testAddHostOriginalHasHost() throws Exception { URI original = new URI("http: URI result = RestAnnotationProcessor.addHostIfMissing(original, new URI("http: assertEquals(original, result); }
@Test public void testAddHostIfMissing() throws Exception { URI result = RestAnnotationProcessor.addHostIfMissing(new URI("/bar"), new URI("http: assertEquals(new URI("http: }
@Test public void testComplexHost() throws Exception { URI result = RestAnnotationProcessor.addHostIfMissing(new URI("bar"), new URI("http: assertEquals(new URI("http: } |
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); } | @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()); } |
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; } | @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))); } |
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; } | @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))); } |
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } 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; } | @Test public void testX509CertificateFromPemDefault() throws IOException, CertificateException { Pems.x509Certificate(ByteSource.wrap(CERTIFICATE.getBytes(Charsets.UTF_8)), null); }
@Test public void testX509CertificateFromPemSuppliedCertFactory() throws IOException, CertificateException { Pems.x509Certificate(ByteSource.wrap(CERTIFICATE.getBytes(Charsets.UTF_8)), CertificateFactory.getInstance("X.509")); } |
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max,
String commandDescription); static final BackoffLimitedRetryHandler INSTANCE; } | @Test void testExponentialBackoffDelayDefaultMaxInterval500() throws InterruptedException { long period = 500; long acceptableDelay = period - 1; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period, period + acceptableDelay); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 2, 5, "TEST FAILURE: 2"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period * 4, period * 9); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 3, 5, "TEST FAILURE: 3"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period * 9, period * 10); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 4, 5, "TEST FAILURE: 4"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period * 10, period * 11); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 5, 5, "TEST FAILURE: 5"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period * 10, period * 11); }
@Test(enabled = false) void testExponentialBackoffDelaySmallInterval5() throws InterruptedException { long period = 5; long acceptableDelay = period - 1; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period, period + acceptableDelay); }
@Test(enabled = false) void testExponentialBackoffDelaySmallInterval1() throws InterruptedException { long period = 1; long acceptableDelay = 5; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period, period + acceptableDelay); }
@Test void testExponentialBackoffDelaySmallInterval0() throws InterruptedException { long period = 0; long acceptableDelay = 5; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period, period + acceptableDelay); }
@Test void testExponentialBackoffDelayDefaultMaxInterval500() throws InterruptedException { long period = 500; long acceptableDelay = period - 1; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assert (elapsedTime >= period - 1) : elapsedTime; assertTrue(elapsedTime < period + acceptableDelay); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 2, 5, "TEST FAILURE: 2"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assert (elapsedTime >= period * 4 - 1) : elapsedTime; assertTrue(elapsedTime < period * 9); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 3, 5, "TEST FAILURE: 3"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assert (elapsedTime >= period * 9 - 1) : elapsedTime; assertTrue(elapsedTime < period * 10); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 4, 5, "TEST FAILURE: 4"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assert (elapsedTime >= period * 10 - 1) : elapsedTime; assertTrue(elapsedTime < period * 11); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 5, 5, "TEST FAILURE: 5"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assert (elapsedTime >= period * 10 - 1) : elapsedTime; assertTrue(elapsedTime < period * 11); } |
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public boolean shouldRetryRequest(HttpCommand command, IOException error) { return ifReplayableBackoffAndReturnTrue(command); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max,
String commandDescription); static final BackoffLimitedRetryHandler INSTANCE; } | @Test void testInputStreamIsNotClosed() throws SecurityException, NoSuchMethodException, IOException { HttpCommand command = createCommand(); HttpResponse response = HttpResponse.builder().statusCode(500).build(); InputStream inputStream = new InputStream() { int count = 2; @Override public void close() { fail("The retry handler should not close the response stream"); } @Override public int read() throws IOException { return count < 0 ? -1 : --count; } @Override public int available() throws IOException { return count < 0 ? 0 : count; } }; response.setPayload(Payloads.newInputStreamPayload(inputStream)); response.getPayload().getContentMetadata().setContentLength(1L); assertEquals(response.getPayload().openStream().available(), 2); assertEquals(response.getPayload().openStream().read(), 1); handler.shouldRetryRequest(command, response); assertEquals(response.getPayload().openStream().available(), 1); assertEquals(response.getPayload().openStream().read(), 0); }
@Test void testClosesInputStream() throws InterruptedException, IOException, SecurityException, NoSuchMethodException { HttpCommand command = createCommand(); HttpResponse response = HttpResponse.builder().statusCode(400).build(); InputStream inputStream = new InputStream() { boolean isOpen = true; @Override public void close() { this.isOpen = false; } int count = 1; @Override public int read() throws IOException { if (this.isOpen) return (count > -1) ? count-- : -1; else return -1; } @Override public int available() throws IOException { if (this.isOpen) return count; else return 0; } }; response.setPayload(Payloads.newInputStreamPayload(inputStream)); response.getPayload().getContentMetadata().setContentLength(1l); assertEquals(response.getPayload().getInput().available(), 1); assertEquals(response.getPayload().getInput().read(), 1); handler.shouldRetryRequest(command, response); assertEquals(response.getPayload().getInput().available(), 0); assertEquals(response.getPayload().getInput().read(), -1); }
@Test void testIncrementsFailureCount() throws InterruptedException, IOException, SecurityException, NoSuchMethodException { HttpCommand command = createCommand(); HttpResponse response = HttpResponse.builder().statusCode(400).build(); handler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 1); handler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 2); handler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 3); }
@Test void testDisallowsExcessiveRetries() throws InterruptedException, IOException, SecurityException, NoSuchMethodException { HttpCommand command = createCommand(); HttpResponse response = HttpResponse.builder().statusCode(400).build(); assertEquals(handler.shouldRetryRequest(command, response), true); assertEquals(handler.shouldRetryRequest(command, response), true); assertEquals(handler.shouldRetryRequest(command, response), true); assertEquals(handler.shouldRetryRequest(command, response), true); assertEquals(handler.shouldRetryRequest(command, response), true); assertEquals(handler.shouldRetryRequest(command, response), false); } |
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); } | @Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfNoRateLimit() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(450).build(); assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfNotReplayable() { Payload payload = newInputStreamPayload(new ByteArrayInputStream(new byte[0])); HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: .payload(payload).build()); HttpResponse response = HttpResponse.builder().statusCode(429).build(); try { assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); } finally { releasePayload(command.getCurrentRequest()); } }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfNoRateLimitInfo() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).build(); assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfTooMuchWait() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, "400").build(); assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testRequestIsDelayed() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, "5").build(); long start = System.currentTimeMillis(); assertTrue(rateLimitRetryHandler.shouldRetryRequest(command, response)); assertTrue(System.currentTimeMillis() - start > 2500); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfRequestIsAborted() throws Exception { final HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: .build()); final HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, "10").build(); final Thread requestThread = Thread.currentThread(); Thread killer = new Thread() { @Override public void run() { Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS); requestThread.interrupt(); } }; killer.start(); assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testIncrementsFailureCount() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).build(); rateLimitRetryHandler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 1); rateLimitRetryHandler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 2); rateLimitRetryHandler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 3); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDisallowExcessiveRetries() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, "0").build(); for (int i = 0; i < 5; i++) { assertTrue(rateLimitRetryHandler.shouldRetryRequest(command, response)); } assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); } |
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; } | @Test public void testNullRange() { GetOptions options = new GetOptions(); assertNull(options.getRange()); } |
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; } | @Test public void testIfETagMatches() { GetOptions options = new GetOptions(); options.ifETagMatches(etag); matchesHex(options.getIfMatch()); }
@Test(expectedExceptions = NullPointerException.class) public void testIfETagMatchesNPE() { ifETagMatches(null); } |
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; } | @Test public void testIfETagDoesntMatch() { GetOptions options = new GetOptions(); options.ifETagDoesntMatch(etag); matchesHex(options.getIfNoneMatch()); }
@Test(expectedExceptions = NullPointerException.class) public void testIfETagDoesntMatchNPE() { ifETagDoesntMatch(null); } |
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } static UriBuilder uriBuilder(CharSequence template); static UriBuilder uriBuilder(URI uri); static boolean lastCharIsToken(CharSequence left, char token); static char lastChar(CharSequence in); static char firstChar(CharSequence in); static boolean isToken(CharSequence right, char token); } | @Test(dataProvider = "strings") public void testQuery(String val) { assertThat(uriBuilder("https: .isEqualTo("moo=" + val); assertThat(uriBuilder("https: .isEqualTo("moo=" + urlEncode(val, '/', ',')); assertThat(uriBuilder("https: .getQuery()) .isEqualTo("foo=bar&kung=fu&moo=" + val); assertThat(uriBuilder("https: .getRawQuery()) .isEqualTo("foo=bar&kung=fu&moo=" + urlEncode(val, '/', ',')); assertThat(uriBuilder("https: .isEqualTo("moo=" + val); assertThat(uriBuilder("https: .isEqualTo("https: assertThat(uriBuilder("https: .getRawQuery()) .isEqualTo("moo=" + urlEncode(val, '/', ',')); assertThat(uriBuilder("https: .getPath()) .isEqualTo("/repos/bob"); }
@Test(dataProvider = "strings") public void testReplaceQueryIsEncoded(String key) { assertThat(uriBuilder("/redirect").addQuery("foo", key).build().getQuery()).isEqualTo("foo=" + key); assertThat(uriBuilder("/redirect").addQuery("foo", key).build().getRawQuery()) .isEqualTo("foo=" + urlEncode(key, '/', ',')); }
@Test(dataProvider = "strings") public void testQuery(String val) { assertEquals(uriBuilder("https: assertEquals(uriBuilder("https: + urlEncode(val, '/', ',')); assertEquals(uriBuilder("https: "https: assertEquals(uriBuilder("https: "https: assertEquals(uriBuilder("https: "https: assertEquals( uriBuilder("https: "https: }
@Test(dataProvider = "strings") public void testPath(String path) { assertEquals(uriBuilder("https: assertEquals(uriBuilder("https: + urlEncode(path, '/', ':', ';', '=')); assertEquals(uriBuilder("https: "https: assertEquals(uriBuilder("https: "https: assertEquals(uriBuilder("https: + path); assertEquals(uriBuilder("https: "https: }
@Test(dataProvider = "strings") public void testAppendPath(String path) { assertEquals(uriBuilder("https: assertEquals(uriBuilder("https: + urlEncode(path, '/', ':', ';', '=')); assertEquals(uriBuilder("https: "https: assertEquals(uriBuilder("https: "https: assertEquals(uriBuilder("https: "https: assertEquals(uriBuilder("https: .toASCIIString(), "https: }
@Test public void testNoDoubleSlashInPath() { assertEquals(uriBuilder("https: }
@Test public void testWhenUrnInPath() { assertEquals(uriBuilder("https: "https: }
@Test public void testWhenMatrixOnPath() { assertEquals( uriBuilder("https: .toASCIIString(), "https: }
@Test(dataProvider = "strings") public void testReplaceQueryIsEncoded(String key) { assertEquals(uriBuilder("/redirect").addQuery("foo", key).toString(), "/redirect?foo=" + key); assertEquals(uriBuilder("/redirect").addQuery("foo", key).build().toString(), "/redirect?foo=" + urlEncode(key, '/', ',')); } |
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); } | @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"); } |
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>,
InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { releasePayload(from); String location = from.getFirstHeaderOrNull(LOCATION); if (location == null) location = from.getFirstHeaderOrNull("location"); if (location != null) { URI locationUri = URI.create(location); if (locationUri.getHost() != null) return locationUri; checkState(request != null, "request should have been initialized"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); } | @Test public void testExceptionWhenNoContentOn200() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/uri-list"); expect(response.getPayload()).andReturn(payload).atLeastOnce(); expect(payload.getInput()).andReturn(null); payload.release(); replay(payload); replay(response); try { function.apply(response); } catch (Exception e) { assert e.getMessage().equals("no content"); } verify(payload); verify(response); }
@Test public void testExceptionWhenIOExceptionOn200() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/uri-list"); RuntimeException exception = new RuntimeException("bad"); expect(response.getPayload()).andReturn(payload).atLeastOnce(); expect(payload.getInput()).andThrow(exception); payload.release(); replay(payload); replay(response); try { function.apply(response); } catch (Exception e) { assert e.equals(exception); } verify(payload); verify(response); }
@Test public void testResponseOk() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/uri-list"); expect(response.getPayload()).andReturn(payload).atLeastOnce(); expect(payload.getInput()).andReturn(toInputStream("http: payload.release(); replay(payload); replay(response); assertEquals(function.apply(response), URI.create("http: verify(payload); verify(response); }
@Test public void testResponseLocationOk() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/plain"); expect(response.getFirstHeaderOrNull(LOCATION)).andReturn("http: expect(response.getPayload()).andReturn(payload).atLeastOnce(); payload.release(); replay(payload); replay(response); assertEquals(function.apply(response), URI.create("http: verify(response); verify(payload); }
@Test public void testResponseLowercaseLocationOk() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/plain"); expect(response.getFirstHeaderOrNull(LOCATION)).andReturn(null); expect(response.getFirstHeaderOrNull("location")).andReturn("http: expect(response.getPayload()).andReturn(payload).atLeastOnce(); payload.release(); replay(payload); replay(response); assertEquals(function.apply(response), URI.create("http: verify(response); verify(payload); } |
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } ParseSax(XMLReader parser, HandlerWithResult<T> handler); T apply(HttpResponse from); T parse(String from); T parse(InputStream from); T parse(InputSource from); T addDetailsAndPropagate(HttpResponse response, Exception e); T addDetailsAndPropagate(HttpResponse response, Exception e, @Nullable String text); HandlerWithResult<T> getHandler(); @Override ParseSax<T> setContext(HttpRequest request); } | @Test public void testAddDetailsAndPropagateOkWhenRequestWithNoDataAndRuntimeExceptionThrowsOriginalException() { ParseSax<String> parser = createParser(); Exception input = new RuntimeException("foo"); try { parser.addDetailsAndPropagate(null, input); } catch (RuntimeException e) { assertEquals(e, input); } }
@Test public void testAddDetailsAndPropagateOkWhenRequestWithNoDataAndExceptionPropagates() { ParseSax<String> parser = createParser(); Exception input = new Exception("foo"); try { parser.addDetailsAndPropagate(null, input); } catch (RuntimeException e) { assertEquals(e.getMessage(), "java.lang.Exception: foo"); assertEquals(e.getCause(), input); } }
@Test public void testAddDetailsAndPropagateOkWhenRequestWithNoDataAndRuntimeExceptionThrowsOriginalException() throws ExecutionException, InterruptedException, TimeoutException, IOException { ParseSax<String> parser = createParser(); Exception input = new RuntimeException("foo"); try { parser.addDetailsAndPropagate(null, input); } catch (RuntimeException e) { assertEquals(e, input); } }
@Test public void testAddDetailsAndPropagateOkWhenRequestWithNoDataAndExceptionPropagates() throws ExecutionException, InterruptedException, TimeoutException, IOException { ParseSax<String> parser = createParser(); Exception input = new Exception("foo"); try { parser.addDetailsAndPropagate(null, input); } catch (RuntimeException e) { assertEquals(e.getMessage(), "java.lang.Exception: foo"); assertEquals(e.getCause(), input); } } |
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor,
FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder,
AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); } | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = ".* parameter 0 failed to be named by AnnotationBasedNamingStrategy requiring one of javax.inject.Named") public void testSerializedNameRequiredOnAllParameters() { parameterizedCtorFactory .create(gson, TypeToken.get(WithDeserializationConstructorButWithoutSerializedName.class)); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Multiple entries with same key: foo.*") public void testNoDuplicateSerializedNamesRequiredOnAllParameters() { parameterizedCtorFactory.create(gson, TypeToken.get(DuplicateSerializedNames.class)); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "absent!") public void testValidatedConstructor() throws IOException { Gson gson = new GsonBuilder().registerTypeAdapterFactory(parameterizedCtorFactory) .registerTypeAdapterFactory(new OptionalTypeAdapterFactory()).create(); assertEquals(new ValidatedConstructor(Optional.of(0), 1), gson.fromJson("{\"foo\":0,\"bar\":1}", ValidatedConstructor.class)); gson.fromJson("{\"bar\":1}", ValidatedConstructor.class); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Incorrect count of names on annotation of .*") public void testSerializedNamesMustHaveCorrectCountOfNames() { parameterizedCtorFactory.create(gson, TypeToken.get(ValueTypeWithFactoryMissingSerializedNames.class)); }
@Test(expectedExceptions = NullPointerException.class) public void testPartialObjectStillThrows() throws IOException { TypeAdapter<ComposedObjects> adapter = parameterizedCtorFactory .create(gson, TypeToken.get(ComposedObjects.class)); assertNull(adapter.fromJson("{\"x\":{\"foo\":0,\"bar\":1}}")); } |
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); } | @Test public void testDontUseProxyForSockets() throws Exception { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds); ProxyForURI proxy = new ProxyForURI(config); Field useProxyForSockets = proxy.getClass().getDeclaredField("useProxyForSockets"); useProxyForSockets.setAccessible(true); useProxyForSockets.setBoolean(proxy, false); URI uri = new URI("socket: assertEquals(proxy.apply(uri), Proxy.NO_PROXY); }
@Test public void testUseProxyForSockets() throws Exception { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds); ProxyForURI proxy = new ProxyForURI(config); URI uri = new URI("socket: assertEquals(proxy.apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080))); }
@Test public void testUseProxyForSocketsSettingShouldntAffectHTTP() throws Exception { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds); ProxyForURI proxy = new ProxyForURI(config); Field useProxyForSockets = proxy.getClass().getDeclaredField("useProxyForSockets"); useProxyForSockets.setAccessible(true); useProxyForSockets.setBoolean(proxy, false); URI uri = new URI("http: assertEquals(proxy.apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080))); }
@Test public void testHTTPDirect() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds); URI uri = new URI("http: assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY); }
@Test public void testHTTPSDirect() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds); URI uri = new URI("https: assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY); }
@Test public void testFTPDirect() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds); URI uri = new URI("ftp: assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY); }
@Test public void testSocketDirect() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds); URI uri = new URI("socket: assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY); }
@Test public void testHTTPThroughHTTPProxy() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds); URI uri = new URI("http: assertEquals(new ProxyForURI(config).apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress( "proxy.example.com", 8080))); }
@Test public void testThroughJvmProxy() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds); URI uri = new URI("http: assertNotNull(new ProxyForURI(config).apply(uri)); }
@Test public void testThroughSystemProxy() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(true, false, Proxy.Type.HTTP, noHostAndPort, noCreds); URI uri = new URI("http: assertNotNull(new ProxyForURI(config).apply(uri)); }
@Test public void testJcloudsProxyHostsPreferredOverJvmProxy() throws URISyntaxException { ProxyConfig test = new MyProxyConfig(true, true, Proxy.Type.HTTP, hostAndPort, noCreds); ProxyConfig jclouds = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, noCreds); ProxyConfig jvm = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds); URI uri = new URI("http: assertEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jclouds).apply(uri)); assertNotEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jvm).apply(uri)); }
@Test public void testJvmProxyAlwaysPreferredOverSystem() throws URISyntaxException { ProxyConfig test = new MyProxyConfig(true, true, Proxy.Type.HTTP, noHostAndPort, noCreds); ProxyConfig jvm = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds); URI uri = new URI("http: assertEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jvm).apply(uri)); } |
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } String apply(Blob input); } | @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); } |
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod,
TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); static final long DEFAULT_PERIOD; static final long DEFAULT_MAX_PERIOD; } | @Test void testRetryAlwaysFalseMillis() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(Integer.MAX_VALUE); Predicate<String> predicate = retry(rawPredicate, 3, 1, SECONDS); stopwatch.start(); assertFalse(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(3000 - EARLY_RETURN_GRACE, duration, 3000 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000 + 1500, 3000); }
@Test void testRetryFirstTimeTrue() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(1); Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS); stopwatch.start(); assertTrue(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(0, duration, 0 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0); }
@Test void testRetryWillRunOnceOnNegativeTimeout() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(1); Predicate<String> predicate = retry(rawPredicate, -1, 1, SECONDS); stopwatch.start(); assertTrue(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(0, duration, 0 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0); }
@Test void testRetryThirdTimeTrue() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(3); Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS); stopwatch.start(); assertTrue(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(2500 - EARLY_RETURN_GRACE, duration, 2500 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000 + 1500); }
@Test void testRetryThirdTimeTrueLimitedMaxInterval() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(3); Predicate<String> predicate = retry(rawPredicate, 3, 1, 1, SECONDS); stopwatch.start(); assertTrue(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(2000 - EARLY_RETURN_GRACE, duration, 2000 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0, 1000, 2000); }
@Test void testAlwaysTrue() { Predicate<String> predicate = retry(Predicates.<String> alwaysTrue(), 3, 1, SECONDS); stopwatch.start(); predicate.apply(""); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(duration, SLOW_BUILD_SERVER_GRACE); }
@Test void testAlwaysFalseMillis() { Predicate<String> predicate = retry(Predicates.<String> alwaysFalse(), 3, 1, SECONDS); stopwatch.start(); predicate.apply(""); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(3000-EARLY_RETURN_GRACE, duration, 3000+SLOW_BUILD_SERVER_GRACE); }
@Test void testThirdTimeTrue() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(2); Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS); stopwatch.start(); predicate.apply(""); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(2500-EARLY_RETURN_GRACE, duration, 2500+SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000+1500); }
@Test void testThirdTimeTrueLimitedMaxInterval() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(2); Predicate<String> predicate = retry(rawPredicate, 3, 1, 1, SECONDS); stopwatch.start(); predicate.apply(""); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(2000-EARLY_RETURN_GRACE, duration, 2000+SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0, 1000, 2000); } |
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); } | @Test(expectedExceptions = TestException.class) public void testPropagateExceptionThatsInList() throws Throwable { Exception e = new TestException(); propagateIfPossible(e, ImmutableSet.<TypeToken<? extends Throwable>> of(typeToken(TestException.class))); }
@Test(expectedExceptions = TestException.class) public void testPropagateWrappedExceptionThatsInList() throws Throwable { Exception e = new TestException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of(typeToken(TestException.class))); }
@Test(expectedExceptions = IllegalStateException.class) public void testPropagateStandardExceptionIllegalStateException() throws Throwable { Exception e = new IllegalStateException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testPropagateStandardExceptionIllegalArgumentException() throws Throwable { Exception e = new IllegalArgumentException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testPropagateStandardExceptionUnsupportedOperationException() throws Throwable { Exception e = new UnsupportedOperationException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = AssertionError.class) public void testPropagateStandardExceptionAssertionError() throws Throwable { AssertionError e = new AssertionError(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateStandardExceptionAuthorizationException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateProvisionExceptionAuthorizationException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible( new ProvisionException(ImmutableSet.of(new Message(ImmutableList.of(), "Error in custom provider", e))), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateCreationExceptionAuthorizationException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible( new CreationException(ImmutableSet.of(new Message(ImmutableList.of(), "Error in custom provider", e))), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = InsufficientResourcesException.class) public void testPropagateStandardExceptionInsufficientResourcesException() throws Throwable { Exception e = new InsufficientResourcesException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = ResourceNotFoundException.class) public void testPropagateStandardExceptionResourceNotFoundException() throws Throwable { Exception e = new ResourceNotFoundException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = IllegalStateException.class) public void testPropagateStandardExceptionIllegalStateExceptionNestedInHttpResponseException() throws Throwable { Exception e = new IllegalStateException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testPropagateStandardExceptionIllegalArgumentExceptionNestedInHttpResponseException() throws Throwable { Exception e = new IllegalArgumentException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testPropagateStandardExceptionUnsupportedOperationExceptionNestedInHttpResponseException() throws Throwable { Exception e = new UnsupportedOperationException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateStandardExceptionAuthorizationExceptionNestedInHttpResponseException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = ResourceNotFoundException.class) public void testPropagateStandardExceptionResourceNotFoundExceptionNestedInHttpResponseException() throws Throwable { Exception e = new ResourceNotFoundException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test(expectedExceptions = HttpResponseException.class) public void testPropagateStandardExceptionHttpResponseException() throws Throwable { Exception e = new HttpResponseException("goo", createNiceMock(HttpCommand.class), null); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); } |
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); } | @Test public void testGetLastValueInMap() { assertEquals( Suppliers2.<String, String> getLastValueInMap( Suppliers.<Map<String, Supplier<String>>> ofInstance(ImmutableMap.of("foo", Suppliers.ofInstance("bar")))).get(), "bar"); } |
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); } | @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); } |
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); } | @Test public void testOfInstanceFunction() { assertEquals(Suppliers2.ofInstanceFunction().apply("foo").get(), "foo"); } |
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); } | @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"); } |
BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } | @Test public void testIfUnmodifiedSince() { Date ifUnmodifiedSince = new Date(999999L); org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.ifUnmodifiedSince(ifUnmodifiedSince); GetOptions expected = new GetOptions(); expected.ifUnmodifiedSince(ifUnmodifiedSince); assertEquals(fn.apply(in), expected); }
@Test public void testIfModifiedSince() { Date ifModifiedSince = new Date(999999L); org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.ifModifiedSince(ifModifiedSince); GetOptions expected = new GetOptions(); expected.ifModifiedSince(ifModifiedSince); assertEquals(fn.apply(in), expected); }
@Test public void testRanges() { org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.range(0, 1024); in.startAt(2048); GetOptions expected = new GetOptions(); expected.range(0, 1024); expected.startAt(2048); assertEquals(fn.apply(in), expected); }
@Test public void testRangesTail() { org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.tail(1024); GetOptions expected = new GetOptions(); expected.tail(1024); assertEquals(fn.apply(in), expected); }
@Test public void testRangesStart() { org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.startAt(1024); GetOptions expected = new GetOptions(); expected.startAt(1024); assertEquals(fn.apply(in), expected); }
@Test public void testNoneReturnsNone() { assertEquals(fn.apply(org.jclouds.blobstore.options.GetOptions.NONE), GetOptions.NONE); }
@Test public void testIfUnmodifiedSince() { Date ifUnmodifiedSince = new Date(999999l); org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.ifUnmodifiedSince(ifUnmodifiedSince); GetOptions expected = new GetOptions(); expected.ifUnmodifiedSince(ifUnmodifiedSince); assertEquals(fn.apply(in), expected); }
@Test public void testIfModifiedSince() { Date ifModifiedSince = new Date(999999l); org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.ifModifiedSince(ifModifiedSince); GetOptions expected = new GetOptions(); expected.ifModifiedSince(ifModifiedSince); assertEquals(fn.apply(in), expected); }
@Test public void testIfMatch() { String ifMatch = "foo"; org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.ifETagMatches(ifMatch); GetOptions expected = new GetOptions(); expected.ifETagMatches(ifMatch); assertEquals(fn.apply(in), expected); }
@Test public void testRanges(){ org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.range(0,1024); in.startAt(2048); GetOptions expected = new GetOptions(); expected.range(0,1024); expected.startAt(2048); assertEquals(fn.apply(in), expected); }
@Test public void testRangesTail(){ org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.tail(1024); GetOptions expected = new GetOptions(); expected.tail(1024); assertEquals(fn.apply(in), expected); }
@Test public void testRangesStart(){ org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.startAt(1024); GetOptions expected = new GetOptions(); expected.startAt(1024); assertEquals(fn.apply(in), expected); }
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { fn.apply(null); } |
Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).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); } | @Test public void testOnThrowableWhenFirstThrowsMatchingException() { assertEquals(Suppliers2.onThrowable(new Supplier<String>() { @Override public String get() { throw new NoSuchElementException(); } }, NoSuchElementException.class, Suppliers.ofInstance("foo")).get(), "foo"); }
@Test(expectedExceptions = RuntimeException.class) public void testOnThrowableWhenFirstThrowsUnmatchingException() { Suppliers2.onThrowable(new Supplier<String>() { @Override public String get() { throw new RuntimeException(); } }, NoSuchElementException.class, Suppliers.ofInstance("foo")).get(); }
@Test public void testOnThrowableWhenFirstIsFine() { assertEquals( Suppliers2.onThrowable(Suppliers.<String> ofInstance("foo"), NoSuchElementException.class, Suppliers.ofInstance("bar")).get(), "foo"); } |
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(); } | @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); } |
BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } | @Test public void testIterableSliceExpectedSingle() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); String contents = "aaaaaaaaaabbbbbbbbbbccccc"; Payload payload = new InputStreamPayload(new ByteArrayInputStream(contents.getBytes(Charsets.US_ASCII))); Iterator<Payload> iter = slicer.slice(payload, 25).iterator(); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(Strings2.toStringAndClose(iter.next().openStream()), contents); assertFalse(iter.hasNext()); }
@Test public void testIterableSliceExpectedMulti() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); Payload payload = new InputStreamPayload(new ByteArrayInputStream("aaaaaaaaaabbbbbbbbbbccccc".getBytes(Charsets.US_ASCII))); Iterator<Payload> iter = slicer.slice(payload, 10).iterator(); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(Strings2.toStringAndClose(iter.next().getInput()), "aaaaaaaaaa"); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(Strings2.toStringAndClose(iter.next().getInput()), "bbbbbbbbbb"); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(Strings2.toStringAndClose(iter.next().getInput()), "ccccc"); assertFalse(iter.hasNext()); }
@Test public void testIterableSliceWithRepeatingByteSourceSmallerPartSize() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); ByteSource byteSource = ByteSource.wrap("aaaaaaaaaabbbbbbbbbbccccc".getBytes(Charsets.UTF_8)); Payload payload = new ByteSourcePayload(byteSource); Iterator<Payload> iter = slicer.slice(payload, 10).iterator(); Payload part; assertTrue(iter.hasNext(), "Not enough results"); part = iter.next(); assertEquals(Strings2.toStringAndClose(part.getInput()), "aaaaaaaaaa"); assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(10)); assertTrue(iter.hasNext(), "Not enough results"); part = iter.next(); assertEquals(Strings2.toStringAndClose(part.getInput()), "bbbbbbbbbb"); assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(10)); assertTrue(iter.hasNext(), "Not enough results"); part = iter.next(); assertEquals(Strings2.toStringAndClose(part.getInput()), "ccccc"); assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(5)); assertFalse(iter.hasNext()); }
@Test public void testIterableSliceWithRepeatingByteSourceLargerPartSize() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); ByteSource byteSource = ByteSource.wrap("aaaaaaaaaabbbbbbbbbbccccc".getBytes(Charsets.UTF_8)); Payload payload = new ByteSourcePayload(byteSource); Iterator<Payload> iter = slicer.slice(payload, 50).iterator(); Payload part; assertTrue(iter.hasNext(), "Not enough results"); part = iter.next(); assertEquals(Strings2.toStringAndClose(part.getInput()), "aaaaaaaaaabbbbbbbbbbccccc"); assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(25)); assertFalse(iter.hasNext()); } |