method2testcases
stringlengths
118
6.63k
### Question: InstanceToNodeMetadata implements Function<Instance, NodeMetadata> { public static Hardware machineTypeURIToCustomHardware(URI machineType) { String uri = machineType.toString(); String values = uri.substring(uri.lastIndexOf('/') + 8); List<String> hardwareValues = Splitter.on('-') .trimResults() .splitToList(values); return new HardwareBuilder() .id(uri) .providerId(uri) .processor(new Processor(Double.parseDouble(hardwareValues.get(0)), 1.0)) .ram(Integer.parseInt(hardwareValues.get(1))) .uri(machineType) .build(); } @Inject InstanceToNodeMetadata(Map<Instance.Status, NodeMetadata.Status> toPortableNodeStatus, GroupNamingConvention.Factory namingConvention, LoadingCache<URI, Optional<Image>> diskURIToImage, @Memoized Supplier<Map<URI, Hardware>> hardwares, @Memoized Supplier<Map<URI, Location>> locationsByUri); @Override NodeMetadata apply(Instance input); static boolean isCustomMachineTypeURI(URI machineType); static Hardware machineTypeURIToCustomHardware(URI machineType); }### Answer: @Test public void machineTypeParserTest() { URI uri = URI.create("https: Hardware hardware = machineTypeURIToCustomHardware(uri); assertThat(hardware.getRam()).isEqualTo(1024); assertThat(hardware.getProcessors().get(0).getCores()).isEqualTo(1); assertThat(hardware.getUri()) .isEqualTo(URI.create("https: assertThat(hardware.getId()) .isEqualTo("https: }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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()); }
### Question: 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(); }### Answer: @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); } }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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")); }
### Question: 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(); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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(); }### Answer: @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: }
### Question: InputParamValidator { public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) { try { performMethodValidation(checkNotNull(invocation, "invocation")); performParameterValidation(invocation, checkNotNull(parameters, "parameters")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Validation on '%s' didn't pass:%n Reason: %s.", parameters, e.getMessage()), e); } } @Inject InputParamValidator(Injector injector); InputParamValidator(); void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters); }### Answer: @Test(expectedExceptions = ClassCastException.class) public void testWrongPredicateTypeLiteral() throws Exception { Invocation invocation = Invocation.create(method(WrongValidator.class, "method", Integer.class), ImmutableList.<Object> of(55)); new InputParamValidator(injector).validateMethodParametersOrThrow(invocation, invocation.getInvokable().getParameters()); }
### Question: Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }### Answer: @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "^Invalid PEM: no parsers for marker -----BEGIN FOO PRIVATE KEY----- .*") public void testPrivateKeySpecFromPemWithInvalidMarker() throws IOException { Pems.privateKeySpec(ByteSource.wrap(INVALID_PRIVATE_KEY.getBytes(Charsets.UTF_8))); } @Test public void testPrivateKeySpecFromPem() throws IOException { Pems.privateKeySpec(ByteSource.wrap(PRIVATE_KEY.getBytes(Charsets.UTF_8))); }
### Question: Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }### Answer: @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "^Invalid PEM: no parsers for marker -----BEGIN FOO PUBLIC KEY----- .*") public void testPublicKeySpecFromPemWithInvalidMarker() throws IOException { Pems.publicKeySpec(ByteSource.wrap(INVALID_PUBLIC_KEY.getBytes(Charsets.UTF_8))); } @Test public void testPublicKeySpecFromPem() throws IOException { Pems.publicKeySpec(ByteSource.wrap(PUBLIC_KEY.getBytes(Charsets.UTF_8))); }
### Question: 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; }### Answer: @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")); }
### Question: 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; }### Answer: @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); }
### Question: GetOptions extends BaseHttpRequestOptions { public String getRange() { return (!ranges.isEmpty()) ? String.format("bytes=%s", Joiner.on(",").join(ranges)) : null; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }### Answer: @Test public void testNullRange() { GetOptions options = new GetOptions(); assertNull(options.getRange()); }
### Question: GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }### Answer: @Test public void testIfETagMatches() { GetOptions options = new GetOptions(); options.ifETagMatches(etag); matchesHex(options.getIfMatch()); } @Test(expectedExceptions = NullPointerException.class) public void testIfETagMatchesNPE() { ifETagMatches(null); }
### Question: GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }### Answer: @Test public void testIfETagDoesntMatch() { GetOptions options = new GetOptions(); options.ifETagDoesntMatch(etag); matchesHex(options.getIfNoneMatch()); } @Test(expectedExceptions = NullPointerException.class) public void testIfETagDoesntMatchNPE() { ifETagDoesntMatch(null); }
### Question: 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); }### Answer: @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, '/', ',')); }
### Question: ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { @VisibleForTesting void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry<String, String> header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().toLowerCase().startsWith(metadataPrefix)) metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), header.getValue()); } } @Inject ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); MutableBlobMetadata apply(HttpResponse from); ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request); ParseSystemAndUserMetadataFromHeaders setName(String name); }### Answer: @Test public void testAddUserMetadataTo() { HttpResponse from = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader("prefix" + "key", "value").build(); MutableBlobMetadata metadata = blobMetadataProvider.get(); parser.addUserMetadataTo(from, metadata); assertEquals(metadata.getUserMetadata().get("key"), "value"); }
### Question: 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); }### Answer: @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); } }
### Question: 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); }### Answer: @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}}")); }
### Question: BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } String apply(Blob input); }### Answer: @Test public void testCorrect() throws SecurityException, NoSuchMethodException { Blob blob = BLOB_FACTORY.create(null); blob.getMetadata().setName("foo"); assertEquals(fn.apply(blob), "foo"); } @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { fn.apply(null); }
### Question: Suppliers2 { public static <K, V> Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input) { return new Supplier<V>() { @Override public V get() { Supplier<V> last = Iterables.getLast(input.get().values()); return last != null ? last.get() : null; } @Override public String toString() { return "getLastValueInMap()"; } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback); }### Answer: @Test public void testGetLastValueInMap() { assertEquals( Suppliers2.<String, String> getLastValueInMap( Suppliers.<Map<String, Supplier<String>>> ofInstance(ImmutableMap.of("foo", Suppliers.ofInstance("bar")))).get(), "bar"); }
### Question: Suppliers2 { public static <K, V> Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue) { return new Supplier<V>() { @Override public V get() { Map<K, Supplier<V>> map = input.get(); return map.containsKey(keyValue) ? map.get(keyValue).get() : null; } @Override public String toString() { return String.format("getValueInMapOrNull('%1$s')", keyValue); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback); }### Answer: @Test public void testGetSpecificValueInMap() { Supplier<Map<String, Supplier<String>>> testMap = Suppliers.<Map<String, Supplier<String>>> ofInstance( ImmutableMap.of("foo", Suppliers.ofInstance("bar"))); assertEquals(Suppliers2.<String, String> getValueInMapOrNull(testMap, "foo").get(), "bar"); assertEquals(Suppliers2.<String, String> getValueInMapOrNull(testMap, "baz").get(), null); }
### Question: Suppliers2 { public static <X> Function<X, Supplier<X>> ofInstanceFunction() { return new Function<X, Supplier<X>>() { @Override public Supplier<X> apply(X arg0) { return Suppliers.ofInstance(arg0); } @Override public String toString() { return "Suppliers.ofInstance()"; } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback); }### Answer: @Test public void testOfInstanceFunction() { assertEquals(Suppliers2.ofInstanceFunction().apply("foo").get(), "foo"); }
### Question: Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback); }### Answer: @Test public void testOrWhenFirstNull() { assertEquals(Suppliers2.or(Suppliers.<String> ofInstance(null), Suppliers.ofInstance("foo")).get(), "foo"); } @Test public void testOrWhenFirstNotNull() { assertEquals(Suppliers2.or(Suppliers.<String> ofInstance("foo"), Suppliers.ofInstance("bar")).get(), "foo"); }
### Question: 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); }### Answer: @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"); }
### Question: PasswordGenerator { public String generate() { StringBuilder sb = new StringBuilder(); sb.append(lower.fragment()); sb.append(upper.fragment()); sb.append(numbers.fragment()); sb.append(symbols.fragment()); return shuffleAndJoin(sb.toString().toCharArray()); } Config lower(); Config upper(); Config numbers(); Config symbols(); String generate(); }### Answer: @Test public void defaultGeneratorContainsAll() { String password = new PasswordGenerator().generate(); assertTrue(password.matches(".*[a-z].*[a-z].*")); assertTrue(password.matches(".*[A-Z].*[A-Z].*")); assertTrue(password.matches(".*[0-9].*[0-9].*")); assertTrue(password.replaceAll("[a-zA-Z0-9]", "").length() > 0); }
### Question: BindLoggersAnnotatedWithResource implements TypeListener { public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type); if (loggerFields.isEmpty()) return; Logger logger = loggerFactory.getLogger(type.getName()); for (Field field : loggerFields) { if (field.isAnnotationPresent(Named.class)) { Named name = field.getAnnotation(Named.class); encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field)); } else { encounter.register(new AssignLoggerToField<I>(logger, field)); } } } @Inject BindLoggersAnnotatedWithResource(LoggerFactory loggerFactory); void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter); }### Answer: @Test void testHear() { Injector i = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(any(), blawr); } }); assertEquals(i.getInstance(A.class).logger.getCategory(), getClass().getName() + "$A"); assertEquals(i.getInstance(B.class).logger.getCategory(), getClass().getName() + "$B"); assertEquals(i.getInstance(B.class).blogger.getCategory(), "blogger"); }
### Question: HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); }### Answer: @Test(expectedExceptions = RuntimeException.class) public void testArbitraryExceptionDoesntConvert() throws Exception { fn.createOrPropagate(new RuntimeException()); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry now") public void testHttpResponseExceptionWithRetryAfterDate() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "Fri, 31 Dec 1999 23:59:59 GMT") .build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 700 seconds") public void testHttpResponseExceptionWithRetryAfterOffset() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "700").build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 86400 seconds") public void testHttpResponseExceptionWithRetryAfterPastIsZero() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "Sun, 2 Jan 2000 00:00:00 GMT") .build())); }
### Question: MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); }### Answer: @Test(expectedExceptions = AuthorizationException.class) public void test401ToAuthorizationException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(401).build())); } @Test(expectedExceptions = AuthorizationException.class) public void test403ToAuthorizationException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(403).build())); } @Test(expectedExceptions = ResourceNotFoundException.class) public void test404ToResourceNotFoundException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(404).build())); } @Test(expectedExceptions = IllegalStateException.class) public void test409ToIllegalStateException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(409).build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry now") public void testHttpResponseExceptionWithRetryAfterDate() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "Fri, 31 Dec 1999 23:59:59 GMT").build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 700 seconds") public void testHttpResponseExceptionWithRetryAfterOffset() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "700").build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 86400 seconds") public void testHttpResponseExceptionWithRetryAfterPastIsZero() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "Sun, 2 Jan 2000 00:00:00 GMT").build())); }
### Question: Providers { public static ProviderMetadata withId(String id) throws NoSuchElementException { return find(all(), ProviderPredicates.id(id)); } static Function<ProviderMetadata, String> idFunction(); static Function<ProviderMetadata, ApiMetadata> apiMetadataFunction(); static Iterable<ProviderMetadata> fromServiceLoader(); static Iterable<ProviderMetadata> all(); static ProviderMetadata withId(String id); static Iterable<ProviderMetadata> viewableAs(TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> viewableAs(Class<? extends View> viewableAs); static Iterable<ProviderMetadata> apiMetadataAssignableFrom(TypeToken<? extends ApiMetadata> api); static Iterable<ProviderMetadata> contextAssignableFrom( TypeToken<? extends Context> context); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code, TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code, Class<? extends View> viewableAs); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata, TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata, Class<? extends View> viewableAs); }### Answer: @Test public void testWithId() { ProviderMetadata providerMetadata; try { providerMetadata = Providers.withId("fake-id"); fail("Looking for a provider with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { } providerMetadata = Providers.withId(testBlobstoreProvider.getId()); assertEquals(testBlobstoreProvider, providerMetadata); assertNotEquals(testBlobstoreProvider, testComputeProvider); assertNotEquals(testBlobstoreProvider, testYetAnotherComputeProvider); } @Test public void testWithId() { ProviderMetadata providerMetadata; try { providerMetadata = Providers.withId("fake-id"); fail("Looking for a provider with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { ; } providerMetadata = Providers.withId(testBlobstoreProvider.getId()); assertEquals(testBlobstoreProvider, providerMetadata); assertNotEquals(testBlobstoreProvider, testComputeProvider); assertNotEquals(testBlobstoreProvider, testYetAnotherComputeProvider); }
### Question: UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata); @Override ProviderMetadata apply(Properties input); }### Answer: @Test public void testProviderMetadataWithUpdatedEndpointUpdatesAndRetainsAllDefaultPropertiesExceptEndpoint() { ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(Constants.PROPERTY_ENDPOINT, "http: ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getEndpoint(), "http: assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); } @Test public void testProviderMetadataWithUpdatedIso3166CodesUpdatesAndRetainsAllDefaultPropertiesExceptIso3166Codes() { ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(PROPERTY_ISO3166_CODES, "US-CA"); ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getIso3166Codes(), ImmutableSet.of("US-CA")); assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); } @Test public void testProviderMetadataWithUpdatedEndpointUpdatesAndRetainsAllDefaultPropertiesExceptEndpoint() { ProviderMetadata md = AnonymousProviderMetadata.forClientMappedToAsyncClientOnEndpoint( IntegrationTestClient.class, IntegrationTestAsyncClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(Constants.PROPERTY_ENDPOINT, "http: ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getEndpoint(), "http: assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); } @Test public void testProviderMetadataWithUpdatedIso3166CodesUpdatesAndRetainsAllDefaultPropertiesExceptIso3166Codes() { ProviderMetadata md = AnonymousProviderMetadata.forClientMappedToAsyncClientOnEndpoint( IntegrationTestClient.class, IntegrationTestAsyncClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(PROPERTY_ISO3166_CODES, "US-CA"); ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getIso3166Codes(), ImmutableSet.of("US-CA")); assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); }
### Question: ContextLinking { public static Module linkView(final String id, final Supplier<View> view) { return new AbstractModule() { @Override protected void configure() { bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view); bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view)); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); }### Answer: @Test public void testLinkedViewBindsViewAndContextSuppliers() { Injector injector = Guice.createInjector(linkView(new DummyView(contextFor(IntegrationTestClient.class)))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); assertNotNull(injector.getExistingBinding(Key.get(VIEW_SUPPLIER, Names.named("IntegrationTestClient")))); }
### Question: ContextLinking { public static Module linkContext(final String id, final Supplier<Context> context) { return new AbstractModule() { @Override protected void configure() { bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); }### Answer: @Test public void testLinkedContextBindsContextSupplier() { Injector injector = Guice.createInjector(linkContext(contextFor(IntegrationTestClient.class))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); }
### Question: ArgsToPagedIterable implements Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); }### Answer: @Test public void testWhenNextMarkerAbsentDoesntAdvance() { GeneratedHttpRequest request = args(ImmutableList.of()); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { fail("The Iterable should not advance"); return null; } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"))).concat().toSet(), ImmutableSet.of("foo", "bar")); } @Test public void testWhenNextMarkerPresentButNoArgsMarkerToNextForArgsParamIsAbsent() { GeneratedHttpRequest request = args(ImmutableList.of()); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertTrue(args.isEmpty()); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } @Test public void testWhenNextMarkerPresentWithArgsMarkerToNextForArgsParamIsPresent() { GeneratedHttpRequest request = args(ImmutableList.<Object> of("path")); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertEquals(args.get(0), "path"); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } @Test public void testFromCallerWhenNextMarkerPresentButNoArgsMarkerToNextForArgsParamIsAbsent() { GeneratedHttpRequest request = callerArgs(ImmutableList.of()); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestCallerArgs converter = new TestCallerArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertTrue(args.isEmpty()); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } @Test public void testFromCallerWhenNextMarkerPresentWithArgsMarkerToNextForArgsParamIsPresent() { GeneratedHttpRequest request = callerArgs(ImmutableList.<Object> of("path")); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestCallerArgs converter = new TestCallerArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertEquals(args.get(0), "path"); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); }
### Question: ExecutorServiceModule extends AbstractModule { static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } ExecutorServiceModule(); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor, ExecutorService ioExecutor); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ListeningExecutorService ioExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); static SimpleTimeLimiter createSimpleTimeLimiter(ExecutorService executorService); }### Answer: @Test public void testShutdownOnClose() throws IOException { Injector i = Guice.createInjector(); Closer closer = i.getInstance(Closer.class); ListeningExecutorService executor = createMock(ListeningExecutorService.class); ExecutorServiceModule.shutdownOnClose(executor, closer); expect(executor.shutdownNow()).andReturn(ImmutableList.<Runnable> of()).atLeastOnce(); replay(executor); closer.close(); verify(executor); }
### Question: ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier, @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); }### Answer: @Test public void test() { Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.of("zone1", "zone2")); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.of( "servo", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US")), "zone1", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-CA")), "zone2", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-VA")) )); ZoneToProvider fn = new ZoneToProvider(justProvider, zoneIdsSupplier, locationToIsoCodes); assertEquals(fn.get(), ImmutableSet.of( new LocationBuilder().scope(LocationScope.ZONE).id("zone1").description("zone1").iso3166Codes(ImmutableSet.of("US-CA")).parent(provider).build(), new LocationBuilder().scope(LocationScope.ZONE).id("zone2").description("zone2").iso3166Codes(ImmutableSet.of("US-VA")).parent(provider).build() )); } @Test(expectedExceptions = IllegalStateException.class) public void testWhenNoZones() { Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.<String>of()); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.<String, Supplier<Set<String>>>of()); ZoneToProvider fn = new ZoneToProvider(justProvider, zoneIdsSupplier, locationToIsoCodes); fn.get(); }
### Question: RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } @Inject RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier, @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); }### Answer: @Test public void test() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.of("region1", "region2")); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.of( "servo", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US")), "region1", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-CA")), "region2", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-VA")) )); RegionToProvider fn = new RegionToProvider(justProvider, regionIdsSupplier, locationToIsoCodes); assertEquals(fn.get(), ImmutableSet.of( new LocationBuilder().scope(LocationScope.REGION).id("region1").description("region1").iso3166Codes(ImmutableSet.of("US-CA")).parent(provider).build(), new LocationBuilder().scope(LocationScope.REGION).id("region2").description("region2").iso3166Codes(ImmutableSet.of("US-VA")).parent(provider).build() )); } @Test(expectedExceptions = IllegalStateException.class) public void testWhenNoRegions() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.<String>of()); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.<String, Supplier<Set<String>>>of()); RegionToProvider fn = new RegionToProvider(justProvider, regionIdsSupplier, locationToIsoCodes); fn.get(); }
### Question: ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider, @Zone Supplier<Set<String>> zoneIdsSupplier, @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier, @Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier); @Override Set<? extends Location> get(); }### Answer: @Test public void testGetAll() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("region1", "region2")); Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("zone1", "zone2", "zone3")); RegionToProviderOrJustProvider regionToProviderOrJustProvider = new RegionToProviderOrJustProvider(justProvider, regionIdsSupplier, locationToIsoCodes); ZoneToRegionToProviderOrJustProvider fn = new ZoneToRegionToProviderOrJustProvider(regionToProviderOrJustProvider, zoneIdsSupplier, locationToIsoCodes, regionToZones); assertEquals(fn.get(), ImmutableSet.of(region1, region2, zone1, zone2, zone3)); } @Test public void testRegionAndZoneFilter() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("region2")); Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.<String> of("zone2")); RegionToProviderOrJustProvider regionToProviderOrJustProvider = new RegionToProviderOrJustProvider(justProvider, regionIdsSupplier, locationToIsoCodes); ZoneToRegionToProviderOrJustProvider fn = new ZoneToRegionToProviderOrJustProvider(regionToProviderOrJustProvider, zoneIdsSupplier, locationToIsoCodes, regionToZones); assertEquals(fn.get(), ImmutableSet.of(region2, zone2)); }
### Question: ZoneIdToURIFromJoinOnRegionIdToURI implements ZoneIdToURISupplier { @Override public Map<String, Supplier<URI>> get() { Map<String, Supplier<Set<String>>> regionIdToZoneIds = this.regionIdToZoneIds.get(); Builder<String, Supplier<URI>> builder = ImmutableMap.builder(); for (Entry<String, Supplier<URI>> regionToURI : regionIdToURIs.get().entrySet()) { Supplier<Set<String>> zoneIds = regionIdToZoneIds.get(regionToURI.getKey()); checkState(zoneIds != null, "region %s is not in the configured region to zone mappings: %s", regionToURI.getKey(), regionIdToZoneIds); for (String zone : zoneIds.get()) { builder.put(zone, regionToURI.getValue()); } } return builder.build(); } @Inject ZoneIdToURIFromJoinOnRegionIdToURI(@Region Supplier<Map<String, Supplier<URI>>> regionIdToURIs, @Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds); @Override Map<String, Supplier<URI>> get(); }### Answer: @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "region eu-central-1 is not in the configured region to zone mappings: .*") public void zoneToRegionMappingsInconsistentOnKeys() { Map<String, Supplier<URI>> regionIdToURIs = Maps.newLinkedHashMap(); regionIdToURIs.put("us-east-1", Suppliers.ofInstance(URI.create("ec2.us-east-1.amazonaws.com"))); regionIdToURIs.put("eu-central-1", Suppliers.ofInstance(URI.create("ec2.eu-central-1.amazonaws.com"))); Map<String, Supplier<Set<String>>> regionIdToZoneIds = Maps.newLinkedHashMap(); regionIdToZoneIds.put("us-east-1", supplyZoneIds("us-east-1a", "us-east-1b")); new ZoneIdToURIFromJoinOnRegionIdToURI(Suppliers.ofInstance(regionIdToURIs), Suppliers.ofInstance(regionIdToZoneIds)).get(); }
### Question: JodaDateService implements DateService { public final String rfc822DateFormat(Date dateTime) { return rfc822DateFormatter.print(new DateTime(dateTime)); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); }### Answer: @Override @Test public void testRfc822DateFormat() { String dsString = dateService.rfc822DateFormat(testData[0].date); assertEquals(dsString, testData[0].rfc822DateString); }
### Question: ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); }### Answer: @Test public void testCorrect() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: assertEquals(fn.apply("1"), URI.create("http: } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeString() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: fn.apply(new File("foo")); } @Test(expectedExceptions = IllegalStateException.class) public void testMustHaveEndpoints() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap .<String, Supplier<URI>> of())); fn.apply("1"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullIsIllegal() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: fn.apply(null); }
### Question: RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri, @Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); }### Answer: @Test public void testWhenRegionNameIsSameAsProviderName() throws SecurityException, NoSuchMethodException { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: assertEquals(fn.apply("leader"), URI.create("http: } @Test public void testWhenFindsRegion() throws SecurityException, NoSuchMethodException { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: assertEquals(fn.apply("1"), URI.create("http: } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeString() { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: fn.apply(new File("foo")); } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeInRegionMapIfSpecified() { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: fn.apply("2"); }
### Question: RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); @Override URI apply(Object from); }### Answer: @Test public void testCorrect() { RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: assertEquals(fn.apply("1"), URI.create("http: } @Test(expectedExceptions = IllegalStateException.class) public void testMustHaveEndpoints() { RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap .<String, Supplier<URI>> of())); fn.apply("1"); }
### Question: JodaDateService implements DateService { public final Date rfc822DateParse(String toParse) { return rfc822DateFormatter.parseDateTime(toParse).toDate(); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); }### Answer: @Override @Test(enabled = false) public void testRfc822DateParse() { Date dsDate = dateService.rfc822DateParse(testData[0].rfc822DateString); assertEquals(dsDate, testData[0].date); }
### Question: ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } @Override Properties apply(final Properties properties); }### Answer: @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "properties cannot be null") public void testPropertiesMandatory() { new ExpandProperties().apply(null); } @Test public void testNoLeafs() { Properties props = new Properties(); props.put("one", "${two}"); props.put("two", "${one}"); Properties resolved = new ExpandProperties().apply(props); assertEquals(resolved.size(), props.size()); assertEquals(resolved.get("one"), "${two}"); assertEquals(resolved.get("two"), "${one}"); }
### Question: ExpandProperties implements Function<Properties, Properties> { @SuppressModernizer private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) { boolean anyReplacementDone = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); StringBuffer sb = new StringBuffer(); Matcher m = VAR.matcher(entry.getValue()); while (m.find()) { String match = m.group(); String var = match.substring(2, match.length() - 1); Optional<String> value = var.equals(key) ? Optional.<String> absent() : Optional.fromNullable(variables .get(var)); m.appendReplacement(sb, value.or("\\" + match)); if (value.isPresent()) { anyReplacementDone = true; } } m.appendTail(sb); properties.put(key, sb.toString()); } return anyReplacementDone; } @Override Properties apply(final Properties properties); }### Answer: @Test public void testResolveProperties() { Properties props = new Properties(); props.put("number", 1); props.put("two", "2"); props.put("greeting", "hello"); props.put("simple", "simple: ${greeting}"); props.put("nested", "nested: ${simple}"); props.put("mixed", "mixed: ${nested} and ${simple}"); props.put("unexisting", "${foobar} substitution"); props.put("recursive", "variable5 ${recursive} recursive ${unexisting}"); props.put("characters{{$$", "characters"); props.put("ugly", "substitute: ${characters{{$$}"); Properties resolved = new ExpandProperties().apply(props); assertEquals(resolved.size(), props.size()); assertEquals(resolved.get("number"), 1); assertEquals(resolved.get("two"), "2"); assertEquals(resolved.get("greeting"), "hello"); assertEquals(resolved.get("simple"), "simple: hello"); assertEquals(resolved.get("nested"), "nested: simple: hello"); assertEquals(resolved.get("mixed"), "mixed: nested: simple: hello and simple: hello"); assertEquals(resolved.get("unexisting"), "${foobar} substitution"); assertEquals(resolved.get("recursive"), "variable5 ${recursive} recursive ${unexisting}"); assertEquals(resolved.get("ugly"), "substitute: characters"); }
### Question: JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); }### Answer: @Test public void testIterableLong() { String list = new JoinOnComma().apply(ImmutableList.of(1L, 2L)); assertEquals(list, "1,2"); } @Test public void testLongArray() { String list = new JoinOnComma().apply(new long[] { 1L, 2L }); assertEquals(list, "1,2"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyArrayIllegalArgumentException() { new JoinOnComma().apply(new long[] {}); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyIterableIllegalArgumentException() { new JoinOnComma().apply(ImmutableList.of()); } @Test(expectedExceptions = NullPointerException.class) public void testNullPointer() { new JoinOnComma().apply(null); }
### Question: SshjSshClient implements SshClient { @VisibleForTesting SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); logger.error(e, "<< " + message); if (e instanceof UserAuthException) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } SshjSshClient(BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket, LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); @Override void put(String path, String contents); void connect(); Payload get(String path); @Override void put(String path, Payload contents); @Override String toString(); @PreDestroy void disconnect(); @Override boolean isConnected(); ExecResponse exec(String command); @Override ExecChannel execChannel(String command); @Override String getHostAddress(); @Override String getUsername(); }### Answer: @Test(expectedExceptions = AuthorizationException.class) public void testPropateConvertsAuthException() { ssh.propagate(new UserAuthException(""), ""); }
### Question: ContextBuilder { @VisibleForTesting static void addExecutorServiceIfNotPresent(List<Module> modules) { if (!any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class); } } )) { if (any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(SingleThreaded.class); } })) { modules.add(new ExecutorServiceModule(newDirectExecutorService())); } else { modules.add(new ExecutorServiceModule()); } } } protected ContextBuilder(ProviderMetadata providerMetadata); protected ContextBuilder(@Nullable ProviderMetadata providerMetadata, ApiMetadata apiMetadata); ContextBuilder(ApiMetadata apiMetadata); static ContextBuilder newBuilder(String providerOrApi); static ContextBuilder newBuilder(ApiMetadata apiMetadata); static ContextBuilder newBuilder(ProviderMetadata providerMetadata); @Override String toString(); ContextBuilder name(String name); ContextBuilder credentialsSupplier(Supplier<Credentials> credentialsSupplier); ContextBuilder credentials(String identity, @Nullable String credential); ContextBuilder endpoint(String endpoint); ContextBuilder apiVersion(String apiVersion); ContextBuilder buildVersion(String buildVersion); ContextBuilder modules(Iterable<? extends Module> modules); ContextBuilder overrides(Properties overrides); static String searchPropertiesForProviderScopedProperty(Properties mutable, String prov, String key); Injector buildInjector(); static Injector buildInjector(String name, ProviderMetadata providerMetadata, Supplier<Credentials> creds, List<Module> inputModules); @SuppressWarnings("unchecked") C build(); V build(Class<V> viewType); V buildView(Class<V> viewType); @SuppressWarnings("unchecked") V buildView(TypeToken<V> viewType); @SuppressWarnings("unchecked") C build(TypeToken<C> contextType); A buildApi(Class<A> api); @SuppressWarnings("unchecked") A buildApi(TypeToken<A> apiType); ApiMetadata getApiMetadata(); }### Answer: @Test public void testAddExecutorServiceModuleIfNotPresent() { List<Module> modules = Lists.newArrayList(); ExecutorServiceModule module = new ExecutorServiceModule(); modules.add(module); ContextBuilder.addExecutorServiceIfNotPresent(modules); assertEquals(modules.size(), 1); assertEquals(modules.remove(0), module); }
### Question: Apis { public static ApiMetadata withId(String id) throws NoSuchElementException { return find(all(), ApiPredicates.id(id)); } static Function<ApiMetadata, String> idFunction(); static Iterable<ApiMetadata> all(); static ApiMetadata withId(String id); static Iterable<ApiMetadata> contextAssignableFrom(TypeToken<?> type); static Iterable<ApiMetadata> viewableAs(TypeToken<? extends View> type); static Iterable<ApiMetadata> viewableAs(Class<? extends View> type); static TypeToken<?> findView(final ApiMetadata apiMetadata, final TypeToken<?> view); }### Answer: @Test public void testWithId() { ApiMetadata apiMetadata; try { apiMetadata = Apis.withId("fake-id"); fail("Looking for a api with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { } apiMetadata = Apis.withId(testBlobstoreApi.getId()); assertEquals(testBlobstoreApi, apiMetadata); } @Test public void testWithId() { ApiMetadata apiMetadata; try { apiMetadata = Apis.withId("fake-id"); fail("Looking for a api with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { ; } apiMetadata = Apis.withId(testBlobstoreApi.getId()); assertEquals(testBlobstoreApi, apiMetadata); }
### Question: IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort, Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks, Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidCidr() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .cidrBlock("a.0.0.0/0").build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidExclusionCidr() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .exclusionCidrBlock("a.0.0.0/0").build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidCidrMultiple() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .cidrBlocks(ImmutableSet.of("a.0.0.0/0", "0.0.0.0/0")).build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidExclusionCidrMultiple() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .exclusionCidrBlocks(ImmutableSet.of("a.0.0.0/0", "0.0.0.0/0")).build()); }
### Question: ConvertToJcloudsResponse implements Function<HTTPResponse, HttpResponse> { @Override public HttpResponse apply(HTTPResponse gaeResponse) { Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse.getContent()) : null; Multimap<String, String> headers = LinkedHashMultimap.create(); String message = null; for (HTTPHeader header : gaeResponse.getHeaders()) { if (header.getName() == null) message = header.getValue(); else headers.put(header.getName(), header.getValue()); } if (payload != null) { contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); } return HttpResponse.builder() .statusCode(gaeResponse.getResponseCode()) .message(message) .payload(payload) .headers(filterOutContentHeaders(headers)).build(); } @Inject ConvertToJcloudsResponse(ContentMetadataCodec contentMetadataCodec); @Override HttpResponse apply(HTTPResponse gaeResponse); }### Answer: @Test void testConvertWithContent() throws IOException { HTTPResponse gaeResponse = createMock(HTTPResponse.class); expect(gaeResponse.getResponseCode()).andReturn(200); List<HTTPHeader> headers = Lists.newArrayList(); headers.add(new HTTPHeader(HttpHeaders.CONTENT_TYPE, "text/xml")); expect(gaeResponse.getHeaders()).andReturn(headers); expect(gaeResponse.getContent()).andReturn("hello".getBytes()).atLeastOnce(); replay(gaeResponse); HttpResponse response = req.apply(gaeResponse); assertEquals(response.getStatusCode(), 200); assertEquals(Strings2.toStringAndClose(response.getPayload().openStream()), "hello"); assertEquals(response.getHeaders().size(), 0); assertEquals(response.getPayload().getContentMetadata().getContentType(), "text/xml"); } @Test void testConvertWithHeaders() throws IOException { HTTPResponse gaeResponse = createMock(HTTPResponse.class); expect(gaeResponse.getResponseCode()).andReturn(200); List<HTTPHeader> headers = Lists.newArrayList(); headers.add(new HTTPHeader(HttpHeaders.CONTENT_TYPE, "text/xml")); expect(gaeResponse.getHeaders()).andReturn(headers); expect(gaeResponse.getContent()).andReturn(null).atLeastOnce(); replay(gaeResponse); HttpResponse response = req.apply(gaeResponse); assertEquals(response.getStatusCode(), 200); assertEquals(response.getPayload(), null); assertEquals(response.getHeaders().size(), 0); } @Test void testConvertWithContent() throws IOException { HTTPResponse gaeResponse = createMock(HTTPResponse.class); expect(gaeResponse.getResponseCode()).andReturn(200); List<HTTPHeader> headers = Lists.newArrayList(); headers.add(new HTTPHeader(HttpHeaders.CONTENT_TYPE, "text/xml")); expect(gaeResponse.getHeaders()).andReturn(headers); expect(gaeResponse.getContent()).andReturn("hello".getBytes()).atLeastOnce(); replay(gaeResponse); HttpResponse response = req.apply(gaeResponse); assertEquals(response.getStatusCode(), 200); assertEquals(Strings2.toString(response.getPayload()), "hello"); assertEquals(response.getHeaders().size(), 0); assertEquals(response.getPayload().getContentMetadata().getContentType(), "text/xml"); }
### Question: InitScriptConfigurationForTasks { @Inject(optional = true) public InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) { this.initScriptPattern = checkNotNull(initScriptPattern, "initScriptPattern ex. /tmp/init-%s"); checkArgument(this.initScriptPattern.startsWith("/"), "initScriptPattern must be a UNIX-style path starting at the root (/)"); int lastSlash = initScriptPattern.lastIndexOf('/'); if (lastSlash == 0) { this.basedir = "/"; } else { this.basedir = initScriptPattern.substring(0, lastSlash); } return this; } protected InitScriptConfigurationForTasks(); static InitScriptConfigurationForTasks create(); @Inject(optional = true) InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern); InitScriptConfigurationForTasks appendCurrentTimeMillisToAnonymousTaskNames(); InitScriptConfigurationForTasks appendIncrementingNumberToAnonymousTaskNames(); String getBasedir(); String getInitScriptPattern(); Supplier<String> getAnonymousTaskSuffixSupplier(); static final String PROPERTY_INIT_SCRIPT_PATTERN; }### Answer: @Test public void testInitScriptPattern() throws Exception { InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create(); config.initScriptPattern("/var/tmp/jclouds-%s"); assertEquals(config.getBasedir(), "/var/tmp"); assertEquals(config.getInitScriptPattern(), "/var/tmp/jclouds-%s"); }
### Question: ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void registerImage(Image image) { checkNotNull(image, "image"); imageCache.put(image.getId(), image); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds, AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testRegisterNullImageIsNotAllowed() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); imageCache.registerImage(null); }
### Question: ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds, AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testRemoveNullImageIsNotAllowed() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); imageCache.removeImage(null); } @Test public void testRemoveImage() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); imageCache.removeImage(image.getId()); assertEquals(imageCache.get().size(), 0); }
### Question: ConvertToGaeRequest implements Function<HttpRequest, HTTPRequest> { @Override public HTTPRequest apply(HttpRequest request) { URL url = null; try { url = request.getEndpoint().toURL(); } catch (MalformedURLException e) { Throwables.propagate(e); } FetchOptions options = disallowTruncate(); options.doNotFollowRedirects(); if (utils.relaxHostname() || utils.trustAllCerts()) options.doNotFollowRedirects(); options.setDeadline(10.0); HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options); for (Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); if (!prohibitedHeaders.contains(header)) gaeRequest.addHeader(new HTTPHeader(header, entry.getValue())); } gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT)); if (request.getPayload() != null) { InputStream input = request.getPayload().getInput(); try { byte[] array = ByteStreams.toByteArray(input); if (!request.getPayload().isRepeatable()) { Payload oldPayload = request.getPayload(); request.setPayload(array); HttpUtils.copy(oldPayload.getContentMetadata(), request.getPayload().getContentMetadata()); } gaeRequest.setPayload(array); if (array.length > 0) { gaeRequest.setHeader(new HTTPHeader("Expect", "100-continue")); } } catch (IOException e) { Throwables.propagate(e); } finally { Closeables2.closeQuietly(input); } for (Entry<String, String> header : contentMetadataCodec.toHeaders( request.getPayload().getContentMetadata()).entries()) { if (!prohibitedHeaders.contains(header.getKey())) gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue())); } } return gaeRequest; } @Inject ConvertToGaeRequest(HttpUtils utils, ContentMetadataCodec contentMetadataCodec); @Override HTTPRequest apply(HttpRequest request); static final String USER_AGENT; final Set<String> prohibitedHeaders; }### Answer: @Test void testConvertRequestGetsTargetAndUri() throws IOException { HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(endPoint).build(); HTTPRequest gaeRequest = req.apply(request); assertEquals(gaeRequest.getURL().getPath(), "/foo"); } @Test void testConvertRequestSetsFetchOptions() throws IOException { HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(endPoint).build(); HTTPRequest gaeRequest = req.apply(request); assert gaeRequest.getFetchOptions() != null; } @Test void testConvertRequestSetsHeaders() throws IOException { HttpRequest request = HttpRequest.builder() .method(HttpMethod.GET) .endpoint(endPoint) .addHeader("foo", "bar").build(); HTTPRequest gaeRequest = req.apply(request); assertEquals(gaeRequest.getHeaders().get(0).getName(), "foo"); assertEquals(gaeRequest.getHeaders().get(0).getValue(), "bar"); } @Test void testConvertRequestNoContent() throws IOException { HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(endPoint).build(); HTTPRequest gaeRequest = req.apply(request); assert gaeRequest.getPayload() == null; assertEquals(gaeRequest.getHeaders().size(), 1); assertEquals(gaeRequest.getHeaders().get(0).getName(), HttpHeaders.USER_AGENT); assertEquals(gaeRequest.getHeaders().get(0).getValue(), "jclouds/1.0 urlfetch/1.4.3"); } @Test(expectedExceptions = UnsupportedOperationException.class) void testConvertRequestBadContent() throws IOException { HttpRequest request = HttpRequest.builder() .method(HttpMethod.GET) .endpoint(endPoint) .payload(Payloads.newPayload(new Date())).build(); req.apply(request); }
### Question: ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds, AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }### Answer: @Test public void testLoadImage() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); } @Test public void testSupplierExpirationReloadsTheCache() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 3, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); Uninterruptibles.sleepUninterruptibly(4, TimeUnit.SECONDS); assertEquals(imageCache.get().size(), 1); assertFalse(any(imageCache.get(), idEquals("foo"))); }
### Question: ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester, @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning, @Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); }### Answer: @Test public void testSocketFinderAllowedInterfacesAll() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.ALL); assertTrue(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); } @Test public void testSocketFinderAllowedInterfacesPrivate() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PRIVATE); assertFalse(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); } @Test public void testSocketFinderAllowedInterfacesPublic() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PUBLIC); assertTrue(ips.contains(PUBLIC_IP)); assertFalse(ips.contains(PRIVATE_IP)); }
### Question: ComputeServiceUtils { public static String formatStatus(ComputeMetadataIncludingStatus<?> resource) { if (resource.getBackendStatus() == null) return resource.getStatus().toString(); return String.format("%s[%s]", resource.getStatus(), resource.getBackendStatus()); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }### Answer: @SuppressWarnings("unchecked") @Test public void testFormatStatusWithBackendStatus() { ComputeMetadataIncludingStatus<Image.Status> resource = createMock(ComputeMetadataIncludingStatus.class); expect(resource.getStatus()).andReturn(Image.Status.PENDING); expect(resource.getBackendStatus()).andReturn("queued").anyTimes(); replay(resource); assertEquals(formatStatus(resource), "PENDING[queued]"); verify(resource); } @SuppressWarnings("unchecked") @Test public void testFormatStatusWithoutBackendStatus() { ComputeMetadataIncludingStatus<Image.Status> resource = createMock(ComputeMetadataIncludingStatus.class); expect(resource.getStatus()).andReturn(Image.Status.PENDING); expect(resource.getBackendStatus()).andReturn(null).anyTimes(); replay(resource); assertEquals(formatStatus(resource), "PENDING"); verify(resource); }
### Question: ComputeServiceUtils { public static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options) { Builder<String, String> builder = ImmutableMap.<String, String> builder(); builder.putAll(options.getUserMetadata()); for (String tag : options.getTags()) builder.put(tag, ""); return builder.build(); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }### Answer: @Test public void testMetadataAndTagsAsValuesOfEmptyString() { TemplateOptions options = TemplateOptions.Builder.tags(ImmutableSet.of("tag")).userMetadata(ImmutableMap.<String, String>of("foo", "bar")); assertEquals(metadataAndTagsAsValuesOfEmptyString(options), ImmutableMap.<String, String>of("foo", "bar", "tag", "")); } @Test public void testMetadataAndTagsAsValuesOfEmptyStringNoTags() { TemplateOptions options = TemplateOptions.Builder.userMetadata(ImmutableMap.<String, String>of("foo", "bar")); assertEquals(metadataAndTagsAsValuesOfEmptyString(options), ImmutableMap.<String, String>of("foo", "bar")); }
### Question: ComputeServiceUtils { public static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options) { Builder<String, String> builder = ImmutableMap.<String, String> builder(); builder.putAll(options.getUserMetadata()); if (!options.getTags().isEmpty()) builder.put("jclouds_tags", Joiner.on(',').join(options.getTags())); return builder.build(); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }### Answer: @Test public void testMetadataAndTagsAsCommaDelimitedValue() { TemplateOptions options = TemplateOptions.Builder.tags(ImmutableSet.of("tag")).userMetadata(ImmutableMap.<String, String>of("foo", "bar")); assertEquals(metadataAndTagsAsCommaDelimitedValue(options), ImmutableMap.<String, String>of("foo", "bar", "jclouds_tags", "tag")); } @Test public void testMetadataAndTagsAsCommaDelimitedValueNoTags() { TemplateOptions options = TemplateOptions.Builder.userMetadata(ImmutableMap.<String, String>of("foo", "bar")); assertEquals(metadataAndTagsAsCommaDelimitedValue(options), ImmutableMap.<String, String>of("foo", "bar")); }
### Question: ComputeServiceUtils { public static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap) { if (osVersionMap.containsKey(family)) { if (osVersionMap.get(family).containsKey(in)) return osVersionMap.get(family).get(in); if (osVersionMap.get(family).containsValue(in)) return in; ContainsSubstring contains = new ContainsSubstring(in.replace('-', '.')); try { String key = Iterables.find(osVersionMap.get(family).keySet(), contains); return osVersionMap.get(family).get(key); } catch (NoSuchElementException e) { try { return Iterables.find(osVersionMap.get(family).values(), contains); } catch (NoSuchElementException e1) { } } } return ""; } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }### Answer: @Test public void testParseVersionOrReturnEmptyStringUbuntu1004() { assertEquals(parseVersionOrReturnEmptyString(OsFamily.UBUNTU, "Ubuntu 10.04", map), "10.04"); } @Test public void testParseVersionOrReturnEmptyStringUbuntu1104() { assertEquals(parseVersionOrReturnEmptyString(OsFamily.UBUNTU, "ubuntu 11.04 server (i386)", map), "11.04"); }
### Question: ComputeServiceUtils { public static Statement execHttpResponse(HttpRequest request) { return pipeHttpResponseToBash(request.getMethod(), request.getEndpoint(), request.getHeaders()); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }### Answer: @Test public void testExecHttpResponse() { HttpRequest request = HttpRequest.builder() .method("GET") .endpoint("https: .addHeader("Host", "adriancolehappy.s3.amazonaws.com") .addHeader("Date", "Sun, 12 Sep 2010 08:25:19 GMT") .addHeader("Authorization", "AWS 0ASHDJAS82:JASHFDA=").build(); assertEquals( ComputeServiceUtils.execHttpResponse(request).render(org.jclouds.scriptbuilder.domain.OsFamily.UNIX), "curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \"Host: adriancolehappy.s3.amazonaws.com\" -H \"Date: Sun, 12 Sep 2010 08:25:19 GMT\" -H \"Authorization: AWS 0ASHDJAS82:JASHFDA=\" https: }
### Question: ComputeServiceUtils { public static Statement extractTargzIntoDirectory(HttpRequest targz, String directory) { return Statements .extractTargzIntoDirectory(targz.getMethod(), targz.getEndpoint(), targz.getHeaders(), directory); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }### Answer: @Test public void testTarxzpHttpResponse() { HttpRequest request = HttpRequest.builder() .method("GET") .endpoint("https: .addHeader("Host", "adriancolehappy.s3.amazonaws.com") .addHeader("Date", "Sun, 12 Sep 2010 08:25:19 GMT") .addHeader("Authorization", "AWS 0ASHDJAS82:JASHFDA=").build(); assertEquals( ComputeServiceUtils.extractTargzIntoDirectory(request, "/stage/").render( org.jclouds.scriptbuilder.domain.OsFamily.UNIX), "curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \"Host: adriancolehappy.s3.amazonaws.com\" -H \"Date: Sun, 12 Sep 2010 08:25:19 GMT\" -H \"Authorization: AWS 0ASHDJAS82:JASHFDA=\" https: }
### Question: ComputeServiceUtils { public static Map<Integer, Integer> getPortRangesFromList(int... ports) { Set<Integer> sortedPorts = ImmutableSortedSet.copyOf(Ints.asList(ports)); RangeSet<Integer> ranges = TreeRangeSet.create(); for (Integer port : sortedPorts) { ranges.add(Range.closedOpen(port, port + 1)); } Map<Integer, Integer> portRanges = Maps.newHashMap(); for (Range<Integer> r : ranges.asRanges()) { portRanges.put(r.lowerEndpoint(), r.upperEndpoint() - 1); } return portRanges; } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }### Answer: @Test public void testGetPortRangesFromList() { Map<Integer, Integer> portRanges = Maps.newHashMap(); portRanges.put(5, 7); portRanges.put(10, 11); portRanges.put(20, 20); assertEquals(portRanges, ComputeServiceUtils.getPortRangesFromList(5, 6, 7, 10, 11, 20)); }
### Question: AutomaticHardwareIdSpec { public static boolean isAutomaticId(String id) { return id.startsWith("automatic:"); } static boolean isAutomaticId(String id); static AutomaticHardwareIdSpec parseId(String hardwareId); static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk); @Override String toString(); double getCores(); int getRam(); Optional<Float> getDisk(); }### Answer: @Test public void isAutomaticIdTest() { assertThat(AutomaticHardwareIdSpec.isAutomaticId("automatic:cores=2;ram=256")).isTrue(); } @Test public void isNotAutomaticId() { assertThat(AutomaticHardwareIdSpec.isAutomaticId("Hi, I'm a non automatic id.")).isFalse(); }
### Question: AutomaticHardwareIdSpec { public static AutomaticHardwareIdSpec parseId(String hardwareId) { AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec(); String hardwareSpec = hardwareId.substring(10); Map<String, String> specValues = Splitter.on(';') .trimResults() .omitEmptyStrings() .withKeyValueSeparator('=') .split(hardwareSpec); if (!specValues.containsKey("ram") || !specValues.containsKey("cores")) { throw new IllegalArgumentException(String.format("Omitted keys on hardwareId: %s. Please set number " + "of cores and ram amount.", hardwareId)); } if (specValues.containsKey("disk")) { float disk = Float.parseFloat(specValues.get("disk")); if (disk > 0.0f) { spec.disk = Optional.of(disk); } else { throw new IllegalArgumentException(String.format("Invalid disk value: %s", hardwareId)); } } spec.ram = Integer.parseInt(specValues.get("ram")); spec.cores = Double.parseDouble(specValues.get("cores")); return spec; } static boolean isAutomaticId(String id); static AutomaticHardwareIdSpec parseId(String hardwareId); static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk); @Override String toString(); double getCores(); int getRam(); Optional<Float> getDisk(); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void parseAutomaticIdMissingValuesTest() { AutomaticHardwareIdSpec.parseId("automatic:cores=2"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Invalid disk value: automatic:cores=2;ram=4096;disk=-100") public void parseAutomaticIdInvalidDiskTest() { AutomaticHardwareIdSpec.parseId("automatic:cores=2;ram=4096;disk=-100"); }
### Question: AutomaticHardwareIdSpec { public static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk) { AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec(); if (cores <= 0 || ram == 0) { throw new IllegalArgumentException(String.format("Omitted or wrong minCores and minRam. If you want to" + " use exact values, please set the minCores and minRam values: cores=%s, ram=%s", cores, ram)); } if (disk.isPresent() && disk.get() <= 0.0f) { throw new IllegalArgumentException(String.format("Invalid disk value: %.0f", disk.get())); } spec.disk = disk; spec.cores = cores; spec.ram = ram; return spec; } static boolean isAutomaticId(String id); static AutomaticHardwareIdSpec parseId(String hardwareId); static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk); @Override String toString(); double getCores(); int getRam(); Optional<Float> getDisk(); }### Answer: @Test public void automaticHardwareIdSpecBuilderTest() { AutomaticHardwareIdSpec spec = AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 2048, Optional.<Float>absent()); assertThat(spec.getCores()).isEqualTo(2.0); assertThat(spec.getRam()).isEqualTo(2048); assertThat(spec.toString()).isEqualTo("automatic:cores=2.0;ram=2048"); AutomaticHardwareIdSpec spec2 = AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(4.0, 4096, Optional.of(10.0f)); assertThat(spec2.getCores()).isEqualTo(4.0); assertThat(spec2.getRam()).isEqualTo(4096); assertThat(spec2.getDisk().get()).isEqualTo(10); assertThat(spec2.toString()).isEqualTo("automatic:cores=4.0;ram=4096;disk=10"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Omitted or wrong minCores and minRam. If you want to" + " use exact values, please set the minCores and minRam values: cores=2.0, ram=0") public void automaticHardwareIdSpecBuilderWrongSpecsTest() { AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 0, Optional.<Float>absent()); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Invalid disk value: -10") public void automaticHardwareIdSpecBuilderWrongDiskTest() { AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 2048, Optional.of(-10.0f)); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions installPrivateKey(String privateKey) { checkArgument(checkNotNull(privateKey, "privateKey").startsWith("-----BEGIN RSA PRIVATE KEY-----"), "key should start with -----BEGIN RSA PRIVATE KEY-----"); this.privateKey = privateKey; return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testinstallPrivateKeyBadFormat() { TemplateOptions options = new TemplateOptions(); options.installPrivateKey("whompy"); } @Test public void testinstallPrivateKey() throws IOException { TemplateOptions options = new TemplateOptions(); options.installPrivateKey("-----BEGIN RSA PRIVATE KEY-----"); assertEquals(options.toString(), "{privateKeyPresent=true}"); assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----"); } @Test(expectedExceptions = NullPointerException.class) public void testinstallPrivateKeyNPE() { installPrivateKey((String) null); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public String getPrivateKey() { return privateKey; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testNullinstallPrivateKey() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getPrivateKey(), null); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions authorizePublicKey(String publicKey) { checkArgument(checkNotNull(publicKey, "publicKey").startsWith("ssh-rsa"), "key should start with ssh-rsa"); this.publicKey = publicKey; return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testauthorizePublicKeyBadFormat() { TemplateOptions options = new TemplateOptions(); options.authorizePublicKey("whompy"); } @Test public void testauthorizePublicKey() throws IOException { TemplateOptions options = new TemplateOptions(); options.authorizePublicKey("ssh-rsa"); assertEquals(options.toString(), "{publicKeyPresent=true}"); assertEquals(options.getPublicKey(), "ssh-rsa"); } @Test(expectedExceptions = NullPointerException.class) public void testauthorizePublicKeyNPE() { authorizePublicKey((String) null); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public String getPublicKey() { return publicKey; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testNullauthorizePublicKey() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getPublicKey(), null); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { @Override public TemplateOptions blockOnPort(int port, int seconds) { return TemplateOptions.class.cast(super.blockOnPort(port, seconds)); } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testblockOnPortBadFormat() { TemplateOptions options = new TemplateOptions(); options.blockOnPort(-1, -1); } @Test public void testblockOnPort() { TemplateOptions options = new TemplateOptions(); options.blockOnPort(22, 30); assertEquals(options.toString(), "{blockOnPort:seconds=22:30}"); assertEquals(options.getPort(), 22); assertEquals(options.getSeconds(), 30); } @Test public void testblockOnPortStatic() { TemplateOptions options = blockOnPort(22, 30); assertEquals(options.getPort(), 22); assertEquals(options.getSeconds(), 30); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions inboundPorts(int... ports) { for (int port : ports) checkArgument(port > 0 && port < 65536, "port must be a positive integer < 65535"); this.inboundPorts = ImmutableSet.copyOf(Ints.asList(ports)); return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testinboundPortsBadFormat() { TemplateOptions options = new TemplateOptions(); options.inboundPorts(-1, -1); } @Test public void testinboundPorts() { TemplateOptions options = new TemplateOptions(); options.inboundPorts(22, 30); assertEquals(options.getInboundPorts()[0], 22); assertEquals(options.getInboundPorts()[1], 30); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public int[] getInboundPorts() { return Ints.toArray(inboundPorts); } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testDefaultOpen22() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getInboundPorts()[0], 22); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public boolean shouldBlockUntilRunning() { return blockUntilRunning; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testblockUntilRunningDefault() { TemplateOptions options = new TemplateOptions(); assertEquals(options.toString(), "{}"); assertEquals(options.shouldBlockUntilRunning(), true); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions blockUntilRunning(boolean blockUntilRunning) { this.blockUntilRunning = blockUntilRunning; if (!blockUntilRunning) port = seconds = -1; return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testblockUntilRunning() { TemplateOptions options = new TemplateOptions(); options.blockUntilRunning(false); assertEquals(options.toString(), "{blockUntilRunning=false}"); assertEquals(options.shouldBlockUntilRunning(), false); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions nodeNames(Iterable<String> nodeNames) { this.nodeNames = ImmutableSet.copyOf(checkNotNull(nodeNames, "nodeNames")); return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testNodeNames() { Set<String> nodeNames = ImmutableSet.of("first-node", "second-node"); TemplateOptions options = nodeNames(nodeNames); assertTrue(options.getNodeNames().containsAll(nodeNames)); }
### Question: TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions networks(Iterable<String> networks) { this.networks = ImmutableSet.copyOf(checkNotNull(networks, "networks")); return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }### Answer: @Test public void testNetworks() { Set<String> networks = ImmutableSet.of("first-network", "second-network"); TemplateOptions options = networks(networks); assertTrue(options.getNetworks().containsAll(networks)); }
### Question: NodeAndTemplateOptionsToStatementWithoutPublicKey implements NodeAndTemplateOptionsToStatement { @Override public Statement apply(NodeMetadata node, TemplateOptions options) { ImmutableList.Builder<Statement> builder = ImmutableList.builder(); if (options.getRunScript() != null) { builder.add(options.getRunScript()); } if (options.getPrivateKey() != null) { builder.add(new InstallRSAPrivateKey(options.getPrivateKey())); } ImmutableList<Statement> bootstrap = builder.build(); if (!bootstrap.isEmpty()) { if (options.getTaskName() == null && !(options.getRunScript() instanceof InitScript)) { options.nameTask("bootstrap"); } return bootstrap.size() == 1 ? bootstrap.get(0) : new StatementList(bootstrap); } return null; } @Override Statement apply(NodeMetadata node, TemplateOptions options); }### Answer: @Test public void testPublicKeyDoesNotGenerateAuthorizePublicKeyStatementIfOnlyPublicKeyOptionsConfigured() { Map<String, String> keys = SshKeys.generate(); TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get("public")); NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey(); assertNull(function.apply(null, options)); } @Test public void testPublicAndRunScriptKeyDoesNotGenerateAuthorizePublicKeyStatementIfRunScriptPresent() { Map<String, String> keys = SshKeys.generate(); TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get("public")).runScript("uptime"); NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey(); Statement statement = function.apply(null, options); assertEquals(statement.render(OsFamily.UNIX), "uptime\n"); } @Test public void testPublicAndPrivateKeyAndRunScriptDoesNotGenerateAuthorizePublicKeyStatementIfOtherOptionsPresent() { Map<String, String> keys = SshKeys.generate(); TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get("public")) .installPrivateKey(keys.get("private")).runScript("uptime"); NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey(); Statement statement = function.apply(null, options); assertTrue(statement instanceof StatementList); StatementList statements = (StatementList) statement; assertEquals(statements.size(), 2); assertEquals(statements.get(0).render(OsFamily.UNIX), "uptime\n"); assertTrue(statements.get(1) instanceof InstallRSAPrivateKey); }
### Question: PollNodeRunning implements Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>> { @Override public AtomicReference<NodeMetadata> apply(AtomicReference<NodeMetadata> node) throws IllegalStateException { String originalId = node.get().getId(); NodeMetadata originalNode = node.get(); try { Stopwatch stopwatch = Stopwatch.createStarted(); if (!nodeRunning.apply(node)) { long timeWaited = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (node.get() == null) { node.set(originalNode); throw new IllegalStateException(format("api response for node(%s) was null", originalId)); } else { throw new IllegalStateException(format( "node(%s) didn't achieve the status running; aborting after %d seconds with final status: %s", originalId, timeWaited / 1000, formatStatus(node.get()))); } } } catch (IllegalStateException e) { if (node.get().getStatus() == Status.TERMINATED) { throw new IllegalStateException(format("node(%s) terminated", originalId)); } else { throw propagate(e); } } return node; } @Inject PollNodeRunning(@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning); @Override AtomicReference<NodeMetadata> apply(AtomicReference<NodeMetadata> node); }### Answer: @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "node\\(id\\) didn't achieve the status running; aborting after 0 seconds with final status: PENDING") public void testIllegalStateExceptionWhenNodeStillPending() { final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() { @Override public boolean apply(AtomicReference<NodeMetadata> input) { assertEquals(input.get(), pendingNode); return false; } }; AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode); try { new PollNodeRunning(nodeRunning).apply(atomicNode); } finally { assertEquals(atomicNode.get(), pendingNode); } } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "node\\(id\\) terminated") public void testIllegalStateExceptionWhenNodeDied() { final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); final NodeMetadata deadNode = new NodeMetadataBuilder().ids("id").status(Status.TERMINATED).build(); Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() { @Override public boolean apply(AtomicReference<NodeMetadata> input) { assertEquals(input.get(), pendingNode); input.set(deadNode); return false; } }; AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode); try { new PollNodeRunning(nodeRunning).apply(atomicNode); } finally { assertEquals(atomicNode.get(), deadNode); } } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "api response for node\\(id\\) was null") public void testIllegalStateExceptionAndNodeResetWhenRefSetToNull() { final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() { @Override public boolean apply(AtomicReference<NodeMetadata> input) { assertEquals(input.get(), pendingNode); input.set(null); return false; } }; AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode); try { new PollNodeRunning(nodeRunning).apply(atomicNode); } finally { assertEquals(atomicNode.get(), pendingNode); } }
### Question: JschSshClient implements SshClient { SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); if (e.getMessage() != null && e.getMessage().indexOf("Auth fail") != -1) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } JschSshClient(ProxyConfig proxyConfig, BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket, LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); @Override void put(String path, String contents); void connect(); Payload get(String path); @Override void put(String path, Payload contents); @Override String toString(); @Override @PreDestroy void disconnect(); @Override boolean isConnected(); ExecResponse exec(String command); @Override String getHostAddress(); @Override String getUsername(); @Override ExecChannel execChannel(String command); }### Answer: @Test(expectedExceptions = AuthorizationException.class) public void testPropateConvertsAuthException() { ssh.propagate(new JSchException("Auth fail"), ""); }
### Question: DelegatingImageExtension implements ImageExtension { public boolean deleteImage(String id) { boolean success = delegate.deleteImage(id); if (success) { imageCache.removeImage(id); } return success; } @Inject DelegatingImageExtension(@Assisted ImageCacheSupplier imageCache, @Assisted ImageExtension delegate, AddDefaultCredentialsToImage addDefaultCredentialsToImage, Map<String, Credentials> credentialStore); ImageTemplate buildImageTemplateFromNode(String name, String id); ListenableFuture<Image> createImage(final ImageTemplate template); boolean deleteImage(String id); }### Answer: @Test public void deleteUnregistersImageFromCache() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); expect(delegate.deleteImage("test")).andReturn(true); imageCache.removeImage("test"); expectLastCall(); replay(delegate, imageCache); new DelegatingImageExtension(imageCache, delegate, null, null).deleteImage("test"); verify(delegate, imageCache); } @Test public void deleteDoesNotUnregisterImageFromCacheWhenFailed() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); expect(delegate.deleteImage("test")).andReturn(false); replay(delegate, imageCache); new DelegatingImageExtension(imageCache, delegate, null, null).deleteImage("test"); verify(delegate, imageCache); }
### Question: ProfitBricksSoapMessageEnvelope implements HttpRequestFilter { @Override public HttpRequest filter(HttpRequest request) throws HttpException { checkNotNull(request.getPayload(), "HTTP Request must contain payload message."); return createSoapRequest(request); } @Override HttpRequest filter(HttpRequest request); }### Answer: @Test public void testPayloadEnclosedWithSoapTags() { String requestBody = "<ws:getAllDataCenters/>"; String expectedPayload = SOAP_PREFIX.concat(requestBody).concat(SOAP_SUFFIX); HttpRequest request = HttpRequest.builder().method("POST").endpoint(ENDPOINT).payload(requestBody).build(); ProfitBricksSoapMessageEnvelope soapEnvelope = new ProfitBricksSoapMessageEnvelope(); HttpRequest filtered = soapEnvelope.filter(request); assertEquals(filtered.getPayload().getRawContent(), expectedPayload); assertEquals(filtered.getPayload().getContentMetadata().getContentLength(), Long.valueOf(expectedPayload.getBytes().length)); } @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = ".*must contain payload message.*") public void testNullRequest() { HttpRequest request = HttpRequest.builder().method("POST").endpoint(ENDPOINT).build(); new ProfitBricksSoapMessageEnvelope().filter(request); }
### Question: NullEqualToIsParentOrIsGrandparentOfCurrentLocation implements Predicate<ComputeMetadata> { @Override public boolean apply(ComputeMetadata input) { Location current = locationSupplier.get(); if (current == null) return true; if (input.getLocation() == null) return true; Location parent = current.getParent(); checkArgument( parent != null || current.getScope() == LocationScope.PROVIDER, "only locations of scope PROVIDER can have a null parent; arg: %s", current); checkState( input.getLocation().getParent() != null || input.getLocation().getScope() == LocationScope.PROVIDER, "only locations of scope PROVIDER can have a null parent; input: %s", input.getLocation()); Builder<Predicate<Location>> predicates = ImmutableSet.builder(); predicates.add(equalTo(current)); if (parent != null) { predicates.add(equalTo(parent)); Location grandparent = parent.getParent(); if (grandparent != null) predicates.add(equalTo(grandparent)); } return Predicates.or(predicates.build()).apply(input.getLocation()); } NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Supplier<Location> locationSupplier); @Override boolean apply(ComputeMetadata input); @Override String toString(); }### Answer: @Test public void testReturnTrueWhenISpecifyARegionAndInputLocationIsProvider() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(provider).build(); assertTrue(predicate.apply(md)); } @Test public void testReturnFalseWhenISpecifyALocationWhichTheSameScopeByNotEqualToInputLocationAndParentsAreNull() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(otherRegion).build(); assertFalse(predicate.apply(md)); } @Test(expectedExceptions = IllegalStateException.class) public void testThrowIllegalStateExceptionWhenInputIsAnOrphanedRegion() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(orphanedRegion).build(); predicate.apply(md); } @Test(expectedExceptions = IllegalStateException.class) public void testThrowIllegalStateExceptionWhenInputIsAnOrphanedZone() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(orphanedZone).build(); predicate.apply(md); } @Test(expectedExceptions = IllegalArgumentException.class) public void testThrowIllegalArgumentExceptionWhenWhenISpecifyAnOrphanedRegion() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(orphanedRegion)); Hardware md = new HardwareBuilder().id("foo").location(region).build(); predicate.apply(md); } @Test(expectedExceptions = IllegalArgumentException.class) public void testThrowIllegalArgumentExceptionWhenWhenISpecifyAnOrphanedZone() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(orphanedZone)); Hardware md = new HardwareBuilder().id("foo").location(region).build(); predicate.apply(md); }
### Question: SshKeys { public static String fingerprint(BigInteger publicExponent, BigInteger modulus) { byte[] keyBlob = keyBlob(publicExponent, modulus); return hexColonDelimited(Hashing.md5().hashBytes(keyBlob)); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }### Answer: @Test public void testCanReadRsaAndCompareFingerprintOnPrivateRSAKey() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); RSAPrivateCrtKeySpec key = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey); String fingerPrint = fingerprint(key.getPublicExponent(), key.getModulus()); assertEquals(fingerPrint, expectedFingerprint); }
### Question: SshKeys { public static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint) { return fingerprint(privateKey.getPublicExponent(), privateKey.getModulus()).equals(fingerprint); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }### Answer: @Test public void testPrivateKeyMatchesFingerprintTyped() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); RSAPrivateCrtKeySpec privateKey = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey); assert privateKeyHasFingerprint(privateKey, expectedFingerprint); } @Test public void testPrivateKeyMatchesFingerprintString() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); assert privateKeyHasFingerprint(privKey, expectedFingerprint); }
### Question: SshKeys { public static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint) { return sha1(privateKey).equals(fingerprint); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }### Answer: @Test public void testPrivateKeyMatchesSha1Typed() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); RSAPrivateCrtKeySpec privateKey = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey); assert privateKeyHasSha1(privateKey, expectedSha1); } @Test public void testPrivateKeyMatchesSha1String() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); assert privateKeyHasSha1(privKey, expectedSha1); }
### Question: SshKeys { public static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH) { KeySpec privateKeySpec = privateKeySpec(privateKeyPEM); checkArgument(privateKeySpec instanceof RSAPrivateCrtKeySpec, "incorrect format expected RSAPrivateCrtKeySpec was %s", privateKeySpec); return privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec.class.cast(privateKeySpec), publicKeySpecFromOpenSSH(publicKeyOpenSSH)); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }### Answer: @Test public void testPrivateKeyMatchesPublicKeyString() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); String pubKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test.pub")); assert privateKeyMatchesPublicKey(privKey, pubKey); }
### Question: SshKeys { public static String encodeAsOpenSSH(RSAPublicKey key) { byte[] keyBlob = keyBlob(key.getPublicExponent(), key.getModulus()); return "ssh-rsa " + base64().encode(keyBlob); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }### Answer: @Test public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { String encoded = SshKeys.encodeAsOpenSSH((RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic( SshKeys.publicKeySpecFromOpenSSH(Resources.asByteSource(Resources.getResource(getClass(), "/test.pub"))))); assertEquals(encoded, Strings2.toStringAndClose(getClass().getResourceAsStream("/test.pub")).trim()); }
### Question: MacAddresses { public static boolean isMacAddress(String in) { return MAC_ADDR_PATTERN.matcher(in).matches(); } static boolean isMacAddress(String in); }### Answer: @Test public void testIsMacAddress() { for (String addr : expectedValidAddresses) assertTrue(isMacAddress(addr)); for (String addr : expectedInvalidAddresses) assertFalse(isMacAddress(addr)); }
### Question: DeregisterLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.DeregisterPayload> { @Override protected String createPayload(LoadBalancer.Request.DeregisterPayload payload) { requestBuilder.append("<ws:deregisterServersOnLoadBalancer>"); for (String s : payload.serverIds()) requestBuilder.append(format("<serverIds>%s</serverIds>", s)); requestBuilder.append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())) .append("</ws:deregisterServersOnLoadBalancer>"); return requestBuilder.toString(); } DeregisterLoadBalancerRequestBinder(); }### Answer: @Test public void testDeregisterPayload() { DeregisterLoadBalancerRequestBinder binder = new DeregisterLoadBalancerRequestBinder(); String actual = binder.createPayload(LoadBalancer.Request.createDeregisteringPayload( "load-balancer-id", ImmutableList.of("1", "2"))); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
### Question: BackoffOnNotFoundWhenGetBucketACL extends CacheLoader<String, AccessControlList> { @Override public AccessControlList load(String bucketName) { ResourceNotFoundException last = null; for (int currentTries = 0; currentTries < maxTries; currentTries++) { try { return client.getBucketACL(bucketName); } catch (ResourceNotFoundException e) { imposeBackoffExponentialDelay(100L, 200L, 2, currentTries, maxTries); last = e; } } throw last; } @Inject BackoffOnNotFoundWhenGetBucketACL(S3Client client); @Override AccessControlList load(String bucketName); @Override String toString(); }### Answer: @Test void testMaxRetriesNotExceededReturnsValue() { AccessControlList acl = createMock(AccessControlList.class); int attempts = 5; BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new ResourceNotFoundException()).times(attempts - 1); expect(mock.getBucketACL("foo")).andReturn(acl); replay(mock); assertSame(backoff.load("foo"), acl); verify(mock); } @Test(expectedExceptions = ResourceNotFoundException.class) void testMaxRetriesExceededThrowsException() { int attempts = 5; BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new ResourceNotFoundException()).times(attempts); replay(mock); backoff.load("foo"); } @Test(expectedExceptions = UncheckedExecutionException.class) void testDoesntCatchOtherExceptions() { BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new UncheckedExecutionException(new TimeoutException())); replay(mock); backoff.load("foo"); verify(mock); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions overrideMetadataWith(Map<String, String> metadata) { checkNotNull(metadata, "metadata"); this.metadata = metadata; return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testMetaNPE() { overrideMetadataWith(null); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public String getIfModifiedSince() { return getFirstHeaderOrNull(COPY_SOURCE_IF_MODIFIED_SINCE); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test public void testNullIfModifiedSince() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfModifiedSince()); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince) { checkState(getIfMatch() == null, "ifETagMatches() is not compatible with ifModifiedSince()"); checkState(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifModifiedSince()"); replaceHeader(COPY_SOURCE_IF_MODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull(ifModifiedSince, "ifModifiedSince"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testIfModifiedSinceNPE() { ifSourceModifiedSince(null); }
### Question: CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince) { checkState(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()"); checkState(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifUnmodifiedSince()"); replaceHeader(COPY_SOURCE_IF_UNMODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull(ifUnmodifiedSince, "ifUnmodifiedSince"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }### Answer: @Test public void testIfUnmodifiedSince() { CopyObjectOptions options = new CopyObjectOptions(); options.ifSourceUnmodifiedSince(now); isNowExpected(options); } @Test public void testIfUnmodifiedSinceStatic() { CopyObjectOptions options = ifSourceUnmodifiedSince(now); isNowExpected(options); } @Test(expectedExceptions = NullPointerException.class) public void testIfUnmodifiedSinceNPE() { ifSourceUnmodifiedSince(null); }
### Question: CreateLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.CreatePayload> { @Override protected String createPayload(LoadBalancer.Request.CreatePayload payload) { requestBuilder.append("<ws:createLoadBalancer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<loadBalancerName>%s</loadBalancerName>", payload.name())) .append(format("<loadBalancerAlgorithm>%s</loadBalancerAlgorithm>", payload.algorithm())) .append(format("<ip>%s</ip>", payload.ip())) .append(format("<lanId>%s</lanId>", payload.lanId())); for (String serverId : payload.serverIds()) requestBuilder.append(format("<serverIds>%s</serverIds>", serverId)); requestBuilder .append("</request>") .append("</ws:createLoadBalancer>"); return requestBuilder.toString(); } CreateLoadBalancerRequestBinder(); }### Answer: @Test public void testCreatePayload() { CreateLoadBalancerRequestBinder binder = new CreateLoadBalancerRequestBinder(); String actual = binder.createPayload( LoadBalancer.Request.creatingBuilder() .dataCenterId("datacenter-id") .name("load-balancer-name") .algorithm(Algorithm.ROUND_ROBIN) .ip("10.0.0.1") .lanId(2) .serverIds(ImmutableList.<String>of( "server-id-1", "server-id-2")) .build()); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }