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... | @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("... |
VirtualGuestToNodeMetadata implements Function<VirtualGuest, NodeMetadata> { @Inject VirtualGuestToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations, GroupNamingConvention.Factory namingConvention, VirtualGuestToImage virtualGuestToImage, VirtualGuestToHardware virtualGuestToHardware) { this.nodeNaming... | @Test public void testVirtualGuestToNodeMetadata() { VirtualGuest virtualGuest = createVirtualGuest(); NodeMetadata nodeMetadata = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, virtualGuestToImage, virtualGuestToHardware).apply(virtualGuest); assertNotNull(nodeMetadata); assertEquals(nodeMetadata.g... |
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... | @Test(expectedExceptions = { IllegalStateException.class }) public void testGetBestPasswordNone() { Set<Password> passwords = Sets.newLinkedHashSet(); VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, virtualGuestToImage, virtualGuestToHardware); f.getBestPassword(passwor... |
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.D... | @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(Ope... |
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 nul... | @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>... | @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(Op... | @Test public void testVirtualGuestToImageWhenOperatingSystemIsNull() { VirtualGuest virtualGuest = createVirtualGuestWithoutOperatingSystem(); Image image = new VirtualGuestToImage(operatingSystemToImage).apply(virtualGuest); assertNotNull(image); assertEquals(image.getStatus(), Image.Status.UNRECOGNIZED); assertEquals... |
OperatingSystemToImage implements Function<OperatingSystem, Image> { @Override public Image apply(OperatingSystem operatingSystem) { checkNotNull(operatingSystem, "operatingSystem"); final SoftwareLicense defaultSoftwareLicense = SoftwareLicense.builder().softwareDescription(SoftwareDescription.builder().build()).build... | @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 Linu... |
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))) .... | @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(I... |
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(datacent... |
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(Ite... | @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(); assertEq... |
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 d... | @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); AWSRunInstances... | @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"); asse... |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withSecurityGroup(String securityGroup) { launchSpecificationBuilder.securityGroupName(securityGroup); return AWSRunInstancesOptions.class.cast(super.withSecurityGroup(securityGroup)); } AWSRunInstancesOptions inPlacementGroup... | @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 =... |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions withSecurityGroupId(String securityGroup) { return withSecurityGroupIds(securityGroup); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSRunInstancesOptions withDe... | @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 o... |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withUserData(byte[] unencodedData) { launchSpecificationBuilder.userData(unencodedData); return AWSRunInstancesOptions.class.cast(super.withUserData(unencodedData)); } AWSRunInstancesOptions inPlacementGroup(String placementGr... | @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 = withUs... |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions asType(String type) { launchSpecificationBuilder.instanceType(type); return AWSRunInstancesOptions.class.cast(super.asType(type)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTe... | @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 opti... |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withKernelId(String kernelId) { launchSpecificationBuilder.kernelId(kernelId); return AWSRunInstancesOptions.class.cast(super.withKernelId(kernelId)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunIns... | @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");... |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions enableMonitoring() { formParameters.put("Monitoring.Enabled", "true"); launchSpecificationBuilder.monitoringEnabled(true); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy... | @Test public void testWithMonitoringEnabled() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.enableMonitoring(); assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), ImmutableList.of("true")); }
@Test public void testWithMonitoringEnabledStatic() { AWSRunInstancesOptions optio... |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions withSubnetId(String subnetId) { formParameters.put("SubnetId", checkNotNull(subnetId, "subnetId")); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenancy); AWSR... | @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");... |
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); AWSRunInstance... | @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"), Immutable... |
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); AWSRunIns... | @Test public void testWithIAMInstanceProfileName() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withIAMInstanceProfileName("Webserver"); assertEquals(options.buildFormParameters().get("IamInstanceProfile.Name"), ImmutableList.of("Webserver")); }
@Test public void testWithIAMInstanceProfileNa... |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withRamdisk(String ramDiskId) { launchSpecificationBuilder.ramdiskId(ramDiskId); return AWSRunInstancesOptions.class.cast(super.withRamdisk(ramDiskId)); } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunI... | @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"); as... |
AWSRunInstancesOptions extends RunInstancesOptions { @Override public AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings) { launchSpecificationBuilder.blockDeviceMappings(mappings); return AWSRunInstancesOptions.class.cast(super.withBlockDeviceMappings(mappings)); } AWSRunInstanc... | @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.... |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions withTenancy(Tenancy tenancy) { formParameters.put("Placement.Tenancy", checkNotNull(tenancy, "tenancy").toString()); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenan... | @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 =... |
AWSRunInstancesOptions extends RunInstancesOptions { public AWSRunInstancesOptions withDedicatedHostId(String hostId) { formParameters.put("Placement.HostId", checkNotNull(hostId, "hostId")); return this; } AWSRunInstancesOptions inPlacementGroup(String placementGroup); AWSRunInstancesOptions withTenancy(Tenancy tenan... | @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() { AWSRunInsta... |
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... | @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.... |
ImportOrReturnExistingKeypair implements Function<RegionNameAndPublicKeyMaterial, KeyPair> { @Override public KeyPair apply(RegionNameAndPublicKeyMaterial from) { return importOrReturnExistingKeypair(from.getRegion(), from.getName(), from.getPublicKeyMaterial()); } @Inject ImportOrReturnExistingKeypair(AWSEC2Api ec2Ap... | @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); rep... |
ImportOrReturnExistingKeypair implements Function<RegionNameAndPublicKeyMaterial, KeyPair> { @Inject public ImportOrReturnExistingKeypair(AWSEC2Api ec2Api) { this.ec2Api = ec2Api; } @Inject ImportOrReturnExistingKeypair(AWSEC2Api ec2Api); @Override KeyPair apply(RegionNameAndPublicKeyMaterial from); KeyPair addFingerp... | @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", "jcloud... |
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().toStr... | @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); as... |
CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions extends
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions { @Override public String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) { RegionAndName key = new RegionAndName(region, group); ... | @Test(expectedExceptions = IllegalArgumentException.class) public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptButNoCredentials() { String region = Region.AP_SOUTHEAST_1; String group = "group"; String userSuppliedKeyPair = "myKeyPair"; CreateKeyPairPlacementAndSecurityGroupsAsN... |
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) { osBui... | @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 builde... |
AWSEC2ComputeServiceContextModule extends BaseComputeServiceContextModule { protected Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader( final RegionAndIdToImage delegate) { return Suppliers.<CacheLoader<RegionAndName, Image>>ofInstance(new CacheLoader<RegionAndName, Image>() { ... | @Test public void testCacheLoaderDoesNotReloadAfterAuthorizationException() throws Exception { AWSEC2ComputeServiceContextModule module = new AWSEC2ComputeServiceContextModule() { public Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(RegionAndIdToImage delegate) { return supe... |
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 getSpot... | @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())... |
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()... | @SuppressWarnings("unchecked") @Test public void testWhenPort22AndToItselfAuthorizesIngressOnce() throws ExecutionException { AWSSecurityGroupApi client = createMock(AWSSecurityGroupApi.class); Predicate<RegionAndName> tester = Predicates.alwaysTrue(); SecurityGroup group = createNiceMock(SecurityGroup.class); Set<Secu... |
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: %... | @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 testDoesNotRetryWhenRateLimit... |
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>... | @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", "serv... |
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) reques... | @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 testOverrideMeth... |
CreateResourcesThenCreateNodes extends CreateNodesWithGroupEncodedIntoNameThenAddToSet { @VisibleForTesting void normalizeNetworkOptions(AzureTemplateOptions options) { if (!options.getNetworks().isEmpty() && !options.getIpOptions().isEmpty()) { throw new IllegalArgumentException("The options.networks and options.ipOpt... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "The options.networks and options.ipOptions are exclusive") public void testNormalizeNetworkOptionsWithConflictingConfig() { AzureTemplateOptions options = new AzureTemplateOptions(); options.ipOptions(IpOptions.builder().subne... |
VirtualMachineToStatus implements Function<VirtualMachine, StatusAndBackendStatus> { @Override public StatusAndBackendStatus apply(VirtualMachine virtualMachine) { String resourceGroup = extractResourceGroup(virtualMachine.id()); ProvisioningState provisioningState = virtualMachine.properties().provisioningState(); Nod... | @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())... |
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 IdRef... | @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-northeurop... |
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({"i... | @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 assertEq... |
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 prope... | @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("/subscriptio... |
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 getRootPassw... | @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(T... | @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(expectedE... |
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);... | @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(TemplateOptio... | @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 GleSYSTemplat... |
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... | @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(Templat... | @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 GleSYSTemplateOptio... |
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... | @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 = Fl... | @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 ... |
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(Signatur... | @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 (reque... |
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.... | @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 testAclQueryStr... |
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... | @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"); ... |
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; ... | @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 en... | @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 RuntimeExcep... |
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(); HttpHealth... | @Test public void testMap() throws SecurityException, NoSuchMethodException { HttpHealthCheckCreationBinder binder = new HttpHealthCheckCreationBinder(json); HttpHealthCheckCreationOptions httpHealthCheckCreationOptions = new HttpHealthCheckCreationOptions.Builder() .timeoutSec(TIMEOUTSEC) .unhealthyThreshold(UNHEALTHY... |
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(fa... | @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<... |
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(); ForwardingRul... | @Test public void testMap() throws SecurityException, NoSuchMethodException { ForwardingRuleCreationBinder binder = new ForwardingRuleCreationBinder(json); ForwardingRuleCreationOptions forwardingRuleCreationOptions = new ForwardingRuleCreationOptions.Builder() .description(DESCRIPTION) .ipAddress(IP_ADDRESS) .ipProtoc... |
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(in... | @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(), instan... |
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,
... | @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); ... | @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(har... |
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 = ... | @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() ... |
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.containsKe... | @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.clas... |
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.containsKe... | @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); BackoffLimited... |
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; i... | @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 = n... |
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());... | @Test public void testLoaderNormal() { AtomicReference<AuthorizationException> authException = newReference(); assertEquals(new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(ofInstance("foo"), authException, new ValueLoadedCallback.NoOpCallback<String>()).load("KEY").get(), "foo"); assertEquals(authExce... |
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... | @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"))) .meth... |
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint =... | @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)))... |
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.getAll... | @Test public void testParseContentLengthWhenContentRangeSet() throws HttpException { ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class); ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider); HttpRes... |
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) re... | @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... |
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>,
InvocationContext<ParseSystemAndUserMetadataFromHeaders> { public MutableBlobMetadata apply(HttpResponse from) { checkNotNull(from, "request"); checkState(name != null, "name must be initialized by now"); MutableBlobM... | @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().getContentMe... |
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 nu... | @Test(expectedExceptions = NullPointerException.class) public void testAddHostNullWithHost() throws Exception { assertNull(RestAnnotationProcessor.addHostIfMissing(null, null)); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddHostWithHostHasNoHost() throws Exception { assertNull(RestAnno... |
InputParamValidator { public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) { try { performMethodValidation(checkNotNull(invocation, "invocation")); performParameterValidation(invocation, checkNotNull(parameters, "parameters")); } catch (IllegalArgumentException e) { throw new I... | @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(invocatio... |
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>(... | @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_... |
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>() { @Over... | @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)))... |
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<X5... | @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(ByteSour... |
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, I... | @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; a... |
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public boolean shouldRetryRequest(HttpCommand command, IOException error) { return ifReplayableBackoffAndReturnTrue(command); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand co... | @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 ret... |
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 re... | @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)); }
@Te... |
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 cou... | @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_M... | @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.... | @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(... | @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: .get... |
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>,
InvocationContext<ParseSystemAndUserMetadataFromHeaders> { @VisibleForTesting void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry<String, String> header : from.getHeaders().entries()) ... | @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().g... |
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(fr... | @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.ge... |
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(In... | @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 pu... |
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)... | @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(WithDeseri... |
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()... | @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(t... |
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.appl... |
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> fi... | @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 ... |
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 (throw... | @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 te... |
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 "getLastVa... | @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 toStr... | @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(Suppliers... |
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(fina... | @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(thi... | @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 = n... | @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); assertEqua... |
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.getFirstThrowable... | @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 = RuntimeExcept... |
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 s... | @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 = doSl... | @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,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.