target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeS3Object() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: injector.getInstance(BindS3ObjectMetadataToRequest.class).bindToRequest(request, new File("foo")); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } | BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } } | BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } @Inject BindS3ObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); } | BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } @Inject BindS3ObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } @Inject BindS3ObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } | BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } } | BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } @Inject BindS3ObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); } | BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } @Inject BindS3ObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } @Inject BindS3ObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test public void testWithASmallSet() { HttpRequest result = binder.bindToRequest(request, ImmutableSet.of("key1", "key2")); Payload payload = Payloads .newStringPayload("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Delete>" + "<Object><Key>key1</Key></Object><Object><Key>key2</Key></Object></Delete>"); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); assertEquals(result.getPayload(), payload); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testEmptySetThrowsException() { binder.bindToRequest(request, ImmutableSet.of()); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = NullPointerException.class) public void testFailsOnNullSet() { binder.bindToRequest(request, null); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testExpectedASetInstance() { binder.bindToRequest(request, ImmutableList.of()); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test public void testPassWithMinimumDetailsAndPayload5GB() { ObjectMetadata md = ObjectMetadataBuilder.create().key("foo").build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); assertEquals(binder.bindToRequest(request, md), HttpRequest.builder().method("POST") .endpoint("http: } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test public void testExtendedPropertiesBind() { ObjectMetadata md = ObjectMetadataBuilder.create().key("foo").cacheControl("no-cache").userMetadata( ImmutableMap.of("foo", "bar")).build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); assertEquals(binder.bindToRequest(request, md), HttpRequest.builder().method("POST").endpoint("http: ImmutableMultimap.of("Cache-Control", "no-cache", "x-amz-meta-foo", "bar", "Content-Type", "binary/octet-stream")).build()); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testNoKeyIsBad() { ObjectMetadata md = ObjectMetadataBuilder.create().build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); binder.bindToRequest(request, md); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test public void testCreatePayload() { ConnectStorageToServerRequestBinder binder = new ConnectStorageToServerRequestBinder(); Storage.Request.ConnectPayload payload = Storage.Request.connectingBuilder() .serverId("qwertyui-qwer-qwer-qwer-qwertyyuiiop") .storageId("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh") .busType(Storage.BusType.VIRTIO) .deviceNumber(2) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Storage.Request.ConnectPayload payload) { requestBuilder.append("<ws:connectStorageToServer>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<busType>%s</busType>", payload.busType())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:connectStorageToServer>"); return requestBuilder.toString(); } | ConnectStorageToServerRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.ConnectPayload> { @Override protected String createPayload(Storage.Request.ConnectPayload payload) { requestBuilder.append("<ws:connectStorageToServer>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<busType>%s</busType>", payload.busType())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:connectStorageToServer>"); return requestBuilder.toString(); } } | ConnectStorageToServerRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.ConnectPayload> { @Override protected String createPayload(Storage.Request.ConnectPayload payload) { requestBuilder.append("<ws:connectStorageToServer>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<busType>%s</busType>", payload.busType())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:connectStorageToServer>"); return requestBuilder.toString(); } ConnectStorageToServerRequestBinder(); } | ConnectStorageToServerRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.ConnectPayload> { @Override protected String createPayload(Storage.Request.ConnectPayload payload) { requestBuilder.append("<ws:connectStorageToServer>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<busType>%s</busType>", payload.busType())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:connectStorageToServer>"); return requestBuilder.toString(); } ConnectStorageToServerRequestBinder(); } | ConnectStorageToServerRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.ConnectPayload> { @Override protected String createPayload(Storage.Request.ConnectPayload payload) { requestBuilder.append("<ws:connectStorageToServer>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<busType>%s</busType>", payload.busType())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:connectStorageToServer>"); return requestBuilder.toString(); } ConnectStorageToServerRequestBinder(); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeObjectMetadata() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: injector.getInstance(BindObjectMetadataToRequest.class).bindToRequest(request, new File("foo")); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(dataProvider = "objects") public void testObject(String key) throws InterruptedException { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: BindAsHostPrefixIfConfigured binder = injector.getInstance(BindAsHostPrefixIfConfigured.class); request = binder.bindToRequest(request, "bucket"); assertEquals(request.getRequestLine(), "GET http: } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { String payloadAsString = payload.toString(); if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) { request = bindAsHostPrefix.bindToRequest(request, payload); String host = request.getEndpoint().getHost(); if (request.getEndpoint().getPort() != -1) { host += ":" + request.getEndpoint().getPort(); } return (R) request.toBuilder().replaceHeader(HttpHeaders.HOST, host).build(); } else { StringBuilder path = new StringBuilder(request.getEndpoint().getRawPath()); if (servicePath.equals("/")) { if (path.toString().equals("/")) path.append(payloadAsString); else path.insert(0, "/" + payloadAsString); } else { int indexToInsert = 0; indexToInsert = path.indexOf(servicePath); indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert += servicePath.length(); path.insert(indexToInsert, "/" + payloadAsString); } return (R) request.toBuilder().replacePath(path.toString()).build(); } } | BindAsHostPrefixIfConfigured implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { String payloadAsString = payload.toString(); if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) { request = bindAsHostPrefix.bindToRequest(request, payload); String host = request.getEndpoint().getHost(); if (request.getEndpoint().getPort() != -1) { host += ":" + request.getEndpoint().getPort(); } return (R) request.toBuilder().replaceHeader(HttpHeaders.HOST, host).build(); } else { StringBuilder path = new StringBuilder(request.getEndpoint().getRawPath()); if (servicePath.equals("/")) { if (path.toString().equals("/")) path.append(payloadAsString); else path.insert(0, "/" + payloadAsString); } else { int indexToInsert = 0; indexToInsert = path.indexOf(servicePath); indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert += servicePath.length(); path.insert(indexToInsert, "/" + payloadAsString); } return (R) request.toBuilder().replacePath(path.toString()).build(); } } } | BindAsHostPrefixIfConfigured implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { String payloadAsString = payload.toString(); if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) { request = bindAsHostPrefix.bindToRequest(request, payload); String host = request.getEndpoint().getHost(); if (request.getEndpoint().getPort() != -1) { host += ":" + request.getEndpoint().getPort(); } return (R) request.toBuilder().replaceHeader(HttpHeaders.HOST, host).build(); } else { StringBuilder path = new StringBuilder(request.getEndpoint().getRawPath()); if (servicePath.equals("/")) { if (path.toString().equals("/")) path.append(payloadAsString); else path.insert(0, "/" + payloadAsString); } else { int indexToInsert = 0; indexToInsert = path.indexOf(servicePath); indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert += servicePath.length(); path.insert(indexToInsert, "/" + payloadAsString); } return (R) request.toBuilder().replacePath(path.toString()).build(); } } @Inject BindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath); } | BindAsHostPrefixIfConfigured implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { String payloadAsString = payload.toString(); if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) { request = bindAsHostPrefix.bindToRequest(request, payload); String host = request.getEndpoint().getHost(); if (request.getEndpoint().getPort() != -1) { host += ":" + request.getEndpoint().getPort(); } return (R) request.toBuilder().replaceHeader(HttpHeaders.HOST, host).build(); } else { StringBuilder path = new StringBuilder(request.getEndpoint().getRawPath()); if (servicePath.equals("/")) { if (path.toString().equals("/")) path.append(payloadAsString); else path.insert(0, "/" + payloadAsString); } else { int indexToInsert = 0; indexToInsert = path.indexOf(servicePath); indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert += servicePath.length(); path.insert(indexToInsert, "/" + payloadAsString); } return (R) request.toBuilder().replacePath(path.toString()).build(); } } @Inject BindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object payload); } | BindAsHostPrefixIfConfigured implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { String payloadAsString = payload.toString(); if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) { request = bindAsHostPrefix.bindToRequest(request, payload); String host = request.getEndpoint().getHost(); if (request.getEndpoint().getPort() != -1) { host += ":" + request.getEndpoint().getPort(); } return (R) request.toBuilder().replaceHeader(HttpHeaders.HOST, host).build(); } else { StringBuilder path = new StringBuilder(request.getEndpoint().getRawPath()); if (servicePath.equals("/")) { if (path.toString().equals("/")) path.append(payloadAsString); else path.insert(0, "/" + payloadAsString); } else { int indexToInsert = 0; indexToInsert = path.indexOf(servicePath); indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert += servicePath.length(); path.insert(indexToInsert, "/" + payloadAsString); } return (R) request.toBuilder().replacePath(path.toString()).build(); } } @Inject BindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object payload); } |
@Test public void testPassWithMinimumDetailsAndPayload5GB() { HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: Payload payload = Payloads .newStringPayload("<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>\"a54357aff0632cce46d942af68356b38\"</ETag></Part></CompleteMultipartUpload>"); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request = binder.bindToRequest(request, ImmutableMap.<Integer, String> of(1, "\"a54357aff0632cce46d942af68356b38\"")); assertEquals(request.getPayload().getRawContent(), payload.getRawContent()); assertEquals(request, HttpRequest.builder().method("PUT").endpoint("http: payload).build()); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyIsBad() { HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: binder.bindToRequest(request, ImmutableMap.<Integer, String> of()); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); } | @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } | BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); } |
@Test(expectedExceptions = IllegalStateException.class) void testIllegalStateIsNotOk() throws Exception { S3Client client = createMock(S3Client.class); replay(client); Exception e = new IllegalStateException(); new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).createOrPropagate(e); } | @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } | FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,
InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } } | FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,
InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } @Inject FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client); } | FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,
InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } @Inject FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client); @Override Boolean createOrPropagate(Throwable t); @Override FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists setContext(@Nullable HttpRequest request); } | FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,
InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } @Inject FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client); @Override Boolean createOrPropagate(Throwable t); @Override FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists setContext(@Nullable HttpRequest request); } |
@Test(expectedExceptions = AWSResponseException.class) void testBlahIsNotOk() throws Exception { S3Client client = createMock(S3Client.class); replay(client); Exception e = getErrorWithCode("blah"); new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).createOrPropagate(e); } | @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } | FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,
InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } } | FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,
InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } @Inject FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client); } | FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,
InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } @Inject FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client); @Override Boolean createOrPropagate(Throwable t); @Override FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists setContext(@Nullable HttpRequest request); } | FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,
InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } @Inject FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client); @Override Boolean createOrPropagate(Throwable t); @Override FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists setContext(@Nullable HttpRequest request); } |
@Test public void test() { HttpResponse response = HttpResponse.builder().statusCode(200).payload( Payloads.newInputStreamPayload(getClass().getResourceAsStream("/complete-multipart-upload.xml"))) .build(); ETagFromHttpResponseViaRegex parser = new ETagFromHttpResponseViaRegex(new ReturnStringIf2xx()); assertEquals(parser.apply(response), "\"3858f62230ac3c915f300c664312c11f-9\""); } | @Override public String apply(HttpResponse response) { String value = null; String content = returnStringIf200.apply(response); if (content != null) { Matcher matcher = PATTERN.matcher(content); if (matcher.find()) { value = matcher.group(1); if (value.indexOf(ESCAPED_QUOTE) != -1) { value = value.replace(ESCAPED_QUOTE, "\""); } } } return value; } | ETagFromHttpResponseViaRegex implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String value = null; String content = returnStringIf200.apply(response); if (content != null) { Matcher matcher = PATTERN.matcher(content); if (matcher.find()) { value = matcher.group(1); if (value.indexOf(ESCAPED_QUOTE) != -1) { value = value.replace(ESCAPED_QUOTE, "\""); } } } return value; } } | ETagFromHttpResponseViaRegex implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String value = null; String content = returnStringIf200.apply(response); if (content != null) { Matcher matcher = PATTERN.matcher(content); if (matcher.find()) { value = matcher.group(1); if (value.indexOf(ESCAPED_QUOTE) != -1) { value = value.replace(ESCAPED_QUOTE, "\""); } } } return value; } @Inject ETagFromHttpResponseViaRegex(ReturnStringIf2xx returnStringIf200); } | ETagFromHttpResponseViaRegex implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String value = null; String content = returnStringIf200.apply(response); if (content != null) { Matcher matcher = PATTERN.matcher(content); if (matcher.find()) { value = matcher.group(1); if (value.indexOf(ESCAPED_QUOTE) != -1) { value = value.replace(ESCAPED_QUOTE, "\""); } } } return value; } @Inject ETagFromHttpResponseViaRegex(ReturnStringIf2xx returnStringIf200); @Override String apply(HttpResponse response); } | ETagFromHttpResponseViaRegex implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String value = null; String content = returnStringIf200.apply(response); if (content != null) { Matcher matcher = PATTERN.matcher(content); if (matcher.find()) { value = matcher.group(1); if (value.indexOf(ESCAPED_QUOTE) != -1) { value = value.replace(ESCAPED_QUOTE, "\""); } } } return value; } @Inject ETagFromHttpResponseViaRegex(ReturnStringIf2xx returnStringIf200); @Override String apply(HttpResponse response); } |
@Test public void testCreatePayload() { CreateNicRequestBinder binder = new CreateNicRequestBinder(); Nic.Request.CreatePayload payload = Nic.Request.creatingBuilder() .ip("192.168.0.1") .name("nic-name") .dhcpActive(true) .serverId("server-id") .lanId(1) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Nic.Request.CreatePayload payload) { requestBuilder.append("<ws:createNic>") .append("<request>") .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:createNic>"); return requestBuilder.toString(); } | CreateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.CreatePayload> { @Override protected String createPayload(Nic.Request.CreatePayload payload) { requestBuilder.append("<ws:createNic>") .append("<request>") .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:createNic>"); return requestBuilder.toString(); } } | CreateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.CreatePayload> { @Override protected String createPayload(Nic.Request.CreatePayload payload) { requestBuilder.append("<ws:createNic>") .append("<request>") .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:createNic>"); return requestBuilder.toString(); } CreateNicRequestBinder(); } | CreateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.CreatePayload> { @Override protected String createPayload(Nic.Request.CreatePayload payload) { requestBuilder.append("<ws:createNic>") .append("<request>") .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:createNic>"); return requestBuilder.toString(); } CreateNicRequestBinder(); } | CreateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.CreatePayload> { @Override protected String createPayload(Nic.Request.CreatePayload payload) { requestBuilder.append("<ws:createNic>") .append("<request>") .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:createNic>"); return requestBuilder.toString(); } CreateNicRequestBinder(); } |
@SuppressWarnings("unchecked") @Test public void testInvalidate() throws Exception { LoadingCache<String, Optional<String>> bucketToRegionCache = createMock(LoadingCache.class); bucketToRegionCache.invalidate("mybucket"); replay(bucketToRegionCache); AssignCorrectHostnameForBucket delegate = new AssignCorrectHostnameForBucket(REGION_TO_ENDPOINT, Functions.forMap(ImmutableMap.of("mybucket", Optional.of("us-west-1")))); new DefaultEndpointThenInvalidateRegion(delegate, bucketToRegionCache).apply("mybucket"); verify(bucketToRegionCache); } | @Override public URI apply(@Nullable Object from) { try { return delegate.apply(from); } finally { bucketToRegionCache.invalidate(from.toString()); } } | DefaultEndpointThenInvalidateRegion implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { try { return delegate.apply(from); } finally { bucketToRegionCache.invalidate(from.toString()); } } } | DefaultEndpointThenInvalidateRegion implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { try { return delegate.apply(from); } finally { bucketToRegionCache.invalidate(from.toString()); } } @Inject DefaultEndpointThenInvalidateRegion(AssignCorrectHostnameForBucket delegate,
@Bucket LoadingCache<String, Optional<String>> bucketToRegionCache); } | DefaultEndpointThenInvalidateRegion implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { try { return delegate.apply(from); } finally { bucketToRegionCache.invalidate(from.toString()); } } @Inject DefaultEndpointThenInvalidateRegion(AssignCorrectHostnameForBucket delegate,
@Bucket LoadingCache<String, Optional<String>> bucketToRegionCache); @Override URI apply(@Nullable Object from); } | DefaultEndpointThenInvalidateRegion implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { try { return delegate.apply(from); } finally { bucketToRegionCache.invalidate(from.toString()); } } @Inject DefaultEndpointThenInvalidateRegion(AssignCorrectHostnameForBucket delegate,
@Bucket LoadingCache<String, Optional<String>> bucketToRegionCache); @Override URI apply(@Nullable Object from); } |
@Test(threadPoolSize = 3, dataProvider = "dataProvider", timeOut = 10000) void testIdempotent(HttpRequest request) { request = filter.filter(request); String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION); String date = request.getFirstHeaderOrNull(HttpHeaders.DATE); int iterations = 1; while (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) { date = request.getFirstHeaderOrNull(HttpHeaders.DATE); request = filter.filter(request); if (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) assert signature.equals(request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION)) : String.format( "sig: %s != %s on attempt %s", signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION), iterations); else iterations++; } System.out.printf("%s: %d iterations before the timestamp updated %n", Thread.currentThread().getName(), iterations); } | public HttpRequest filter(HttpRequest request) throws HttpException { request = replaceDateHeader(request); Credentials current = creds.get(); if (current instanceof SessionCredentials) { request = replaceSecurityTokenHeader(request, SessionCredentials.class.cast(current)); } String signature = calculateSignature(createStringToSign(request)); request = replaceAuthorizationHeader(request, signature); utils.logRequest(signatureLog, request, "<<"); return request; } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { public HttpRequest filter(HttpRequest request) throws HttpException { request = replaceDateHeader(request); Credentials current = creds.get(); if (current instanceof SessionCredentials) { request = replaceSecurityTokenHeader(request, SessionCredentials.class.cast(current)); } String signature = calculateSignature(createStringToSign(request)); request = replaceAuthorizationHeader(request, signature); utils.logRequest(signatureLog, request, "<<"); return request; } } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { public HttpRequest filter(HttpRequest request) throws HttpException { request = replaceDateHeader(request); Credentials current = creds.get(); if (current instanceof SessionCredentials) { request = replaceSecurityTokenHeader(request, SessionCredentials.class.cast(current)); } String signature = calculateSignature(createStringToSign(request)); request = replaceAuthorizationHeader(request, signature); utils.logRequest(signatureLog, request, "<<"); return request; } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { public HttpRequest filter(HttpRequest request) throws HttpException { request = replaceDateHeader(request); Credentials current = creds.get(); if (current instanceof SessionCredentials) { request = replaceSecurityTokenHeader(request, SessionCredentials.class.cast(current)); } String signature = calculateSignature(createStringToSign(request)); request = replaceAuthorizationHeader(request, signature); utils.logRequest(signatureLog, request, "<<"); return request; } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { public HttpRequest filter(HttpRequest request) throws HttpException { request = replaceDateHeader(request); Credentials current = creds.get(); if (current instanceof SessionCredentials) { request = replaceSecurityTokenHeader(request, SessionCredentials.class.cast(current)); } String signature = calculateSignature(createStringToSign(request)); request = replaceAuthorizationHeader(request, signature); utils.logRequest(signatureLog, request, "<<"); return request; } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@Test void testAppendBucketNameHostHeader() throws SecurityException, NoSuchMethodException { GeneratedHttpRequest request = processor.createRequest( method(S3Client.class, "getBucketLocation", String.class), ImmutableList.<Object>of("bucket")); StringBuilder builder = new StringBuilder(); ((RequestAuthorizeSignatureV2) filter).appendBucketName(request, builder); assertEquals(builder.toString(), ""); } | @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@Test void testAclQueryString() throws SecurityException, NoSuchMethodException { HttpRequest request = putBucketAcl(); StringBuilder builder = new StringBuilder(); ((RequestAuthorizeSignatureV2) filter).appendUriPath(request, builder); assertEquals(builder.toString(), "/" + bucketName + "?acl"); } | @VisibleForTesting void appendUriPath(HttpRequest request, StringBuilder toSign) { toSign.append(request.getEndpoint().getRawPath()); if (request.getEndpoint().getQuery() != null) { Multimap<String, String> params = queryParser().apply(request.getEndpoint().getQuery()); char separator = '?'; for (String paramName : Ordering.natural().sortedCopy(params.keySet())) { if (!SIGNED_PARAMETERS.contains(paramName)) { continue; } toSign.append(separator).append(paramName); String paramValue = get(params.get(paramName), 0); if (paramValue != null) { toSign.append("=").append(paramValue); } separator = '&'; } } } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendUriPath(HttpRequest request, StringBuilder toSign) { toSign.append(request.getEndpoint().getRawPath()); if (request.getEndpoint().getQuery() != null) { Multimap<String, String> params = queryParser().apply(request.getEndpoint().getQuery()); char separator = '?'; for (String paramName : Ordering.natural().sortedCopy(params.keySet())) { if (!SIGNED_PARAMETERS.contains(paramName)) { continue; } toSign.append(separator).append(paramName); String paramValue = get(params.get(paramName), 0); if (paramValue != null) { toSign.append("=").append(paramValue); } separator = '&'; } } } } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendUriPath(HttpRequest request, StringBuilder toSign) { toSign.append(request.getEndpoint().getRawPath()); if (request.getEndpoint().getQuery() != null) { Multimap<String, String> params = queryParser().apply(request.getEndpoint().getQuery()); char separator = '?'; for (String paramName : Ordering.natural().sortedCopy(params.keySet())) { if (!SIGNED_PARAMETERS.contains(paramName)) { continue; } toSign.append(separator).append(paramName); String paramValue = get(params.get(paramName), 0); if (paramValue != null) { toSign.append("=").append(paramValue); } separator = '&'; } } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendUriPath(HttpRequest request, StringBuilder toSign) { toSign.append(request.getEndpoint().getRawPath()); if (request.getEndpoint().getQuery() != null) { Multimap<String, String> params = queryParser().apply(request.getEndpoint().getQuery()); char separator = '?'; for (String paramName : Ordering.natural().sortedCopy(params.keySet())) { if (!SIGNED_PARAMETERS.contains(paramName)) { continue; } toSign.append(separator).append(paramName); String paramValue = get(params.get(paramName), 0); if (paramValue != null) { toSign.append("=").append(paramValue); } separator = '&'; } } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendUriPath(HttpRequest request, StringBuilder toSign) { toSign.append(request.getEndpoint().getRawPath()); if (request.getEndpoint().getQuery() != null) { Multimap<String, String> params = queryParser().apply(request.getEndpoint().getQuery()); char separator = '?'; for (String paramName : Ordering.natural().sortedCopy(params.keySet())) { if (!SIGNED_PARAMETERS.contains(paramName)) { continue; } toSign.append(separator).append(paramName); String paramValue = get(params.get(paramName), 0); if (paramValue != null) { toSign.append("=").append(paramValue); } separator = '&'; } } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@Test void testAppendBucketNameHostHeaderService() throws SecurityException, NoSuchMethodException { HttpRequest request = listOwnedBuckets(); StringBuilder builder = new StringBuilder(); ((RequestAuthorizeSignatureV2) filter).appendBucketName(request, builder); assertEquals(builder.toString(), ""); } | @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner { @VisibleForTesting void appendBucketName(HttpRequest req, StringBuilder toSign) { String bucketName = S3Utils.getBucketName(req); if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) { toSign.append(servicePath).append(bucketName); } } @Inject RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,
@Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,
@Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,
@org.jclouds.location.Provider Supplier<Credentials> creds,
@TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,
DateService dateService); HttpRequest filter(HttpRequest request); String createStringToSign(HttpRequest request); String sign(String toSign); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@Test public void testParseRegion() { Assert.assertEquals( AwsHostNameUtils.parseRegionName("test.s3.cn-north-1.amazonaws.com.cn", "s3"), "cn-north-1" ); } | public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } | AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } } | AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } } | AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } static String parseRegionName(final String host, final String serviceHint); static String parseServiceName(URI endpoint); } | AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } static String parseRegionName(final String host, final String serviceHint); static String parseServiceName(URI endpoint); } |
@Test public void testParseDefaultRegion() { Assert.assertEquals( AwsHostNameUtils.parseRegionName("s3.amazonaws.com", "s3"), "us-east-1" ); } | public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } | AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } } | AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } } | AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } static String parseRegionName(final String host, final String serviceHint); static String parseServiceName(URI endpoint); } | AwsHostNameUtils { public static String parseRegionName(final String host, final String serviceHint) { String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return "us-east-1"; } static String parseRegionName(final String host, final String serviceHint); static String parseServiceName(URI endpoint); } |
@Test public void testParseService() { Assert.assertEquals( AwsHostNameUtils.parseServiceName(URI.create("https: "s3" ); Assert.assertEquals( AwsHostNameUtils.parseServiceName(URI.create("https: "s3" ); } | public static String parseServiceName(URI endpoint) { String host = endpoint.getHost(); if (!host.endsWith(".amazonaws.com") && !host.endsWith(".amazonaws.com.cn")) { return "s3"; } String serviceAndRegion = host.substring(0, host.indexOf(".amazonaws.com")); if (serviceAndRegion.endsWith(".s3") || S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) { return "s3"; } char separator = '.'; if (serviceAndRegion.indexOf(separator) == -1) { return serviceAndRegion; } return serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator)); } | AwsHostNameUtils { public static String parseServiceName(URI endpoint) { String host = endpoint.getHost(); if (!host.endsWith(".amazonaws.com") && !host.endsWith(".amazonaws.com.cn")) { return "s3"; } String serviceAndRegion = host.substring(0, host.indexOf(".amazonaws.com")); if (serviceAndRegion.endsWith(".s3") || S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) { return "s3"; } char separator = '.'; if (serviceAndRegion.indexOf(separator) == -1) { return serviceAndRegion; } return serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator)); } } | AwsHostNameUtils { public static String parseServiceName(URI endpoint) { String host = endpoint.getHost(); if (!host.endsWith(".amazonaws.com") && !host.endsWith(".amazonaws.com.cn")) { return "s3"; } String serviceAndRegion = host.substring(0, host.indexOf(".amazonaws.com")); if (serviceAndRegion.endsWith(".s3") || S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) { return "s3"; } char separator = '.'; if (serviceAndRegion.indexOf(separator) == -1) { return serviceAndRegion; } return serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator)); } } | AwsHostNameUtils { public static String parseServiceName(URI endpoint) { String host = endpoint.getHost(); if (!host.endsWith(".amazonaws.com") && !host.endsWith(".amazonaws.com.cn")) { return "s3"; } String serviceAndRegion = host.substring(0, host.indexOf(".amazonaws.com")); if (serviceAndRegion.endsWith(".s3") || S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) { return "s3"; } char separator = '.'; if (serviceAndRegion.indexOf(separator) == -1) { return serviceAndRegion; } return serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator)); } static String parseRegionName(final String host, final String serviceHint); static String parseServiceName(URI endpoint); } | AwsHostNameUtils { public static String parseServiceName(URI endpoint) { String host = endpoint.getHost(); if (!host.endsWith(".amazonaws.com") && !host.endsWith(".amazonaws.com.cn")) { return "s3"; } String serviceAndRegion = host.substring(0, host.indexOf(".amazonaws.com")); if (serviceAndRegion.endsWith(".s3") || S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) { return "s3"; } char separator = '.'; if (serviceAndRegion.indexOf(separator) == -1) { return serviceAndRegion; } return serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator)); } static String parseRegionName(final String host, final String serviceHint); static String parseServiceName(URI endpoint); } |
@Test public void testCreatePayload() { SetInternetAccessBinder binder = new SetInternetAccessBinder(); Nic.Request.SetInternetAccessPayload payload = Nic.Request.setInternetAccessBuilder() .dataCenterId("datacenter-id") .internetAccess(true) .lanId(1) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Nic.Request.SetInternetAccessPayload payload) { requestBuilder.append("<ws:setInternetAccess>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append(format("<internetAccess>%s</internetAccess>", payload.internetAccess())) .append("</ws:setInternetAccess>"); return requestBuilder.toString(); } | SetInternetAccessBinder extends BaseProfitBricksRequestBinder<Nic.Request.SetInternetAccessPayload> { @Override protected String createPayload(Nic.Request.SetInternetAccessPayload payload) { requestBuilder.append("<ws:setInternetAccess>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append(format("<internetAccess>%s</internetAccess>", payload.internetAccess())) .append("</ws:setInternetAccess>"); return requestBuilder.toString(); } } | SetInternetAccessBinder extends BaseProfitBricksRequestBinder<Nic.Request.SetInternetAccessPayload> { @Override protected String createPayload(Nic.Request.SetInternetAccessPayload payload) { requestBuilder.append("<ws:setInternetAccess>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append(format("<internetAccess>%s</internetAccess>", payload.internetAccess())) .append("</ws:setInternetAccess>"); return requestBuilder.toString(); } SetInternetAccessBinder(); } | SetInternetAccessBinder extends BaseProfitBricksRequestBinder<Nic.Request.SetInternetAccessPayload> { @Override protected String createPayload(Nic.Request.SetInternetAccessPayload payload) { requestBuilder.append("<ws:setInternetAccess>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append(format("<internetAccess>%s</internetAccess>", payload.internetAccess())) .append("</ws:setInternetAccess>"); return requestBuilder.toString(); } SetInternetAccessBinder(); } | SetInternetAccessBinder extends BaseProfitBricksRequestBinder<Nic.Request.SetInternetAccessPayload> { @Override protected String createPayload(Nic.Request.SetInternetAccessPayload payload) { requestBuilder.append("<ws:setInternetAccess>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append(format("<internetAccess>%s</internetAccess>", payload.internetAccess())) .append("</ws:setInternetAccess>"); return requestBuilder.toString(); } SetInternetAccessBinder(); } |
@Test void testGetBucketLocationSignature() { Invocation invocation = Invocation.create(method(S3Client.class, "getBucketLocation", String.class), ImmutableList.<Object>of(BUCKET_NAME)); HttpRequest getBucketLocation = GeneratedHttpRequest.builder().method("GET") .invocation(invocation) .endpoint("https: .addHeader(HttpHeaders.HOST, BUCKET_NAME + ".s3.cn-north-1.amazonaws.com.cn") .addQueryParam("location", "") .build(); HttpRequest filtered = filter(temporaryCredentials).filter(getBucketLocation); assertEquals(filtered.getFirstHeaderOrNull("Authorization"), GET_BUCKET_LOCATION_SIGNATURE_RESULT); } | @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@Test void testGetObjectSignature() { Invocation invocation = Invocation.create(method(S3Client.class, "getObject", String.class, String.class, GetOptions[].class), ImmutableList.<Object>of(BUCKET_NAME, OBJECT_NAME, new GetOptions[0])); HttpRequest getObject = GeneratedHttpRequest.builder().method("GET") .invocation(invocation) .endpoint("https: .addHeader(HttpHeaders.HOST, BUCKET_NAME + ".s3.cn-north-1.amazonaws.com.cn") .build(); HttpRequest filtered = filter(temporaryCredentials).filter(getObject); assertEquals(filtered.getFirstHeaderOrNull("Authorization"), GET_OBJECT_RESULT); } | @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@Test void testGetObjectACLSignature() { Invocation invocation = Invocation.create(method(S3Client.class, "getObjectACL", String.class, String.class), ImmutableList.<Object>of(BUCKET_NAME)); HttpRequest getObjectACL = GeneratedHttpRequest.builder().method("GET") .invocation(invocation) .endpoint("https: .addHeader(HttpHeaders.HOST, BUCKET_NAME + ".s3.cn-north-1.amazonaws.com.cn") .addQueryParam("acl", "") .build(); HttpRequest filtered = filter(temporaryCredentials).filter(getObjectACL); assertEquals(filtered.getFirstHeaderOrNull("Authorization"), GET_OBJECT_ACL_RESULT); } | @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@Test void testPutObjectSignature() { Invocation invocation = Invocation.create(method(S3Client.class, "putObject", String.class, S3Object.class, PutObjectOptions[].class), ImmutableList.<Object>of(BUCKET_NAME)); Payload payload = Payloads.newStringPayload(PUT_OBJECT_CONTENT); payload.getContentMetadata().setContentType("text/plain"); HttpRequest putObject = GeneratedHttpRequest.builder().method("PUT") .invocation(invocation) .endpoint("https: .addHeader(HttpHeaders.HOST, BUCKET_NAME + ".s3.cn-north-1.amazonaws.com.cn") .addHeader("x-amz-storage-class", "REDUCED_REDUNDANCY") .payload(payload) .build(); HttpRequest filtered = filter(temporaryCredentials).filter(putObject); assertEquals(filtered.getFirstHeaderOrNull("Authorization"), PUT_OBJECT_RESULT); } | @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@Test void testListBucketFunnyCharactersSignature() { Invocation invocation = Invocation.create(method(S3Client.class, "listBucket", String.class, ListBucketOptions[].class), ImmutableList.<Object>of(BUCKET_NAME, new ListBucketOptions[0])); HttpRequest getObject = GeneratedHttpRequest.builder().method("GET") .invocation(invocation) .endpoint("https: .addHeader(HttpHeaders.HOST, BUCKET_NAME + ".s3.cn-north-1.amazonaws.com.cn") .build(); HttpRequest filtered = filter(temporaryCredentials).filter(getObject); assertEquals(filtered.getFirstHeaderOrNull("Authorization"), LIST_BUCKET_RESULT); } | @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } | RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature { @Override public HttpRequest filter(HttpRequest request) throws HttpException { if (useChunkedUpload(request)) { return signForChunkedUpload(request); } return signForAuthorizationHeader(request); } @Inject RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,
Aws4SignerForChunkedUpload signerForChunkedUpload,
Aws4SignerForQueryString signerForQueryString); @Override HttpRequest filter(HttpRequest request); @Override HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds); } |
@SuppressWarnings("unchecked") @Test public void test401ShouldRetryAndFailAfterFiveAttempts() { HttpCommand command = createMock(HttpCommand.class); SessionApi sessionClient = createMock(SessionApi.class); LoadingCache<Credentials, LoginResponse> cache = createMock(LoadingCache.class); cache.invalidateAll(); expectLastCall().anyTimes(); final AtomicInteger counter = new AtomicInteger(); expect(command.incrementFailureCount()).andAnswer(new IAnswer<Integer>() { @Override public Integer answer() throws Throwable { return counter.incrementAndGet(); } }).anyTimes(); expect(command.isReplayable()).andReturn(true).anyTimes(); expect(command.getFailureCount()).andAnswer(new IAnswer<Integer>() { @Override public Integer answer() throws Throwable { return counter.get(); } }).anyTimes(); replay(cache, command); HttpResponse response = HttpResponse.builder().payload( Payloads.newStringPayload("Not relevant")).statusCode(401).build(); InvalidateSessionAndRetryOn401AndLogoutOnClose retry = new InvalidateSessionAndRetryOn401AndLogoutOnClose(cache, sessionClient); for (int i = 0; i < 5; i++) { assertTrue(retry.shouldRetryRequest(command, response)); } assertFalse(retry.shouldRetryRequest(command, response)); verify(cache, command); } | @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { try { switch (response.getStatusCode()) { case 401: authenticationResponseCache.invalidateAll(); return super.shouldRetryRequest(command, response); } return false; } finally { releasePayload(response); } } | InvalidateSessionAndRetryOn401AndLogoutOnClose extends BackoffLimitedRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { try { switch (response.getStatusCode()) { case 401: authenticationResponseCache.invalidateAll(); return super.shouldRetryRequest(command, response); } return false; } finally { releasePayload(response); } } } | InvalidateSessionAndRetryOn401AndLogoutOnClose extends BackoffLimitedRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { try { switch (response.getStatusCode()) { case 401: authenticationResponseCache.invalidateAll(); return super.shouldRetryRequest(command, response); } return false; } finally { releasePayload(response); } } @Inject protected InvalidateSessionAndRetryOn401AndLogoutOnClose(LoadingCache<Credentials, LoginResponse> authenticationResponseCache,
SessionApi sessionClient); } | InvalidateSessionAndRetryOn401AndLogoutOnClose extends BackoffLimitedRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { try { switch (response.getStatusCode()) { case 401: authenticationResponseCache.invalidateAll(); return super.shouldRetryRequest(command, response); } return false; } finally { releasePayload(response); } } @Inject protected InvalidateSessionAndRetryOn401AndLogoutOnClose(LoadingCache<Credentials, LoginResponse> authenticationResponseCache,
SessionApi sessionClient); @Override boolean shouldRetryRequest(HttpCommand command, HttpResponse response); @PreDestroy void logoutOnClose(); } | InvalidateSessionAndRetryOn401AndLogoutOnClose extends BackoffLimitedRetryHandler { @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { try { switch (response.getStatusCode()) { case 401: authenticationResponseCache.invalidateAll(); return super.shouldRetryRequest(command, response); } return false; } finally { releasePayload(response); } } @Inject protected InvalidateSessionAndRetryOn401AndLogoutOnClose(LoadingCache<Credentials, LoginResponse> authenticationResponseCache,
SessionApi sessionClient); @Override boolean shouldRetryRequest(HttpCommand command, HttpResponse response); @PreDestroy void logoutOnClose(); } |
@Test public void testApply() throws UnknownHostException { final CloudStackApi client = createMock(CloudStackApi.class); SecurityGroupApi secClient = createMock(SecurityGroupApi.class); ZoneApi zoneClient = createMock(ZoneApi.class); AsyncJobApi jobClient = createMock(AsyncJobApi.class); SecurityGroup group = createMock(SecurityGroup.class); Zone zone = createMock(Zone.class); expect(group.getIngressRules()).andReturn(ImmutableSet.<IngressRule> of()); expect(group.getId()).andReturn("sec-1234").anyTimes(); expect(zone.isSecurityGroupsEnabled()).andReturn(true); expect(client.getSecurityGroupApi()).andReturn(secClient) .anyTimes(); expect(client.getZoneApi()).andReturn(zoneClient); expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes(); expect(zoneClient.getZone("zone-abc1")).andReturn(zone); expect(secClient.createSecurityGroup("group-1")).andReturn(group); expect(secClient.authorizeIngressPortsToCIDRs("sec-1234", "TCP", 22, 22, ImmutableSet.of("0.0.0.0/0"))).andReturn("job-1234"); replay(client, secClient, zoneClient, zone, group); ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder() .zone("zone-abc1") .name("group-1") .ports(ImmutableSet.of(22)) .cidrs(ImmutableSet.<String> of()).build(); CreateSecurityGroupIfNeeded parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(CloudStackApi.class).toInstance(client); bind(new TypeLiteral<CacheLoader<String, Zone>>() {}). to(ZoneIdToZone.class); bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}). to(ZoneIdToZoneSupplier.class); bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance("60"); } @Provides @Singleton protected Predicate<String> jobComplete(JobComplete jobComplete) { return retry(jobComplete, 1200, 1, 5, SECONDS); } }).getInstance(CreateSecurityGroupIfNeeded.class); assertEquals(parser.apply(input), group); verify(client, secClient, zoneClient, zone, group); } | @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); @Override SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input); } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); @Override SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input); } |
@Test public void testApplyGroupAlreadyExists() throws UnknownHostException { final CloudStackApi client = createMock(CloudStackApi.class); SecurityGroupApi secClient = createMock(SecurityGroupApi.class); ZoneApi zoneClient = createMock(ZoneApi.class); AsyncJobApi jobClient = createMock(AsyncJobApi.class); SecurityGroup group = createMock(SecurityGroup.class); Zone zone = createMock(Zone.class); expect(group.getId()).andReturn("sec-1234").anyTimes(); expect(zone.isSecurityGroupsEnabled()).andReturn(true); expect(client.getSecurityGroupApi()).andReturn(secClient) .anyTimes(); expect(client.getZoneApi()).andReturn(zoneClient); expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes(); expect(zoneClient.getZone("zone-abc2")).andReturn(zone); expect(secClient.createSecurityGroup("group-1")).andThrow(new IllegalStateException()); expect(secClient.getSecurityGroupByName("group-1")).andReturn(group); replay(client, secClient, zoneClient, zone, group); ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder() .zone("zone-abc2") .name("group-1") .ports(ImmutableSet.of(22)) .cidrs(ImmutableSet.<String> of()).build(); CreateSecurityGroupIfNeeded parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(CloudStackApi.class).toInstance(client); bind(new TypeLiteral<CacheLoader<String, Zone>>() {}). to(ZoneIdToZone.class); bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}). to(ZoneIdToZoneSupplier.class); bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance("60"); } @Provides @Singleton protected Predicate<String> jobComplete(JobComplete jobComplete) { return retry(jobComplete, 1200, 1, 5, SECONDS); } }).getInstance(CreateSecurityGroupIfNeeded.class); assertEquals(parser.apply(input), group); verify(client, secClient, zoneClient, zone, group); } | @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); @Override SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input); } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); @Override SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input); } |
@Test public void testCreatePayload() { UpdateNicRequestBinder binder = new UpdateNicRequestBinder(); Nic.Request.UpdatePayload payload = Nic.Request.updatingBuilder() .id("nic-id") .ip("192.168.0.1") .name("nic-name") .dhcpActive(true) .lanId(1) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Nic.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateNic>") .append("<request>") .append(format("<nicId>%s</nicId>", payload.id())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:updateNic>"); return requestBuilder.toString(); } | UpdateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.UpdatePayload> { @Override protected String createPayload(Nic.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateNic>") .append("<request>") .append(format("<nicId>%s</nicId>", payload.id())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:updateNic>"); return requestBuilder.toString(); } } | UpdateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.UpdatePayload> { @Override protected String createPayload(Nic.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateNic>") .append("<request>") .append(format("<nicId>%s</nicId>", payload.id())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:updateNic>"); return requestBuilder.toString(); } UpdateNicRequestBinder(); } | UpdateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.UpdatePayload> { @Override protected String createPayload(Nic.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateNic>") .append("<request>") .append(format("<nicId>%s</nicId>", payload.id())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:updateNic>"); return requestBuilder.toString(); } UpdateNicRequestBinder(); } | UpdateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.UpdatePayload> { @Override protected String createPayload(Nic.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateNic>") .append("<request>") .append(format("<nicId>%s</nicId>", payload.id())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:updateNic>"); return requestBuilder.toString(); } UpdateNicRequestBinder(); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testApplyZoneNoSecurityGroups() throws UnknownHostException { final CloudStackApi client = createMock(CloudStackApi.class); SecurityGroupApi secClient = createMock(SecurityGroupApi.class); ZoneApi zoneClient = createMock(ZoneApi.class); AsyncJobApi jobClient = createMock(AsyncJobApi.class); SecurityGroup group = createMock(SecurityGroup.class); Zone zone = createMock(Zone.class); expect(zone.isSecurityGroupsEnabled()).andReturn(false); expect(client.getZoneApi()).andReturn(zoneClient); expect(zoneClient.getZone("zone-abc3")).andReturn(zone); replay(client, zoneClient, zone); ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder() .zone("zone-abc3") .name("group-1") .ports(ImmutableSet.of(22)) .cidrs(ImmutableSet.<String> of()).build(); CreateSecurityGroupIfNeeded parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(CloudStackApi.class).toInstance(client); bind(new TypeLiteral<CacheLoader<String, Zone>>() {}). to(ZoneIdToZone.class); bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}). to(ZoneIdToZoneSupplier.class); bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance("60"); } @Provides @Singleton protected Predicate<String> jobComplete(JobComplete jobComplete) { return retry(jobComplete, 1200, 1, 5, SECONDS); } }).getInstance(CreateSecurityGroupIfNeeded.class); assertEquals(parser.apply(input), group); verify(client, zoneClient, zone); } | @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); @Override SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input); } | CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> { @Override public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) { checkNotNull(input, "input"); String zoneId = input.getZone(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); checkArgument(supportsSecurityGroups().apply(zone), "Security groups are required, but the zone %s does not support security groups", zoneId); logger.debug(">> creating securityGroup %s", input); try { SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); ImmutableSet<String> cidrs; if (!input.getCidrs().isEmpty()) { cidrs = ImmutableSet.copyOf(input.getCidrs()); } else { cidrs = ImmutableSet.of("0.0.0.0/0"); } for (int port : input.getPorts()) { authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs); } return securityGroup; } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", input, e.getMessage()); SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName()); logger.debug("<< reused securityGroup(%s)", group.getId()); return group; } } @Inject CreateSecurityGroupIfNeeded(CloudStackApi client,
Predicate<String> jobComplete,
Supplier<LoadingCache<String, Zone>> zoneIdToZone); @Override SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input); } |
@Test public void testApply() throws Exception { WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto()); LoginCredentials credentials = f.apply(new EncryptedPasswordAndPrivateKey(ENCRYPTED_PASSWORD, PRIVATE_KEY)); assertEquals(credentials.getUser(), "Administrator"); assertEquals(credentials.getOptionalPassword().get(), "u4.y9mb;nR."); assertFalse(credentials.getOptionalPrivateKey().isPresent()); } | @Override public LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey) { if (dataAndKey == null) return null; try { KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey()); KeyFactory kf = crypto.rsaKeyFactory(); PrivateKey privKey = kf.generatePrivate(keySpec); Cipher cipher = crypto.cipher("RSA"); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] cipherText = base64().decode(whitespace.matcher(dataAndKey.getEncryptedPassword()).replaceAll("")); byte[] plainText = cipher.doFinal(cipherText); String password = new String(plainText, UTF_8); return LoginCredentials.builder() .user("Administrator") .password(password) .noPrivateKey() .build(); } catch (Exception e) { throw Throwables.propagate(e); } } | WindowsLoginCredentialsFromEncryptedData implements Function<EncryptedPasswordAndPrivateKey, LoginCredentials> { @Override public LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey) { if (dataAndKey == null) return null; try { KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey()); KeyFactory kf = crypto.rsaKeyFactory(); PrivateKey privKey = kf.generatePrivate(keySpec); Cipher cipher = crypto.cipher("RSA"); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] cipherText = base64().decode(whitespace.matcher(dataAndKey.getEncryptedPassword()).replaceAll("")); byte[] plainText = cipher.doFinal(cipherText); String password = new String(plainText, UTF_8); return LoginCredentials.builder() .user("Administrator") .password(password) .noPrivateKey() .build(); } catch (Exception e) { throw Throwables.propagate(e); } } } | WindowsLoginCredentialsFromEncryptedData implements Function<EncryptedPasswordAndPrivateKey, LoginCredentials> { @Override public LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey) { if (dataAndKey == null) return null; try { KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey()); KeyFactory kf = crypto.rsaKeyFactory(); PrivateKey privKey = kf.generatePrivate(keySpec); Cipher cipher = crypto.cipher("RSA"); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] cipherText = base64().decode(whitespace.matcher(dataAndKey.getEncryptedPassword()).replaceAll("")); byte[] plainText = cipher.doFinal(cipherText); String password = new String(plainText, UTF_8); return LoginCredentials.builder() .user("Administrator") .password(password) .noPrivateKey() .build(); } catch (Exception e) { throw Throwables.propagate(e); } } @Inject WindowsLoginCredentialsFromEncryptedData(Crypto crypto); } | WindowsLoginCredentialsFromEncryptedData implements Function<EncryptedPasswordAndPrivateKey, LoginCredentials> { @Override public LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey) { if (dataAndKey == null) return null; try { KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey()); KeyFactory kf = crypto.rsaKeyFactory(); PrivateKey privKey = kf.generatePrivate(keySpec); Cipher cipher = crypto.cipher("RSA"); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] cipherText = base64().decode(whitespace.matcher(dataAndKey.getEncryptedPassword()).replaceAll("")); byte[] plainText = cipher.doFinal(cipherText); String password = new String(plainText, UTF_8); return LoginCredentials.builder() .user("Administrator") .password(password) .noPrivateKey() .build(); } catch (Exception e) { throw Throwables.propagate(e); } } @Inject WindowsLoginCredentialsFromEncryptedData(Crypto crypto); @Override LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey); } | WindowsLoginCredentialsFromEncryptedData implements Function<EncryptedPasswordAndPrivateKey, LoginCredentials> { @Override public LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey) { if (dataAndKey == null) return null; try { KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey()); KeyFactory kf = crypto.rsaKeyFactory(); PrivateKey privKey = kf.generatePrivate(keySpec); Cipher cipher = crypto.cipher("RSA"); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] cipherText = base64().decode(whitespace.matcher(dataAndKey.getEncryptedPassword()).replaceAll("")); byte[] plainText = cipher.doFinal(cipherText); String password = new String(plainText, UTF_8); return LoginCredentials.builder() .user("Administrator") .password(password) .noPrivateKey() .build(); } catch (Exception e) { throw Throwables.propagate(e); } } @Inject WindowsLoginCredentialsFromEncryptedData(Crypto crypto); @Override LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey); } |
@Test public void testIsDestroyed() { VirtualMachine virtualMachine = VirtualMachine.builder(). id("229").state(VirtualMachine.State.DESTROYED).build(); expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine); replay(client, virtualMachineClient); assertTrue(new VirtualMachineDestroyed(client).apply(virtualMachine)); verify(client, virtualMachineClient); } | public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } | VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } } | VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } @Inject VirtualMachineDestroyed(CloudStackApi client); } | VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } @Inject VirtualMachineDestroyed(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); } | VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } @Inject VirtualMachineDestroyed(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); } |
@Test public void testStillRunning() { VirtualMachine virtualMachine = VirtualMachine.builder(). id("229").state(VirtualMachine.State.RUNNING).build(); expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine); replay(client, virtualMachineClient); assertFalse(new VirtualMachineDestroyed(client).apply(virtualMachine)); verify(client, virtualMachineClient); } | public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } | VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } } | VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } @Inject VirtualMachineDestroyed(CloudStackApi client); } | VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } @Inject VirtualMachineDestroyed(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); } | VirtualMachineDestroyed implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); virtualMachine = refresh(virtualMachine); if (virtualMachine == null) return true; logger.trace("%s: looking for virtualMachine state %s: currently: %s", virtualMachine.getId(), State.DESTROYED, virtualMachine.getState()); return virtualMachine.getState() == State.DESTROYED; } @Inject VirtualMachineDestroyed(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); } |
@Test public void testWaitForVirtualMachineToBeExpunged() { VirtualMachine virtualMachine = VirtualMachine.builder().id("229").build(); expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(null); replay(client, virtualMachineClient); assertTrue(new VirtualMachineExpunged(client).apply(virtualMachine)); verify(client, virtualMachineClient); } | public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } | VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } } | VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } @Inject VirtualMachineExpunged(CloudStackApi client); } | VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } @Inject VirtualMachineExpunged(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); } | VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } @Inject VirtualMachineExpunged(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); } |
@Test public void testNoRemovedYet() { VirtualMachine virtualMachine = VirtualMachine.builder().id("229").build(); expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine); replay(client, virtualMachineClient); assertFalse(new VirtualMachineExpunged(client).apply(virtualMachine)); verify(client, virtualMachineClient); } | public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } | VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } } | VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } @Inject VirtualMachineExpunged(CloudStackApi client); } | VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } @Inject VirtualMachineExpunged(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); } | VirtualMachineExpunged implements Predicate<VirtualMachine> { public boolean apply(VirtualMachine virtualMachine) { logger.trace("looking for state on virtualMachine %s", checkNotNull(virtualMachine, "virtualMachine")); return refresh(virtualMachine) == null; } @Inject VirtualMachineExpunged(CloudStackApi client); boolean apply(VirtualMachine virtualMachine); } |
@Test public void testJobComplete() { AsyncJob<?> job = AsyncJob.builder().id("100") .status(Status.SUCCEEDED).resultCode(ResultCode.SUCCESS).build(); expect((Object) asyncJobClient.getAsyncJob(job.getId())).andReturn(job); replay(client, asyncJobClient); assertTrue(new JobComplete(client).apply(job.getId())); verify(client, asyncJobClient); } | @Inject public JobComplete(CloudStackApi client) { this.client = client; } | JobComplete implements Predicate<String> { @Inject public JobComplete(CloudStackApi client) { this.client = client; } } | JobComplete implements Predicate<String> { @Inject public JobComplete(CloudStackApi client) { this.client = client; } @Inject JobComplete(CloudStackApi client); } | JobComplete implements Predicate<String> { @Inject public JobComplete(CloudStackApi client) { this.client = client; } @Inject JobComplete(CloudStackApi client); boolean apply(String jobId); } | JobComplete implements Predicate<String> { @Inject public JobComplete(CloudStackApi client) { this.client = client; } @Inject JobComplete(CloudStackApi client); boolean apply(String jobId); } |
@Test public void testFailedJobComplete() { AsyncJob<?> job = AsyncJob.builder().id("100") .status(Status.FAILED).resultCode(ResultCode.FAIL) .error(AsyncJobError.builder().errorCode(ErrorCode.INTERNAL_ERROR).errorText("Dummy test error").build()).build(); expect((Object) asyncJobClient.getAsyncJob(job.getId())).andReturn(job); replay(client, asyncJobClient); try { new JobComplete(client).apply(job.getId()); fail("No exception thrown"); } catch (AsyncJobException e) { assertTrue(e.toString().contains("Dummy test error")); } verify(client, asyncJobClient); } | public boolean apply(String jobId) { logger.trace(">> looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) { return false; } logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); if (job.hasFailed()) { throw new AsyncJobException(String.format("job %s failed with exception %s", job.toString(), job.getError().toString())); } return job.hasSucceed(); } | JobComplete implements Predicate<String> { public boolean apply(String jobId) { logger.trace(">> looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) { return false; } logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); if (job.hasFailed()) { throw new AsyncJobException(String.format("job %s failed with exception %s", job.toString(), job.getError().toString())); } return job.hasSucceed(); } } | JobComplete implements Predicate<String> { public boolean apply(String jobId) { logger.trace(">> looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) { return false; } logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); if (job.hasFailed()) { throw new AsyncJobException(String.format("job %s failed with exception %s", job.toString(), job.getError().toString())); } return job.hasSucceed(); } @Inject JobComplete(CloudStackApi client); } | JobComplete implements Predicate<String> { public boolean apply(String jobId) { logger.trace(">> looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) { return false; } logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); if (job.hasFailed()) { throw new AsyncJobException(String.format("job %s failed with exception %s", job.toString(), job.getError().toString())); } return job.hasSucceed(); } @Inject JobComplete(CloudStackApi client); boolean apply(String jobId); } | JobComplete implements Predicate<String> { public boolean apply(String jobId) { logger.trace(">> looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) { return false; } logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); if (job.hasFailed()) { throw new AsyncJobException(String.format("job %s failed with exception %s", job.toString(), job.getError().toString())); } return job.hasSucceed(); } @Inject JobComplete(CloudStackApi client); boolean apply(String jobId); } |
@Test public void testTemplateInAcceptableCategory() { assertTrue(new OSCategoryIn(client).apply(acceptableCategories).apply( Template.builder().id("1").OSTypeId("10").build() )); verify(client, guestOSClient); } | @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } | OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } } | OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } @Inject OSCategoryIn(CloudStackApi client); OSCategoryIn(Supplier<Map<String, String>> categoriesSupplier, Supplier<Set<OSType>> osTypesSupplier); } | OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } @Inject OSCategoryIn(CloudStackApi client); OSCategoryIn(Supplier<Map<String, String>> categoriesSupplier, Supplier<Set<OSType>> osTypesSupplier); @Override Predicate<Template> apply(final Set<String> acceptableCategories); } | OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } @Inject OSCategoryIn(CloudStackApi client); OSCategoryIn(Supplier<Map<String, String>> categoriesSupplier, Supplier<Set<OSType>> osTypesSupplier); @Override Predicate<Template> apply(final Set<String> acceptableCategories); } |
@Test public void testTemplateNotInAcceptableCategory() { assertFalse(new OSCategoryIn(client).apply(acceptableCategories).apply( Template.builder().id("2").OSTypeId("30").build() )); verify(client, guestOSClient); } | @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } | OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } } | OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } @Inject OSCategoryIn(CloudStackApi client); OSCategoryIn(Supplier<Map<String, String>> categoriesSupplier, Supplier<Set<OSType>> osTypesSupplier); } | OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } @Inject OSCategoryIn(CloudStackApi client); OSCategoryIn(Supplier<Map<String, String>> categoriesSupplier, Supplier<Set<OSType>> osTypesSupplier); @Override Predicate<Template> apply(final Set<String> acceptableCategories); } | OSCategoryIn implements Function<Set<String>, Predicate<Template>> { @Override public Predicate<Template> apply(final Set<String> acceptableCategories) { final Map<String, String> categories = categoriesSupplier.get(); final Set<String> acceptableOSTypeIds = Maps.filterValues( Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() { @Override public String apply(OSType input) { return input.getId(); } }), new Function<OSType, String>() { @Override public String apply(OSType input) { return categories.get(input.getOSCategoryId()); } }), Predicates.in(acceptableCategories)).keySet(); return new Predicate<Template>() { @Override public boolean apply(Template input) { return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId()); } @Override public String toString() { return "OSCategoryIn(" + acceptableCategories + ")"; } }; } @Inject OSCategoryIn(CloudStackApi client); OSCategoryIn(Supplier<Map<String, String>> categoriesSupplier, Supplier<Set<OSType>> osTypesSupplier); @Override Predicate<Template> apply(final Set<String> acceptableCategories); } |
@Test public void testCreatePayload() { UpdateServerRequestBinder binder = new UpdateServerRequestBinder(); Server.Request.UpdatePayload payload = Server.Request.updatingBuilder() .id("qwertyui-qwer-qwer-qwer-qwertyyuiiop") .cores(8) .ram(8 * 1024) .name("apache-node") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Server.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateServer>") .append("<request>") .append(format("<serverId>%s</serverId>", payload.id())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateServer>"); return requestBuilder.toString(); } | UpdateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.UpdatePayload> { @Override protected String createPayload(Server.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateServer>") .append("<request>") .append(format("<serverId>%s</serverId>", payload.id())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateServer>"); return requestBuilder.toString(); } } | UpdateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.UpdatePayload> { @Override protected String createPayload(Server.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateServer>") .append("<request>") .append(format("<serverId>%s</serverId>", payload.id())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateServer>"); return requestBuilder.toString(); } UpdateServerRequestBinder(); } | UpdateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.UpdatePayload> { @Override protected String createPayload(Server.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateServer>") .append("<request>") .append(format("<serverId>%s</serverId>", payload.id())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateServer>"); return requestBuilder.toString(); } UpdateServerRequestBinder(); } | UpdateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.UpdatePayload> { @Override protected String createPayload(Server.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateServer>") .append("<request>") .append(format("<serverId>%s</serverId>", payload.id())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateServer>"); return requestBuilder.toString(); } UpdateServerRequestBinder(); } |
@Test public void testDefaultSecurityGroupIds() { TemplateOptions options = new CloudStackTemplateOptions(); assertEquals(options.as(CloudStackTemplateOptions.class).getSecurityGroupIds(), ImmutableSet.of()); } | public Set<String> getSecurityGroupIds() { return securityGroupIds; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public Set<String> getSecurityGroupIds() { return securityGroupIds; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public Set<String> getSecurityGroupIds() { return securityGroupIds; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public Set<String> getSecurityGroupIds() { return securityGroupIds; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public Set<String> getSecurityGroupIds() { return securityGroupIds; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testSecurityGroupIds() { TemplateOptions options = new CloudStackTemplateOptions().securityGroupIds(ImmutableSet.of("3")); assertEquals(options.as(CloudStackTemplateOptions.class).getSecurityGroupIds(), ImmutableSet.of("3")); } | public CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds) { this.securityGroupIds = ImmutableSet.copyOf(securityGroupIds); return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds) { this.securityGroupIds = ImmutableSet.copyOf(securityGroupIds); return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds) { this.securityGroupIds = ImmutableSet.copyOf(securityGroupIds); return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds) { this.securityGroupIds = ImmutableSet.copyOf(securityGroupIds); return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds) { this.securityGroupIds = ImmutableSet.copyOf(securityGroupIds); return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testGenerateSecurityGroupDefaultsFalse() { TemplateOptions options = new CloudStackTemplateOptions(); assertFalse(options.as(CloudStackTemplateOptions.class) .shouldGenerateSecurityGroup()); } | public boolean shouldGenerateSecurityGroup() { return generateSecurityGroup; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateSecurityGroup() { return generateSecurityGroup; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateSecurityGroup() { return generateSecurityGroup; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateSecurityGroup() { return generateSecurityGroup; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateSecurityGroup() { return generateSecurityGroup; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testGenerateSecurityGroup() { TemplateOptions options = new CloudStackTemplateOptions().generateSecurityGroup(true); assertTrue(options.as(CloudStackTemplateOptions.class) .shouldGenerateSecurityGroup()); } | public CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup) { this.generateSecurityGroup = generateSecurityGroup; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup) { this.generateSecurityGroup = generateSecurityGroup; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup) { this.generateSecurityGroup = generateSecurityGroup; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup) { this.generateSecurityGroup = generateSecurityGroup; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup) { this.generateSecurityGroup = generateSecurityGroup; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testNetworkId() { TemplateOptions options = new CloudStackTemplateOptions().networks("3"); assertEquals(options.as(CloudStackTemplateOptions.class).getNetworks(), ImmutableSet.of("3")); } | @Override public CloudStackTemplateOptions networks(Iterable<String> networks) { return CloudStackTemplateOptions.class.cast(super.networks(networks)); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { @Override public CloudStackTemplateOptions networks(Iterable<String> networks) { return CloudStackTemplateOptions.class.cast(super.networks(networks)); } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { @Override public CloudStackTemplateOptions networks(Iterable<String> networks) { return CloudStackTemplateOptions.class.cast(super.networks(networks)); } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { @Override public CloudStackTemplateOptions networks(Iterable<String> networks) { return CloudStackTemplateOptions.class.cast(super.networks(networks)); } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { @Override public CloudStackTemplateOptions networks(Iterable<String> networks) { return CloudStackTemplateOptions.class.cast(super.networks(networks)); } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testIpOnDefaultNetwork() { TemplateOptions options = new CloudStackTemplateOptions().ipOnDefaultNetwork("10.0.0.1"); assertEquals(options.as(CloudStackTemplateOptions.class).getIpOnDefaultNetwork(), "10.0.0.1"); } | public CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) { this.ipOnDefaultNetwork = ipOnDefaultNetwork; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) { this.ipOnDefaultNetwork = ipOnDefaultNetwork; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) { this.ipOnDefaultNetwork = ipOnDefaultNetwork; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) { this.ipOnDefaultNetwork = ipOnDefaultNetwork; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) { this.ipOnDefaultNetwork = ipOnDefaultNetwork; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testCreatePayload() { CreateServerRequestBinder binder = new CreateServerRequestBinder(); Server.Request.CreatePayload payload = Server.Request.creatingBuilder() .name("jclouds-node") .cores(4) .ram(4 * 1024) .dataCenterId("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Server.Request.CreatePayload payload) { requestBuilder.append("<ws:createServer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<internetAccess>%s</internetAccess>", payload.hasInternetAccess())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:createServer>"); return requestBuilder.toString(); } | CreateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.CreatePayload> { @Override protected String createPayload(Server.Request.CreatePayload payload) { requestBuilder.append("<ws:createServer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<internetAccess>%s</internetAccess>", payload.hasInternetAccess())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:createServer>"); return requestBuilder.toString(); } } | CreateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.CreatePayload> { @Override protected String createPayload(Server.Request.CreatePayload payload) { requestBuilder.append("<ws:createServer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<internetAccess>%s</internetAccess>", payload.hasInternetAccess())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:createServer>"); return requestBuilder.toString(); } CreateServerRequestBinder(); } | CreateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.CreatePayload> { @Override protected String createPayload(Server.Request.CreatePayload payload) { requestBuilder.append("<ws:createServer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<internetAccess>%s</internetAccess>", payload.hasInternetAccess())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:createServer>"); return requestBuilder.toString(); } CreateServerRequestBinder(); } | CreateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.CreatePayload> { @Override protected String createPayload(Server.Request.CreatePayload payload) { requestBuilder.append("<ws:createServer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<cores>%s</cores>", payload.cores())) .append(format("<ram>%s</ram>", payload.ram())) .append(formatIfNotEmpty("<serverName>%s</serverName>", payload.name())) .append(formatIfNotEmpty("<bootFromStorageId>%s</bootFromStorageId>", payload.bootFromStorageId())) .append(formatIfNotEmpty("<bootFromImageId>%s</bootFromImageId>", payload.bootFromImageId())) .append(formatIfNotEmpty("<internetAccess>%s</internetAccess>", payload.hasInternetAccess())) .append(formatIfNotEmpty("<lanId>%s</lanId>", payload.lanId())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<availabilityZone>%s</availabilityZone>", payload.availabilityZone())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:createServer>"); return requestBuilder.toString(); } CreateServerRequestBinder(); } |
@Test public void testSetupStaticNatDefaultsTrue() { TemplateOptions options = new CloudStackTemplateOptions(); assertTrue(options.as(CloudStackTemplateOptions.class) .shouldSetupStaticNat()); } | public boolean shouldSetupStaticNat() { return setupStaticNat; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldSetupStaticNat() { return setupStaticNat; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldSetupStaticNat() { return setupStaticNat; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldSetupStaticNat() { return setupStaticNat; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldSetupStaticNat() { return setupStaticNat; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testSetupStaticNat() { TemplateOptions options = new CloudStackTemplateOptions().setupStaticNat(false); assertFalse(options.as(CloudStackTemplateOptions.class) .shouldSetupStaticNat()); } | public CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat) { this.setupStaticNat = setupStaticNat; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat) { this.setupStaticNat = setupStaticNat; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat) { this.setupStaticNat = setupStaticNat; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat) { this.setupStaticNat = setupStaticNat; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat) { this.setupStaticNat = setupStaticNat; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testGenerateKeyPairDefaultsFalse() { TemplateOptions options = new CloudStackTemplateOptions(); assertFalse(options.as(CloudStackTemplateOptions.class) .shouldGenerateKeyPair()); } | public boolean shouldGenerateKeyPair() { return generateKeyPair; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateKeyPair() { return generateKeyPair; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateKeyPair() { return generateKeyPair; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateKeyPair() { return generateKeyPair; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public boolean shouldGenerateKeyPair() { return generateKeyPair; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testGenerateKeyPair() { TemplateOptions options = new CloudStackTemplateOptions().generateKeyPair(true); assertTrue(options.as(CloudStackTemplateOptions.class) .shouldGenerateKeyPair()); } | public CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair) { this.generateKeyPair = generateKeyPair; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair) { this.generateKeyPair = generateKeyPair; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair) { this.generateKeyPair = generateKeyPair; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair) { this.generateKeyPair = generateKeyPair; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair) { this.generateKeyPair = generateKeyPair; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testKeyPair() { TemplateOptions options = keyPair("test"); assertEquals(options.as(CloudStackTemplateOptions.class).getKeyPair(), "test"); } | public CloudStackTemplateOptions keyPair(String keyPair) { this.keyPair = keyPair; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions keyPair(String keyPair) { this.keyPair = keyPair; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions keyPair(String keyPair) { this.keyPair = keyPair; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions keyPair(String keyPair) { this.keyPair = keyPair; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions keyPair(String keyPair) { this.keyPair = keyPair; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testDiskOfferingId() { TemplateOptions options = diskOfferingId("test"); assertEquals(options.as(CloudStackTemplateOptions.class).getDiskOfferingId(), "test"); } | public CloudStackTemplateOptions diskOfferingId(String diskOfferingId) { this.diskOfferingId = diskOfferingId; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions diskOfferingId(String diskOfferingId) { this.diskOfferingId = diskOfferingId; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions diskOfferingId(String diskOfferingId) { this.diskOfferingId = diskOfferingId; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions diskOfferingId(String diskOfferingId) { this.diskOfferingId = diskOfferingId; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions diskOfferingId(String diskOfferingId) { this.diskOfferingId = diskOfferingId; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testDataDiskSizeDefault() { TemplateOptions options = new CloudStackTemplateOptions(); assertEquals(options.as(CloudStackTemplateOptions.class).getDataDiskSize(), 0); } | public int getDataDiskSize() { return dataDiskSize; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public int getDataDiskSize() { return dataDiskSize; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public int getDataDiskSize() { return dataDiskSize; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public int getDataDiskSize() { return dataDiskSize; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public int getDataDiskSize() { return dataDiskSize; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testDataDiskSize() { TemplateOptions options = dataDiskSize(10); assertEquals(options.as(CloudStackTemplateOptions.class).getDataDiskSize(), 10); } | public CloudStackTemplateOptions dataDiskSize(int dataDiskSize) { this.dataDiskSize = dataDiskSize; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions dataDiskSize(int dataDiskSize) { this.dataDiskSize = dataDiskSize; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions dataDiskSize(int dataDiskSize) { this.dataDiskSize = dataDiskSize; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions dataDiskSize(int dataDiskSize) { this.dataDiskSize = dataDiskSize; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions dataDiskSize(int dataDiskSize) { this.dataDiskSize = dataDiskSize; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testAccount() { TemplateOptions options = account("test"); assertEquals(options.as(CloudStackTemplateOptions.class).getAccount(), "test"); } | public CloudStackTemplateOptions account(String account) { this.account = account; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions account(String account) { this.account = account; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions account(String account) { this.account = account; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions account(String account) { this.account = account; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions account(String account) { this.account = account; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testDomainId() { TemplateOptions options = domainId("test"); assertEquals(options.as(CloudStackTemplateOptions.class).getDomainId(), "test"); } | public CloudStackTemplateOptions domainId(String domainId) { this.domainId = domainId; return this; } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions domainId(String domainId) { this.domainId = domainId; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions domainId(String domainId) { this.domainId = domainId; return this; } } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions domainId(String domainId) { this.domainId = domainId; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } | CloudStackTemplateOptions extends TemplateOptions implements Cloneable { public CloudStackTemplateOptions domainId(String domainId) { this.domainId = domainId; return this; } CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds); CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks); CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork); CloudStackTemplateOptions keyPair(String keyPair); CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat); CloudStackTemplateOptions account(String account); CloudStackTemplateOptions domainId(String domainId); CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair); CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup); CloudStackTemplateOptions diskOfferingId(String diskOfferingId); CloudStackTemplateOptions dataDiskSize(int dataDiskSize); CloudStackTemplateOptions userData(byte[] userData); CloudStackTemplateOptions userData(String userData); CloudStackTemplateOptions userData(URL userDataUrl); Set<String> getSecurityGroupIds(); Map<String, String> getIpsToNetworks(); String getIpOnDefaultNetwork(); String getKeyPair(); boolean shouldSetupStaticNat(); String getAccount(); String getDomainId(); boolean shouldGenerateKeyPair(); boolean shouldGenerateSecurityGroup(); String getDiskOfferingId(); int getDataDiskSize(); byte[] getUserData(); @Override CloudStackTemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override CloudStackTemplateOptions blockOnPort(int port, int seconds); @Override CloudStackTemplateOptions inboundPorts(int... ports); @Override CloudStackTemplateOptions authorizePublicKey(String publicKey); @Override CloudStackTemplateOptions installPrivateKey(String privateKey); @Override CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning); @Override CloudStackTemplateOptions dontAuthorizePublicKey(); @Override CloudStackTemplateOptions nameTask(String name); @Override CloudStackTemplateOptions runAsRoot(boolean runAsRoot); @Override CloudStackTemplateOptions runScript(Statement script); @Override CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override CloudStackTemplateOptions overrideLoginPassword(String password); @Override CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey); @Override CloudStackTemplateOptions overrideLoginUser(String loginUser); @Override CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); @Override CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata); @Override CloudStackTemplateOptions userMetadata(String key, String value); @Override CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames); @Override CloudStackTemplateOptions networks(Iterable<String> networks); } |
@Test public void testCreatePayload() { AddFirewallRuleToNicRequestBinder binder = new AddFirewallRuleToNicRequestBinder(); Firewall.Request.AddRulePayload payload = Firewall.Request.createAddRulePayload( "nic-id", ImmutableList.of( Firewall.Rule.builder() .name("name") .portRangeEnd(45678) .portRangeStart(12345) .protocol(Firewall.Protocol.TCP) .sourceIp("192.168.0.1") .sourceMac("aa:bb:cc:dd:ee:ff") .targetIp("192.168.0.2") .build() )); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Firewall.Request.AddRulePayload payload) { requestBuilder.append("<ws:addFirewallRulesToNic>") .append(format("<nicId>%s</nicId>", payload.nicId())); for (Firewall.Rule rule : payload.rules()) requestBuilder .append("<request>") .append(formatIfNotEmpty("<icmpCode>%s</icmpCode>", rule.icmpCode())) .append(formatIfNotEmpty("<icmpType>%s</icmpType>", rule.icmpType())) .append(formatIfNotEmpty("<name>%s</name>", rule.name())) .append(formatIfNotEmpty("<portRangeEnd>%s</portRangeEnd>", rule.portRangeEnd())) .append(formatIfNotEmpty("<portRangeStart>%s</portRangeStart>", rule.portRangeStart())) .append(formatIfNotEmpty("<protocol>%s</protocol>", rule.protocol())) .append(formatIfNotEmpty("<sourceIp>%s</sourceIp>", rule.sourceIp())) .append(formatIfNotEmpty("<sourceMac>%s</sourceMac>", rule.sourceMac())) .append(formatIfNotEmpty("<targetIp>%s</targetIp>", rule.targetIp())) .append("</request>"); requestBuilder.append("</ws:addFirewallRulesToNic>"); return requestBuilder.toString(); } | AddFirewallRuleToNicRequestBinder extends BaseProfitBricksRequestBinder<Firewall.Request.AddRulePayload> { @Override protected String createPayload(Firewall.Request.AddRulePayload payload) { requestBuilder.append("<ws:addFirewallRulesToNic>") .append(format("<nicId>%s</nicId>", payload.nicId())); for (Firewall.Rule rule : payload.rules()) requestBuilder .append("<request>") .append(formatIfNotEmpty("<icmpCode>%s</icmpCode>", rule.icmpCode())) .append(formatIfNotEmpty("<icmpType>%s</icmpType>", rule.icmpType())) .append(formatIfNotEmpty("<name>%s</name>", rule.name())) .append(formatIfNotEmpty("<portRangeEnd>%s</portRangeEnd>", rule.portRangeEnd())) .append(formatIfNotEmpty("<portRangeStart>%s</portRangeStart>", rule.portRangeStart())) .append(formatIfNotEmpty("<protocol>%s</protocol>", rule.protocol())) .append(formatIfNotEmpty("<sourceIp>%s</sourceIp>", rule.sourceIp())) .append(formatIfNotEmpty("<sourceMac>%s</sourceMac>", rule.sourceMac())) .append(formatIfNotEmpty("<targetIp>%s</targetIp>", rule.targetIp())) .append("</request>"); requestBuilder.append("</ws:addFirewallRulesToNic>"); return requestBuilder.toString(); } } | AddFirewallRuleToNicRequestBinder extends BaseProfitBricksRequestBinder<Firewall.Request.AddRulePayload> { @Override protected String createPayload(Firewall.Request.AddRulePayload payload) { requestBuilder.append("<ws:addFirewallRulesToNic>") .append(format("<nicId>%s</nicId>", payload.nicId())); for (Firewall.Rule rule : payload.rules()) requestBuilder .append("<request>") .append(formatIfNotEmpty("<icmpCode>%s</icmpCode>", rule.icmpCode())) .append(formatIfNotEmpty("<icmpType>%s</icmpType>", rule.icmpType())) .append(formatIfNotEmpty("<name>%s</name>", rule.name())) .append(formatIfNotEmpty("<portRangeEnd>%s</portRangeEnd>", rule.portRangeEnd())) .append(formatIfNotEmpty("<portRangeStart>%s</portRangeStart>", rule.portRangeStart())) .append(formatIfNotEmpty("<protocol>%s</protocol>", rule.protocol())) .append(formatIfNotEmpty("<sourceIp>%s</sourceIp>", rule.sourceIp())) .append(formatIfNotEmpty("<sourceMac>%s</sourceMac>", rule.sourceMac())) .append(formatIfNotEmpty("<targetIp>%s</targetIp>", rule.targetIp())) .append("</request>"); requestBuilder.append("</ws:addFirewallRulesToNic>"); return requestBuilder.toString(); } AddFirewallRuleToNicRequestBinder(); } | AddFirewallRuleToNicRequestBinder extends BaseProfitBricksRequestBinder<Firewall.Request.AddRulePayload> { @Override protected String createPayload(Firewall.Request.AddRulePayload payload) { requestBuilder.append("<ws:addFirewallRulesToNic>") .append(format("<nicId>%s</nicId>", payload.nicId())); for (Firewall.Rule rule : payload.rules()) requestBuilder .append("<request>") .append(formatIfNotEmpty("<icmpCode>%s</icmpCode>", rule.icmpCode())) .append(formatIfNotEmpty("<icmpType>%s</icmpType>", rule.icmpType())) .append(formatIfNotEmpty("<name>%s</name>", rule.name())) .append(formatIfNotEmpty("<portRangeEnd>%s</portRangeEnd>", rule.portRangeEnd())) .append(formatIfNotEmpty("<portRangeStart>%s</portRangeStart>", rule.portRangeStart())) .append(formatIfNotEmpty("<protocol>%s</protocol>", rule.protocol())) .append(formatIfNotEmpty("<sourceIp>%s</sourceIp>", rule.sourceIp())) .append(formatIfNotEmpty("<sourceMac>%s</sourceMac>", rule.sourceMac())) .append(formatIfNotEmpty("<targetIp>%s</targetIp>", rule.targetIp())) .append("</request>"); requestBuilder.append("</ws:addFirewallRulesToNic>"); return requestBuilder.toString(); } AddFirewallRuleToNicRequestBinder(); } | AddFirewallRuleToNicRequestBinder extends BaseProfitBricksRequestBinder<Firewall.Request.AddRulePayload> { @Override protected String createPayload(Firewall.Request.AddRulePayload payload) { requestBuilder.append("<ws:addFirewallRulesToNic>") .append(format("<nicId>%s</nicId>", payload.nicId())); for (Firewall.Rule rule : payload.rules()) requestBuilder .append("<request>") .append(formatIfNotEmpty("<icmpCode>%s</icmpCode>", rule.icmpCode())) .append(formatIfNotEmpty("<icmpType>%s</icmpType>", rule.icmpType())) .append(formatIfNotEmpty("<name>%s</name>", rule.name())) .append(formatIfNotEmpty("<portRangeEnd>%s</portRangeEnd>", rule.portRangeEnd())) .append(formatIfNotEmpty("<portRangeStart>%s</portRangeStart>", rule.portRangeStart())) .append(formatIfNotEmpty("<protocol>%s</protocol>", rule.protocol())) .append(formatIfNotEmpty("<sourceIp>%s</sourceIp>", rule.sourceIp())) .append(formatIfNotEmpty("<sourceMac>%s</sourceMac>", rule.sourceMac())) .append(formatIfNotEmpty("<targetIp>%s</targetIp>", rule.targetIp())) .append("</request>"); requestBuilder.append("</ws:addFirewallRulesToNic>"); return requestBuilder.toString(); } AddFirewallRuleToNicRequestBinder(); } |
@Test public void testApplyWhereVirtualMachineWithIPForwardingRule() throws UnknownHostException { Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet .<Location>of(ZoneToLocationTest.one, ZoneToLocationTest.two)); Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet .<Image>of(TemplateToImageTest.one, TemplateToImageTest.two)); VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(locationSupplier, imageSupplier, CacheBuilder.newBuilder().<String, Set<IPForwardingRule>> build( new CacheLoader<String, Set<IPForwardingRule>>() { @Override public Set<IPForwardingRule> load(String arg0) throws Exception { return ImmutableSet.of(IPForwardingRule.builder().id("1234l").IPAddress("1.1.1.1").build()); } }), namingConvention); VirtualMachine guest = Iterables.get(new ListVirtualMachinesResponseTest().expected(), 0); NodeMetadata node = parser.apply(guest); assertEquals( node.toString(), new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3-54") .location(ZoneToLocationTest.one).status(Status.PENDING).hostname("i-3-54-VM") .privateAddresses(ImmutableSet.of("10.1.1.18")).publicAddresses(ImmutableSet.of("1.1.1.1")) .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, "XenServer")) .imageId(TemplateToImageTest.one.getId()) .operatingSystem(TemplateToImageTest.one.getOperatingSystem()) .tags(ImmutableSet.of("another-tag")) .userMetadata(ImmutableMap.of("some-tag", "some-value")) .build().toString() ); } | @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); @Override NodeMetadata apply(final VirtualMachine from); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); @Override NodeMetadata apply(final VirtualMachine from); static final Map<VirtualMachine.State, Status> vmStateToNodeStatus; } |
@Test public void testApplyWhereVirtualMachineHasNoIpForwardingRuleAndAPublicIP() throws UnknownHostException { Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet .<Location>of(ZoneToLocationTest.one, ZoneToLocationTest.two)); Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet .<Image>of(TemplateToImageTest.one, TemplateToImageTest.two)); VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(locationSupplier, imageSupplier, CacheBuilder.newBuilder().<String, Set<IPForwardingRule>> build( new CacheLoader<String, Set<IPForwardingRule>>() { @Override public Set<IPForwardingRule> load(String arg0) throws Exception { return ImmutableSet.of(); } }), namingConvention); VirtualMachine guest = VirtualMachine.builder() .id("54") .name("i-3-54-VM") .displayName("i-3-54-VM") .account("adrian") .domainId("1") .domain("ROOT") .created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2011-02-16T14:28:37-0800")) .state(VirtualMachine.State.STARTING) .isHAEnabled(false) .zoneId("1") .zoneName("San Jose 1") .templateId("2") .templateName("CentOS 5.3(64-bit) no GUI (XenServer)") .templateDisplayText("CentOS 5.3(64-bit) no GUI (XenServer)") .passwordEnabled(false) .serviceOfferingId("1") .serviceOfferingName("Small Instance") .cpuCount(1) .cpuSpeed(500) .memory(512) .guestOSId("11") .rootDeviceId("0") .rootDeviceType("NetworkFilesystem") .jobId("63l") .jobStatus(0) .nics(ImmutableSet.of(NIC.builder().id("72").networkId("204").netmask("255.255.255.0").gateway("1.1.1.1") .IPAddress("1.1.1.5").trafficType(TrafficType.GUEST).guestIPType(GuestIPType.VIRTUAL) .isDefault(true).build())).hypervisor("XenServer").build(); NodeMetadata node = parser.apply(guest); assertEquals( node.toString(), new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3-54") .location(ZoneToLocationTest.one).status(Status.PENDING).hostname("i-3-54-VM") .privateAddresses(ImmutableSet.<String>of()) .publicAddresses(ImmutableSet.<String>of("1.1.1.5")) .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, "XenServer")) .imageId(TemplateToImageTest.one.getId()) .operatingSystem(TemplateToImageTest.one.getOperatingSystem()).build().toString()); } | @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); @Override NodeMetadata apply(final VirtualMachine from); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); @Override NodeMetadata apply(final VirtualMachine from); static final Map<VirtualMachine.State, Status> vmStateToNodeStatus; } |
@Test public void testApplyWhereVirtualMachineWithNoPassword() throws UnknownHostException { Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet .<Location>of(ZoneToLocationTest.one, ZoneToLocationTest.two)); Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet .<Image>of(TemplateToImageTest.one, TemplateToImageTest.two)); VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(locationSupplier, imageSupplier, CacheBuilder.newBuilder().<String, Set<IPForwardingRule>> build( new CacheLoader<String, Set<IPForwardingRule>>() { @Override public Set<IPForwardingRule> load(String arg0) throws Exception { throw new ResourceNotFoundException("no ip forwarding rule for: " + arg0); } }), namingConvention); VirtualMachine guest = Iterables.get(new ListVirtualMachinesResponseTest().expected(), 0); NodeMetadata node = parser.apply(guest); assertEquals( node.toString(), new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3-54") .location(ZoneToLocationTest.one).status(Status.PENDING).hostname("i-3-54-VM") .privateAddresses(ImmutableSet.of("10.1.1.18")) .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, "XenServer")) .imageId(TemplateToImageTest.one.getId()) .operatingSystem(TemplateToImageTest.one.getOperatingSystem()) .tags(ImmutableSet.of("another-tag")) .userMetadata(ImmutableMap.of("some-tag", "some-value")) .build().toString()); } | @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); @Override NodeMetadata apply(final VirtualMachine from); } | VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> { @Override public NodeMetadata apply(final VirtualMachine from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getName()); builder.hostname(from.getDisplayName()); builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull()); if (from.getGroup() != null) { builder.group(from.getGroup()); } else if (from.getDisplayName() != null) { builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName())); } Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getProviderId().equals(from.getTemplateId() + "") && (input.getLocation() == null || input.getId().equals(from.getZoneId() + "")); } }).orNull(); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (!from.getTags().isEmpty()) { ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder(); for (Tag tag : from.getTags()) { tagsBuilder.put(tag.getKey(), tag.getValue()); } Map<String, String> tagMap = tagsBuilder.build(); builder.tags(filterValues(tagMap, equalTo("jclouds-empty-tag-placeholder")).keySet()) .userMetadata(filterValues(tagMap, not(equalTo("jclouds-empty-tag-placeholder")))); } builder.hardware(new HardwareBuilder() .ids(from.getServiceOfferingId() + "") .name(from.getServiceOfferingName() + "") .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed()))) .ram((int)from.getMemory()) .hypervisor(from.getHypervisor()) .build()); builder.status(vmStateToNodeStatus.get(from.getState())); Set<String> publicAddresses = newHashSet(); Set<String> privateAddresses = newHashSet(); if (from.getIPAddress() != null) { boolean isPrivate = isPrivateIPAddress(from.getIPAddress()); if (isPrivate) { privateAddresses.add(from.getIPAddress()); } else { publicAddresses.add(from.getIPAddress()); } } if (from.getPublicIP() != null) { publicAddresses.add(from.getPublicIP()); } for (NIC nic : from.getNICs()) { if (nic.getIPAddress() != null) { if (isPrivateIPAddress(nic.getIPAddress())) { privateAddresses.add(nic.getIPAddress()); } else { publicAddresses.add(nic.getIPAddress()); } } } try { Iterables.addAll(publicAddresses, transform( filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()), new Predicate<IPForwardingRule>() { @Override public boolean apply(IPForwardingRule rule) { return !"Deleting".equals(rule.getState()); } }), new Function<IPForwardingRule, String>() { @Override public String apply(IPForwardingRule rule) { return rule.getIPAddress(); } })); } catch (UncheckedExecutionException e) { if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) { Throwables.propagateIfPossible(e.getCause()); throw e; } } return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build(); } @Inject VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images,
LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,
GroupNamingConvention.Factory namingConvention); @Override NodeMetadata apply(final VirtualMachine from); static final Map<VirtualMachine.State, Status> vmStateToNodeStatus; } |
@Test public void testApply() { IngressRule ruleToConvert = IngressRule.builder() .id("some-id") .account("some-account") .securityGroupName("some-group-name") .protocol(IpProtocol.TCP.toString()) .startPort(10) .endPort(20) .CIDR("0.0.0.0/0") .build(); org.jclouds.cloudstack.domain.SecurityGroup origGroup = org.jclouds.cloudstack.domain.SecurityGroup.builder() .id("some-id") .name("some-group") .description("some-description") .account("some-account") .ingressRules(ImmutableSet.of(ruleToConvert)) .build(); CloudStackSecurityGroupToSecurityGroup parser = createGroupParser(); SecurityGroup group = parser.apply(origGroup); assertEquals(group.getId(), origGroup.getId()); assertEquals(group.getProviderId(), origGroup.getId()); assertEquals(group.getName(), origGroup.getName()); assertEquals(group.getOwnerId(), origGroup.getAccount()); assertEquals(group.getIpPermissions(), ImmutableSet.copyOf(transform(origGroup.getIngressRules(), ruleConverter))); } | @Override public SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); builder.id(group.getId()); builder.providerId(group.getId()); builder.name(group.getName()); builder.ownerId(group.getAccount()); builder.ipPermissions(transform(group.getIngressRules(), ruleToPermission)); return builder.build(); } | CloudStackSecurityGroupToSecurityGroup implements Function<org.jclouds.cloudstack.domain.SecurityGroup, SecurityGroup> { @Override public SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); builder.id(group.getId()); builder.providerId(group.getId()); builder.name(group.getName()); builder.ownerId(group.getAccount()); builder.ipPermissions(transform(group.getIngressRules(), ruleToPermission)); return builder.build(); } } | CloudStackSecurityGroupToSecurityGroup implements Function<org.jclouds.cloudstack.domain.SecurityGroup, SecurityGroup> { @Override public SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); builder.id(group.getId()); builder.providerId(group.getId()); builder.name(group.getName()); builder.ownerId(group.getAccount()); builder.ipPermissions(transform(group.getIngressRules(), ruleToPermission)); return builder.build(); } @Inject CloudStackSecurityGroupToSecurityGroup(Function<IngressRule, IpPermission> ruleToPermission); } | CloudStackSecurityGroupToSecurityGroup implements Function<org.jclouds.cloudstack.domain.SecurityGroup, SecurityGroup> { @Override public SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); builder.id(group.getId()); builder.providerId(group.getId()); builder.name(group.getName()); builder.ownerId(group.getAccount()); builder.ipPermissions(transform(group.getIngressRules(), ruleToPermission)); return builder.build(); } @Inject CloudStackSecurityGroupToSecurityGroup(Function<IngressRule, IpPermission> ruleToPermission); @Override SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group); } | CloudStackSecurityGroupToSecurityGroup implements Function<org.jclouds.cloudstack.domain.SecurityGroup, SecurityGroup> { @Override public SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group) { SecurityGroupBuilder builder = new SecurityGroupBuilder(); builder.id(group.getId()); builder.providerId(group.getId()); builder.name(group.getName()); builder.ownerId(group.getAccount()); builder.ipPermissions(transform(group.getIngressRules(), ruleToPermission)); return builder.build(); } @Inject CloudStackSecurityGroupToSecurityGroup(Function<IngressRule, IpPermission> ruleToPermission); @Override SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group); } |
@Test public void testApplyWithTCP() { IngressRule ruleToConvert = IngressRule.builder() .id("some-id") .account("some-account") .securityGroupName("some-group-name") .protocol(IpProtocol.TCP.toString()) .startPort(10) .endPort(20) .CIDR("0.0.0.0/0") .build(); IngressRuleToIpPermission converter = new IngressRuleToIpPermission(); IpPermission convertedPerm = converter.apply(ruleToConvert); assertEquals(convertedPerm.getIpProtocol(), IpProtocol.fromValue(ruleToConvert.getProtocol())); assertEquals(convertedPerm.getFromPort(), ruleToConvert.getStartPort()); assertEquals(convertedPerm.getToPort(), ruleToConvert.getEndPort()); assertEquals(convertedPerm.getCidrBlocks(), ImmutableSet.of("0.0.0.0/0")); assertEquals(convertedPerm.getTenantIdGroupNamePairs().size(), 1); assertEquals(convertedPerm.getGroupIds().size(), 0); } | @Override public IpPermission apply(IngressRule rule) { IpPermission.Builder builder = IpPermission.builder(); builder.ipProtocol(IpProtocol.fromValue(rule.getProtocol())); builder.fromPort(rule.getStartPort()); builder.toPort(rule.getEndPort()); if (rule.getCIDR() != null) { builder.cidrBlock(rule.getCIDR()); } if (rule.getSecurityGroupName() != null && rule.getAccount() != null) { builder.tenantIdGroupNamePair(rule.getAccount(), rule.getSecurityGroupName()); } return builder.build(); } | IngressRuleToIpPermission implements Function<IngressRule, IpPermission> { @Override public IpPermission apply(IngressRule rule) { IpPermission.Builder builder = IpPermission.builder(); builder.ipProtocol(IpProtocol.fromValue(rule.getProtocol())); builder.fromPort(rule.getStartPort()); builder.toPort(rule.getEndPort()); if (rule.getCIDR() != null) { builder.cidrBlock(rule.getCIDR()); } if (rule.getSecurityGroupName() != null && rule.getAccount() != null) { builder.tenantIdGroupNamePair(rule.getAccount(), rule.getSecurityGroupName()); } return builder.build(); } } | IngressRuleToIpPermission implements Function<IngressRule, IpPermission> { @Override public IpPermission apply(IngressRule rule) { IpPermission.Builder builder = IpPermission.builder(); builder.ipProtocol(IpProtocol.fromValue(rule.getProtocol())); builder.fromPort(rule.getStartPort()); builder.toPort(rule.getEndPort()); if (rule.getCIDR() != null) { builder.cidrBlock(rule.getCIDR()); } if (rule.getSecurityGroupName() != null && rule.getAccount() != null) { builder.tenantIdGroupNamePair(rule.getAccount(), rule.getSecurityGroupName()); } return builder.build(); } IngressRuleToIpPermission(); } | IngressRuleToIpPermission implements Function<IngressRule, IpPermission> { @Override public IpPermission apply(IngressRule rule) { IpPermission.Builder builder = IpPermission.builder(); builder.ipProtocol(IpProtocol.fromValue(rule.getProtocol())); builder.fromPort(rule.getStartPort()); builder.toPort(rule.getEndPort()); if (rule.getCIDR() != null) { builder.cidrBlock(rule.getCIDR()); } if (rule.getSecurityGroupName() != null && rule.getAccount() != null) { builder.tenantIdGroupNamePair(rule.getAccount(), rule.getSecurityGroupName()); } return builder.build(); } IngressRuleToIpPermission(); @Override IpPermission apply(IngressRule rule); } | IngressRuleToIpPermission implements Function<IngressRule, IpPermission> { @Override public IpPermission apply(IngressRule rule) { IpPermission.Builder builder = IpPermission.builder(); builder.ipProtocol(IpProtocol.fromValue(rule.getProtocol())); builder.fromPort(rule.getStartPort()); builder.toPort(rule.getEndPort()); if (rule.getCIDR() != null) { builder.cidrBlock(rule.getCIDR()); } if (rule.getSecurityGroupName() != null && rule.getAccount() != null) { builder.tenantIdGroupNamePair(rule.getAccount(), rule.getSecurityGroupName()); } return builder.build(); } IngressRuleToIpPermission(); @Override IpPermission apply(IngressRule rule); } |
@Test public void testLoad() throws UnknownHostException { final CloudStackApi client = createMock(CloudStackApi.class); SSHKeyPairApi keyClient = createMock(SSHKeyPairApi.class); SshKeyPair pair = createMock(SshKeyPair.class); expect(client.getSSHKeyPairApi()).andReturn(keyClient); expect(keyClient.createSSHKeyPair("group-1")).andReturn(pair); replay(client, keyClient); CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(CloudStackApi.class).toInstance(client); } }).getInstance(CreateUniqueKeyPair.class); assertEquals(parser.load("group-1"), pair); verify(client, keyClient); } | @Override public SshKeyPair load(String input) { SshKeyPair keyPair = null; while (keyPair == null) { try { keyPair = client.getSSHKeyPairApi().createSSHKeyPair(input); logger.debug(">> creating SSH key pair with name %s", input); } catch (IllegalStateException e) { logger.error(e, "<< error creating SSH key pair with name %s: ", Throwables.getRootCause(e).getMessage()); throw Throwables.propagate(e); } } logger.debug("<< created keyPair(%s)", keyPair.getName()); return keyPair; } | CreateUniqueKeyPair extends CacheLoader<String, SshKeyPair> { @Override public SshKeyPair load(String input) { SshKeyPair keyPair = null; while (keyPair == null) { try { keyPair = client.getSSHKeyPairApi().createSSHKeyPair(input); logger.debug(">> creating SSH key pair with name %s", input); } catch (IllegalStateException e) { logger.error(e, "<< error creating SSH key pair with name %s: ", Throwables.getRootCause(e).getMessage()); throw Throwables.propagate(e); } } logger.debug("<< created keyPair(%s)", keyPair.getName()); return keyPair; } } | CreateUniqueKeyPair extends CacheLoader<String, SshKeyPair> { @Override public SshKeyPair load(String input) { SshKeyPair keyPair = null; while (keyPair == null) { try { keyPair = client.getSSHKeyPairApi().createSSHKeyPair(input); logger.debug(">> creating SSH key pair with name %s", input); } catch (IllegalStateException e) { logger.error(e, "<< error creating SSH key pair with name %s: ", Throwables.getRootCause(e).getMessage()); throw Throwables.propagate(e); } } logger.debug("<< created keyPair(%s)", keyPair.getName()); return keyPair; } @Inject CreateUniqueKeyPair(CloudStackApi client); } | CreateUniqueKeyPair extends CacheLoader<String, SshKeyPair> { @Override public SshKeyPair load(String input) { SshKeyPair keyPair = null; while (keyPair == null) { try { keyPair = client.getSSHKeyPairApi().createSSHKeyPair(input); logger.debug(">> creating SSH key pair with name %s", input); } catch (IllegalStateException e) { logger.error(e, "<< error creating SSH key pair with name %s: ", Throwables.getRootCause(e).getMessage()); throw Throwables.propagate(e); } } logger.debug("<< created keyPair(%s)", keyPair.getName()); return keyPair; } @Inject CreateUniqueKeyPair(CloudStackApi client); @Override SshKeyPair load(String input); } | CreateUniqueKeyPair extends CacheLoader<String, SshKeyPair> { @Override public SshKeyPair load(String input) { SshKeyPair keyPair = null; while (keyPair == null) { try { keyPair = client.getSSHKeyPairApi().createSSHKeyPair(input); logger.debug(">> creating SSH key pair with name %s", input); } catch (IllegalStateException e) { logger.error(e, "<< error creating SSH key pair with name %s: ", Throwables.getRootCause(e).getMessage()); throw Throwables.propagate(e); } } logger.debug("<< created keyPair(%s)", keyPair.getName()); return keyPair; } @Inject CreateUniqueKeyPair(CloudStackApi client); @Override SshKeyPair load(String input); } |
@Test public void testLoad() throws UnknownHostException { final CloudStackApi client = createMock(CloudStackApi.class); SecurityGroupApi secClient = createMock(SecurityGroupApi.class); ZoneApi zoneClient = createMock(ZoneApi.class); AsyncJobApi jobClient = createMock(AsyncJobApi.class); SecurityGroup group = createMock(SecurityGroup.class); Zone zone = createMock(Zone.class); expect(group.getIngressRules()).andReturn(ImmutableSet.<IngressRule> of()); expect(group.getId()).andReturn("sec-1234").anyTimes(); expect(zone.isSecurityGroupsEnabled()).andReturn(true); expect(client.getSecurityGroupApi()).andReturn(secClient) .anyTimes(); expect(client.getZoneApi()).andReturn(zoneClient); expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes(); expect(zoneClient.getZone("zone-1")).andReturn(zone); expect(secClient.getSecurityGroupByName("group-1")).andReturn(null); expect(secClient.createSecurityGroup("group-1")).andReturn(group); expect(secClient.authorizeIngressPortsToCIDRs("sec-1234", "TCP", 22, 22, ImmutableSet.of("0.0.0.0/0"))).andReturn("job-1234"); replay(client, secClient, zoneClient, zone, group); ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder() .zone("zone-1") .name("group-1") .ports(ImmutableSet.of(22)) .cidrs(ImmutableSet.<String> of()).build(); FindSecurityGroupOrCreate parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(CloudStackApi.class).toInstance(client); bind(new TypeLiteral<CacheLoader<String, Zone>>() {}). to(ZoneIdToZone.class); bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}). to(ZoneIdToZoneSupplier.class); bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance("60"); bind(new TypeLiteral<Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup>>() { }).to(CreateSecurityGroupIfNeeded.class); bind(new TypeLiteral<CacheLoader<ZoneAndName, SecurityGroup>>() { }).to(FindSecurityGroupOrCreate.class); } @Provides @Singleton protected Predicate<String> jobComplete(JobComplete jobComplete) { return retry(jobComplete, 1200, 1, 5, SECONDS); } }).getInstance(FindSecurityGroupOrCreate.class); assertEquals(parser.load(input), group); verify(client, secClient, zoneClient, zone, group); } | @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); @Override SecurityGroup load(ZoneAndName in); @Override String toString(); } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); @Override SecurityGroup load(ZoneAndName in); @Override String toString(); } |
@Test public void testLoadAlreadyExists() throws UnknownHostException { final CloudStackApi client = createMock(CloudStackApi.class); SecurityGroupApi secClient = createMock(SecurityGroupApi.class); ZoneApi zoneClient = createMock(ZoneApi.class); AsyncJobApi jobClient = createMock(AsyncJobApi.class); SecurityGroup group = createMock(SecurityGroup.class); Zone zone = createMock(Zone.class); expect(group.getId()).andReturn("sec-1234").anyTimes(); expect(client.getSecurityGroupApi()).andReturn(secClient) .anyTimes(); expect(client.getZoneApi()).andReturn(zoneClient); expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes(); expect(secClient.getSecurityGroupByName("group-1")).andReturn(group); replay(client, secClient, zoneClient, zone, group); ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder() .zone("zone-1") .name("group-1") .ports(ImmutableSet.of(22)) .cidrs(ImmutableSet.<String> of()).build(); FindSecurityGroupOrCreate parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(CloudStackApi.class).toInstance(client); bind(new TypeLiteral<CacheLoader<String, Zone>>() {}). to(ZoneIdToZone.class); bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}). to(ZoneIdToZoneSupplier.class); bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance("60"); bind(new TypeLiteral<Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup>>() { }).to(CreateSecurityGroupIfNeeded.class); bind(new TypeLiteral<CacheLoader<ZoneAndName, SecurityGroup>>() { }).to(FindSecurityGroupOrCreate.class); } @Provides @Singleton protected Predicate<String> jobComplete(JobComplete jobComplete) { return retry(jobComplete, 1200, 1, 5, SECONDS); } }).getInstance(FindSecurityGroupOrCreate.class); assertEquals(parser.load(input), group); verify(client, secClient, zoneClient, zone, group); } | @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); @Override SecurityGroup load(ZoneAndName in); @Override String toString(); } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); @Override SecurityGroup load(ZoneAndName in); @Override String toString(); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testLoadZoneNoSecurityGroups() throws UnknownHostException { final CloudStackApi client = createMock(CloudStackApi.class); SecurityGroupApi secClient = createMock(SecurityGroupApi.class); ZoneApi zoneClient = createMock(ZoneApi.class); AsyncJobApi jobClient = createMock(AsyncJobApi.class); SecurityGroup group = createMock(SecurityGroup.class); Zone zone = createMock(Zone.class); expect(zone.isSecurityGroupsEnabled()).andReturn(false); expect(client.getSecurityGroupApi()).andReturn(secClient) .anyTimes(); expect(client.getZoneApi()).andReturn(zoneClient); expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes(); expect(zoneClient.getZone("zone-1")).andReturn(zone); expect(secClient.getSecurityGroupByName("group-1")).andReturn(null); replay(client, secClient, zoneClient, zone, group); ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder() .zone("zone-1") .name("group-1") .ports(ImmutableSet.of(22)) .cidrs(ImmutableSet.<String> of()).build(); FindSecurityGroupOrCreate parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(CloudStackApi.class).toInstance(client); bind(new TypeLiteral<CacheLoader<String, Zone>>() {}). to(ZoneIdToZone.class); bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}). to(ZoneIdToZoneSupplier.class); bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance("60"); bind(new TypeLiteral<Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup>>() { }).to(CreateSecurityGroupIfNeeded.class); bind(new TypeLiteral<CacheLoader<ZoneAndName, SecurityGroup>>() { }).to(FindSecurityGroupOrCreate.class); } @Provides @Singleton protected Predicate<String> jobComplete(JobComplete jobComplete) { return retry(jobComplete, 1200, 1, 5, SECONDS); } }).getInstance(FindSecurityGroupOrCreate.class); assertEquals(parser.load(input), group); verify(client, secClient, zoneClient, zone, group); } | @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); @Override SecurityGroup load(ZoneAndName in); @Override String toString(); } | FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> { @Override public SecurityGroup load(ZoneAndName in) { SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName()); if (group != null) { return group; } else { return createNewSecurityGroup(in); } } @Inject FindSecurityGroupOrCreate(CloudStackApi client,
Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator); @Override SecurityGroup load(ZoneAndName in); @Override String toString(); } |
@Test public void testWithDoubleDomainname() { LoginResponse response = createMock(LoginResponse.class); SessionApi client = createMock(SessionApi.class); expect(client.loginUserInDomainWithHashOfPassword(eq("User"), eq("Test/Domain"), (String) anyObject())).andReturn(response); replay(client); LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client); Credentials cred = new Credentials("Test/Domain/User", "koffiedik"); obj.load(cred); } | @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); @Override LoginResponse load(Credentials input); @Override String toString(); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); @Override LoginResponse load(Credentials input); @Override String toString(); } |
@Test public void testCreatePayload() { CreateSnapshotRequestBinder binder = new CreateSnapshotRequestBinder(); Snapshot.Request.CreatePayload payload = Snapshot.Request.creatingBuilder() .storageId("123-1233-1324") .name("snapshot-name") .description("describing-the-snapshot") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Snapshot.Request.CreatePayload payload) { requestBuilder.append("<ws:createSnapshot>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(formatIfNotEmpty("<description>%s</description>", payload.description())) .append(formatIfNotEmpty("<snapshotName>%s</snapshotName>", payload.name())) .append("</request>") .append("</ws:createSnapshot>"); return requestBuilder.toString(); } | CreateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.CreatePayload> { @Override protected String createPayload(Snapshot.Request.CreatePayload payload) { requestBuilder.append("<ws:createSnapshot>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(formatIfNotEmpty("<description>%s</description>", payload.description())) .append(formatIfNotEmpty("<snapshotName>%s</snapshotName>", payload.name())) .append("</request>") .append("</ws:createSnapshot>"); return requestBuilder.toString(); } } | CreateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.CreatePayload> { @Override protected String createPayload(Snapshot.Request.CreatePayload payload) { requestBuilder.append("<ws:createSnapshot>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(formatIfNotEmpty("<description>%s</description>", payload.description())) .append(formatIfNotEmpty("<snapshotName>%s</snapshotName>", payload.name())) .append("</request>") .append("</ws:createSnapshot>"); return requestBuilder.toString(); } protected CreateSnapshotRequestBinder(); } | CreateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.CreatePayload> { @Override protected String createPayload(Snapshot.Request.CreatePayload payload) { requestBuilder.append("<ws:createSnapshot>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(formatIfNotEmpty("<description>%s</description>", payload.description())) .append(formatIfNotEmpty("<snapshotName>%s</snapshotName>", payload.name())) .append("</request>") .append("</ws:createSnapshot>"); return requestBuilder.toString(); } protected CreateSnapshotRequestBinder(); } | CreateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.CreatePayload> { @Override protected String createPayload(Snapshot.Request.CreatePayload payload) { requestBuilder.append("<ws:createSnapshot>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(formatIfNotEmpty("<description>%s</description>", payload.description())) .append(formatIfNotEmpty("<snapshotName>%s</snapshotName>", payload.name())) .append("</request>") .append("</ws:createSnapshot>"); return requestBuilder.toString(); } protected CreateSnapshotRequestBinder(); } |
@Test public void testWithSingleDomainname() { LoginResponse response = createMock(LoginResponse.class); SessionApi client = createMock(SessionApi.class); expect(client.loginUserInDomainWithHashOfPassword(eq("User"), eq("Domain"), (String) anyObject())).andReturn(response); replay(client); LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client); Credentials cred = new Credentials("Domain/User", "koffiedik"); obj.load(cred); } | @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); @Override LoginResponse load(Credentials input); @Override String toString(); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); @Override LoginResponse load(Credentials input); @Override String toString(); } |
@Test public void testWithNoDomainname() { LoginResponse response = createMock(LoginResponse.class); SessionApi client = createMock(SessionApi.class); expect(client.loginUserInDomainWithHashOfPassword(eq("User"), eq(""), (String) anyObject())).andReturn(response); replay(client); LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client); Credentials cred = new Credentials("User", "koffiedik"); obj.load(cred); } | @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); @Override LoginResponse load(Credentials input); @Override String toString(); } | LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> { @Override public LoginResponse load(Credentials input) { String username = input.identity; String domain = ""; if (username.indexOf('/') != -1) { domain = username.substring(0, username.lastIndexOf('/')); username = username.substring(username.lastIndexOf('/') + 1, username.length()); } String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes()); return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword); } @Inject LoginWithPasswordCredentials(SessionApi client); @Override LoginResponse load(Credentials input); @Override String toString(); } |
@Test(expectedExceptions = IllegalStateException.class) public void testMustParseSomething() throws Exception { new NodesParsedFromSupplier(ByteSource.wrap("nodes:\n".getBytes(Charsets.UTF_8)), new NodesFromYamlStream()).get(); } | @Override public LoadingCache<String, Node> get() { LoadingCache<String, Node> nodes = parser.apply(supplier); checkState(nodes != null && nodes.size() > 0, "no nodes parsed from supplier: %s", supplier); return nodes; } | NodesParsedFromSupplier implements Supplier<LoadingCache<String, Node>> { @Override public LoadingCache<String, Node> get() { LoadingCache<String, Node> nodes = parser.apply(supplier); checkState(nodes != null && nodes.size() > 0, "no nodes parsed from supplier: %s", supplier); return nodes; } } | NodesParsedFromSupplier implements Supplier<LoadingCache<String, Node>> { @Override public LoadingCache<String, Node> get() { LoadingCache<String, Node> nodes = parser.apply(supplier); checkState(nodes != null && nodes.size() > 0, "no nodes parsed from supplier: %s", supplier); return nodes; } @Inject NodesParsedFromSupplier(@Provider ByteSource supplier, Function<ByteSource, LoadingCache<String, Node>> parser); } | NodesParsedFromSupplier implements Supplier<LoadingCache<String, Node>> { @Override public LoadingCache<String, Node> get() { LoadingCache<String, Node> nodes = parser.apply(supplier); checkState(nodes != null && nodes.size() > 0, "no nodes parsed from supplier: %s", supplier); return nodes; } @Inject NodesParsedFromSupplier(@Provider ByteSource supplier, Function<ByteSource, LoadingCache<String, Node>> parser); @Override LoadingCache<String, Node> get(); } | NodesParsedFromSupplier implements Supplier<LoadingCache<String, Node>> { @Override public LoadingCache<String, Node> get() { LoadingCache<String, Node> nodes = parser.apply(supplier); checkState(nodes != null && nodes.size() > 0, "no nodes parsed from supplier: %s", supplier); return nodes; } @Inject NodesParsedFromSupplier(@Provider ByteSource supplier, Function<ByteSource, LoadingCache<String, Node>> parser); @Override LoadingCache<String, Node> get(); } |
@Test public void testNodesParse() throws Exception { assertEquals(parser.apply(NodesFromYamlTest.TEST1), expectedNodeMetadataFromResource(resource, provider)); assertEquals(credentialStore, ImmutableMap.of("node#cluster-1", new Credentials("myUser", NodesFromYamlTest.key))); } | @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); @Override NodeMetadata apply(Node from); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); @Override NodeMetadata apply(Node from); } |
@Test public void testNodesParseLocation() throws Exception { assertEquals(parser.apply(NodesFromYamlTest.TEST2), expectedNodeMetadataFromResource(resource, zoneCalled("virginia", provider))); assertEquals(credentialStore, ImmutableMap.of("node#cluster-1", new Credentials("myUser", NodesFromYamlTest.key))); } | @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); @Override NodeMetadata apply(Node from); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); @Override NodeMetadata apply(Node from); } |
@Test public void testNodesParseLoginPort() throws Exception { assertEquals(parser.apply(NodesFromYamlTest.TEST3), expectedNodeMetadataFromResource(2, resource, provider, 2022)); } | @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); @Override NodeMetadata apply(Node from); } | NodeToNodeMetadata implements Function<Node, NodeMetadata> { @Override public NodeMetadata apply(Node from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId()); builder.name(from.getName()); builder.loginPort(from.getLoginPort()); builder.hostname(from.getHostname()); builder.location(findLocationWithId(from.getLocationId())); builder.group(from.getGroup()); builder.tags(from.getTags()); builder.userMetadata(from.getMetadata()); builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family( OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription()) .version(from.getOsVersion()).build()); builder.status(Status.RUNNING); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); if (from.getUsername() != null) { Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { credBuilder.credential(from.getCredential()); } if (from.getSudoPassword() != null) { credBuilder.password(from.getSudoPassword()); credBuilder.authenticateSudo(true); } LoginCredentials creds = credBuilder.build(); builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } return builder.build(); } @Inject NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,
Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore); @Override NodeMetadata apply(Node from); } |
@Test(dataProvider = "ignoreOnMacOSX") public void testGetBlobContentType_AutoDetect_True() throws IOException { FilesystemStorageStrategyImpl storageStrategyAutoDetectContentType = new FilesystemStorageStrategyImpl( new Provider<BlobBuilder>() { @Override public BlobBuilder get() { return new BlobBuilderImpl(); } }, TestUtils.TARGET_BASE_DIR, true, new FilesystemContainerNameValidatorImpl(), new FilesystemBlobKeyValidatorImpl(), defaultLocation); String blobKey = TestUtils.createRandomBlobKey("file-", ".jpg"); TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey); Blob blob = storageStrategyAutoDetectContentType.getBlob(CONTAINER_NAME, blobKey); assertEquals(blob.getMetadata().getContentMetadata().getContentType(), "image/jpeg"); blobKey = TestUtils.createRandomBlobKey("file-", ".pdf"); TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey); blob = storageStrategyAutoDetectContentType.getBlob(CONTAINER_NAME, blobKey); assertEquals(blob.getMetadata().getContentMetadata().getContentType(), "application/pdf"); blobKey = TestUtils.createRandomBlobKey("file-", ".mp4"); TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey); blob = storageStrategyAutoDetectContentType.getBlob(CONTAINER_NAME, blobKey); assertEquals(blob.getMetadata().getContentMetadata().getContentType(), "video/mp4"); } | @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); } |
@Test(dataProvider = "ignoreOnMacOSX") public void testGetBlobContentType_AutoDetect_False() throws IOException { String blobKey = TestUtils.createRandomBlobKey("file-", ".jpg"); TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey); Blob blob = storageStrategy.getBlob(CONTAINER_NAME, blobKey); assertEquals(blob.getMetadata().getContentMetadata().getContentType(), null); } | @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); ByteSource byteSource; if (getDirectoryBlobSuffix(key) != null) { if (!file.isDirectory()) { return null; } logger.debug("%s - %s is a directory", container, key); byteSource = ByteSource.empty(); } else { byteSource = Files.asByteSource(file); } try { String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; HashCode hashCode = null; String eTag = null; Date expires = null; Tier tier = Tier.STANDARD; ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath()); if (view != null) { try { Set<String> attributes = ImmutableSet.copyOf(view.list()); cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL); contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION); contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING); contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE); contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE); if (contentType == null && autoDetectContentType) { contentType = probeContentType(file.toPath()); } if (attributes.contains(XATTR_CONTENT_MD5)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5)); view.read(XATTR_CONTENT_MD5, buf); byte [] etagBytes = buf.array(); if (etagBytes.length == 16) { hashCode = HashCode.fromBytes(buf.array()); eTag = "\"" + hashCode + "\""; } else { eTag = new String(etagBytes, US_ASCII); } } if (attributes.contains(XATTR_EXPIRES)) { ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES)); view.read(XATTR_EXPIRES, buf); buf.flip(); expires = new Date(buf.asLongBuffer().get()); } String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER); if (tierString != null) { tier = Tier.valueOf(tierString); } for (String attribute : attributes) { if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) { continue; } String value = readStringAttributeIfPresent(view, attributes, attribute); userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value); } } catch (IOException e) { logger.debug("xattrs not supported on %s", file.toPath()); } builder.payload(byteSource) .cacheControl(cacheControl) .contentDisposition(contentDisposition) .contentEncoding(contentEncoding) .contentLanguage(contentLanguage) .contentLength(byteSource.size()) .contentMD5(hashCode) .eTag(eTag) .contentType(contentType) .expires(expires) .tier(tier) .userMetadata(userMetadata.build()); } else { builder.payload(byteSource) .contentLength(byteSource.size()) .contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } } catch (FileNotFoundException fnfe) { return null; } catch (IOException e) { throw Throwables.propagate(e); } Blob blob = builder.build(); blob.getMetadata().setContainer(container); blob.getMetadata().setLastModified(new Date(file.lastModified())); blob.getMetadata().setSize(file.length()); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); } |
@Test public void testPutIncorrectContentLength() throws Exception { Blob blob = new BlobBuilderImpl() .name("key") .payload(randomByteSource().slice(0, 1024)) .contentLength(512) .build(); try { storageStrategy.putBlob(CONTAINER_NAME, blob); Fail.failBecauseExceptionWasNotThrown(IOException.class); } catch (IOException ioe) { } } | @Override public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); if (getDirectoryBlobSuffix(blobKey) != null) { return putDirectoryBlob(containerName, blob); } File outputFile = getFileForBlobKey(containerName, blobKey); String tmpBlobName = blobKey + "-" + UUID.randomUUID(); File tmpFile = getFileForBlobKey(containerName, tmpBlobName); Path tmpPath = tmpFile.toPath(); boolean isMpu = false; if (blob.getMetadata() != null && blob.getMetadata().getETag() != null) isMpu = MPU_ETAG_FORMAT.matcher(blob.getMetadata().getETag()).matches(); InputStream inputStream = null; byte[] eTag = null; try { Files.createParentDirs(tmpFile); if (isMpu) { inputStream = payload.openStream(); eTag = blob.getMetadata().getETag().getBytes(); } else { inputStream = new HashingInputStream(Hashing.md5(), payload.openStream()); } long actualSize = Files.asByteSink(tmpFile).writeFrom(inputStream); Long expectedSize = blob.getMetadata().getContentMetadata().getContentLength(); if (expectedSize != null && actualSize != expectedSize) { throw new IOException("Content-Length mismatch, actual: " + actualSize + " expected: " + expectedSize); } if (!isMpu) { HashCode actualHashCode = ((HashingInputStream) inputStream).hash(); HashCode expectedHashCode = payload.getContentMetadata().getContentMD5AsHashCode(); if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) { throw new IOException("MD5 hash code mismatch, actual: " + actualHashCode + " expected: " + expectedHashCode); } payload.getContentMetadata().setContentMD5(actualHashCode); eTag = actualHashCode.asBytes(); } if (outputFile.exists()) { delete(outputFile); } UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(tmpPath); if (view != null) { try { view.write(XATTR_CONTENT_MD5, ByteBuffer.wrap(eTag)); writeCommonMetadataAttr(view, blob); } catch (IOException e) { logger.debug("xattrs not supported on %s", tmpPath); } } setBlobAccess(containerName, tmpBlobName, BlobAccess.PRIVATE); if (!tmpFile.renameTo(outputFile)) { throw new IOException("Could not rename file " + tmpFile + " to " + outputFile); } tmpFile = null; return base16().lowerCase().encode(eTag); } finally { if (tmpFile != null) { try { delete(tmpFile); } catch (IOException e) { logger.debug("Could not delete %s: %s", tmpFile, e); } } closeQuietly(inputStream); if (payload != null) { payload.release(); } } } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); if (getDirectoryBlobSuffix(blobKey) != null) { return putDirectoryBlob(containerName, blob); } File outputFile = getFileForBlobKey(containerName, blobKey); String tmpBlobName = blobKey + "-" + UUID.randomUUID(); File tmpFile = getFileForBlobKey(containerName, tmpBlobName); Path tmpPath = tmpFile.toPath(); boolean isMpu = false; if (blob.getMetadata() != null && blob.getMetadata().getETag() != null) isMpu = MPU_ETAG_FORMAT.matcher(blob.getMetadata().getETag()).matches(); InputStream inputStream = null; byte[] eTag = null; try { Files.createParentDirs(tmpFile); if (isMpu) { inputStream = payload.openStream(); eTag = blob.getMetadata().getETag().getBytes(); } else { inputStream = new HashingInputStream(Hashing.md5(), payload.openStream()); } long actualSize = Files.asByteSink(tmpFile).writeFrom(inputStream); Long expectedSize = blob.getMetadata().getContentMetadata().getContentLength(); if (expectedSize != null && actualSize != expectedSize) { throw new IOException("Content-Length mismatch, actual: " + actualSize + " expected: " + expectedSize); } if (!isMpu) { HashCode actualHashCode = ((HashingInputStream) inputStream).hash(); HashCode expectedHashCode = payload.getContentMetadata().getContentMD5AsHashCode(); if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) { throw new IOException("MD5 hash code mismatch, actual: " + actualHashCode + " expected: " + expectedHashCode); } payload.getContentMetadata().setContentMD5(actualHashCode); eTag = actualHashCode.asBytes(); } if (outputFile.exists()) { delete(outputFile); } UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(tmpPath); if (view != null) { try { view.write(XATTR_CONTENT_MD5, ByteBuffer.wrap(eTag)); writeCommonMetadataAttr(view, blob); } catch (IOException e) { logger.debug("xattrs not supported on %s", tmpPath); } } setBlobAccess(containerName, tmpBlobName, BlobAccess.PRIVATE); if (!tmpFile.renameTo(outputFile)) { throw new IOException("Could not rename file " + tmpFile + " to " + outputFile); } tmpFile = null; return base16().lowerCase().encode(eTag); } finally { if (tmpFile != null) { try { delete(tmpFile); } catch (IOException e) { logger.debug("Could not delete %s: %s", tmpFile, e); } } closeQuietly(inputStream); if (payload != null) { payload.release(); } } } } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); if (getDirectoryBlobSuffix(blobKey) != null) { return putDirectoryBlob(containerName, blob); } File outputFile = getFileForBlobKey(containerName, blobKey); String tmpBlobName = blobKey + "-" + UUID.randomUUID(); File tmpFile = getFileForBlobKey(containerName, tmpBlobName); Path tmpPath = tmpFile.toPath(); boolean isMpu = false; if (blob.getMetadata() != null && blob.getMetadata().getETag() != null) isMpu = MPU_ETAG_FORMAT.matcher(blob.getMetadata().getETag()).matches(); InputStream inputStream = null; byte[] eTag = null; try { Files.createParentDirs(tmpFile); if (isMpu) { inputStream = payload.openStream(); eTag = blob.getMetadata().getETag().getBytes(); } else { inputStream = new HashingInputStream(Hashing.md5(), payload.openStream()); } long actualSize = Files.asByteSink(tmpFile).writeFrom(inputStream); Long expectedSize = blob.getMetadata().getContentMetadata().getContentLength(); if (expectedSize != null && actualSize != expectedSize) { throw new IOException("Content-Length mismatch, actual: " + actualSize + " expected: " + expectedSize); } if (!isMpu) { HashCode actualHashCode = ((HashingInputStream) inputStream).hash(); HashCode expectedHashCode = payload.getContentMetadata().getContentMD5AsHashCode(); if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) { throw new IOException("MD5 hash code mismatch, actual: " + actualHashCode + " expected: " + expectedHashCode); } payload.getContentMetadata().setContentMD5(actualHashCode); eTag = actualHashCode.asBytes(); } if (outputFile.exists()) { delete(outputFile); } UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(tmpPath); if (view != null) { try { view.write(XATTR_CONTENT_MD5, ByteBuffer.wrap(eTag)); writeCommonMetadataAttr(view, blob); } catch (IOException e) { logger.debug("xattrs not supported on %s", tmpPath); } } setBlobAccess(containerName, tmpBlobName, BlobAccess.PRIVATE); if (!tmpFile.renameTo(outputFile)) { throw new IOException("Could not rename file " + tmpFile + " to " + outputFile); } tmpFile = null; return base16().lowerCase().encode(eTag); } finally { if (tmpFile != null) { try { delete(tmpFile); } catch (IOException e) { logger.debug("Could not delete %s: %s", tmpFile, e); } } closeQuietly(inputStream); if (payload != null) { payload.release(); } } } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); if (getDirectoryBlobSuffix(blobKey) != null) { return putDirectoryBlob(containerName, blob); } File outputFile = getFileForBlobKey(containerName, blobKey); String tmpBlobName = blobKey + "-" + UUID.randomUUID(); File tmpFile = getFileForBlobKey(containerName, tmpBlobName); Path tmpPath = tmpFile.toPath(); boolean isMpu = false; if (blob.getMetadata() != null && blob.getMetadata().getETag() != null) isMpu = MPU_ETAG_FORMAT.matcher(blob.getMetadata().getETag()).matches(); InputStream inputStream = null; byte[] eTag = null; try { Files.createParentDirs(tmpFile); if (isMpu) { inputStream = payload.openStream(); eTag = blob.getMetadata().getETag().getBytes(); } else { inputStream = new HashingInputStream(Hashing.md5(), payload.openStream()); } long actualSize = Files.asByteSink(tmpFile).writeFrom(inputStream); Long expectedSize = blob.getMetadata().getContentMetadata().getContentLength(); if (expectedSize != null && actualSize != expectedSize) { throw new IOException("Content-Length mismatch, actual: " + actualSize + " expected: " + expectedSize); } if (!isMpu) { HashCode actualHashCode = ((HashingInputStream) inputStream).hash(); HashCode expectedHashCode = payload.getContentMetadata().getContentMD5AsHashCode(); if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) { throw new IOException("MD5 hash code mismatch, actual: " + actualHashCode + " expected: " + expectedHashCode); } payload.getContentMetadata().setContentMD5(actualHashCode); eTag = actualHashCode.asBytes(); } if (outputFile.exists()) { delete(outputFile); } UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(tmpPath); if (view != null) { try { view.write(XATTR_CONTENT_MD5, ByteBuffer.wrap(eTag)); writeCommonMetadataAttr(view, blob); } catch (IOException e) { logger.debug("xattrs not supported on %s", tmpPath); } } setBlobAccess(containerName, tmpBlobName, BlobAccess.PRIVATE); if (!tmpFile.renameTo(outputFile)) { throw new IOException("Could not rename file " + tmpFile + " to " + outputFile); } tmpFile = null; return base16().lowerCase().encode(eTag); } finally { if (tmpFile != null) { try { delete(tmpFile); } catch (IOException e) { logger.debug("Could not delete %s: %s", tmpFile, e); } } closeQuietly(inputStream); if (payload != null) { payload.release(); } } } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); if (getDirectoryBlobSuffix(blobKey) != null) { return putDirectoryBlob(containerName, blob); } File outputFile = getFileForBlobKey(containerName, blobKey); String tmpBlobName = blobKey + "-" + UUID.randomUUID(); File tmpFile = getFileForBlobKey(containerName, tmpBlobName); Path tmpPath = tmpFile.toPath(); boolean isMpu = false; if (blob.getMetadata() != null && blob.getMetadata().getETag() != null) isMpu = MPU_ETAG_FORMAT.matcher(blob.getMetadata().getETag()).matches(); InputStream inputStream = null; byte[] eTag = null; try { Files.createParentDirs(tmpFile); if (isMpu) { inputStream = payload.openStream(); eTag = blob.getMetadata().getETag().getBytes(); } else { inputStream = new HashingInputStream(Hashing.md5(), payload.openStream()); } long actualSize = Files.asByteSink(tmpFile).writeFrom(inputStream); Long expectedSize = blob.getMetadata().getContentMetadata().getContentLength(); if (expectedSize != null && actualSize != expectedSize) { throw new IOException("Content-Length mismatch, actual: " + actualSize + " expected: " + expectedSize); } if (!isMpu) { HashCode actualHashCode = ((HashingInputStream) inputStream).hash(); HashCode expectedHashCode = payload.getContentMetadata().getContentMD5AsHashCode(); if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) { throw new IOException("MD5 hash code mismatch, actual: " + actualHashCode + " expected: " + expectedHashCode); } payload.getContentMetadata().setContentMD5(actualHashCode); eTag = actualHashCode.asBytes(); } if (outputFile.exists()) { delete(outputFile); } UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(tmpPath); if (view != null) { try { view.write(XATTR_CONTENT_MD5, ByteBuffer.wrap(eTag)); writeCommonMetadataAttr(view, blob); } catch (IOException e) { logger.debug("xattrs not supported on %s", tmpPath); } } setBlobAccess(containerName, tmpBlobName, BlobAccess.PRIVATE); if (!tmpFile.renameTo(outputFile)) { throw new IOException("Could not rename file " + tmpFile + " to " + outputFile); } tmpFile = null; return base16().lowerCase().encode(eTag); } finally { if (tmpFile != null) { try { delete(tmpFile); } catch (IOException e) { logger.debug("Could not delete %s: %s", tmpFile, e); } } closeQuietly(inputStream); if (payload != null) { payload.release(); } } } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); } |
@Test public void testDeletingInvalidPathFileEndsNormally() { String invalidPathBlobKey = "A<!:!@#$%^&*?]8 /\0"; try { storageStrategy.removeBlob(CONTAINER_NAME, invalidPathBlobKey); } catch (InvalidPathException ipe) { fail("Deleting an invalid path ended with an InvalidPathException.", ipe); } } | @Override public void removeBlob(final String container, final String blobKey) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(blobKey); String fileName = buildPathStartingFromBaseDir(container, blobKey); logger.debug("Deleting blob %s", fileName); File fileToBeDeleted = new File(fileName); if (fileToBeDeleted.isDirectory()) { try { UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(fileToBeDeleted.toPath()); if (view != null) { for (String s : view.list()) { view.delete(s); } } } catch (IOException e) { logger.debug("Could not delete attributes from %s: %s", fileToBeDeleted, e); } } try { delete(fileToBeDeleted); } catch (IOException e) { logger.debug("Could not delete %s: %s", fileToBeDeleted, e); } removeDirectoriesTreeOfBlobKey(container, blobKey); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public void removeBlob(final String container, final String blobKey) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(blobKey); String fileName = buildPathStartingFromBaseDir(container, blobKey); logger.debug("Deleting blob %s", fileName); File fileToBeDeleted = new File(fileName); if (fileToBeDeleted.isDirectory()) { try { UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(fileToBeDeleted.toPath()); if (view != null) { for (String s : view.list()) { view.delete(s); } } } catch (IOException e) { logger.debug("Could not delete attributes from %s: %s", fileToBeDeleted, e); } } try { delete(fileToBeDeleted); } catch (IOException e) { logger.debug("Could not delete %s: %s", fileToBeDeleted, e); } removeDirectoriesTreeOfBlobKey(container, blobKey); } } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public void removeBlob(final String container, final String blobKey) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(blobKey); String fileName = buildPathStartingFromBaseDir(container, blobKey); logger.debug("Deleting blob %s", fileName); File fileToBeDeleted = new File(fileName); if (fileToBeDeleted.isDirectory()) { try { UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(fileToBeDeleted.toPath()); if (view != null) { for (String s : view.list()) { view.delete(s); } } } catch (IOException e) { logger.debug("Could not delete attributes from %s: %s", fileToBeDeleted, e); } } try { delete(fileToBeDeleted); } catch (IOException e) { logger.debug("Could not delete %s: %s", fileToBeDeleted, e); } removeDirectoriesTreeOfBlobKey(container, blobKey); } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public void removeBlob(final String container, final String blobKey) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(blobKey); String fileName = buildPathStartingFromBaseDir(container, blobKey); logger.debug("Deleting blob %s", fileName); File fileToBeDeleted = new File(fileName); if (fileToBeDeleted.isDirectory()) { try { UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(fileToBeDeleted.toPath()); if (view != null) { for (String s : view.list()) { view.delete(s); } } } catch (IOException e) { logger.debug("Could not delete attributes from %s: %s", fileToBeDeleted, e); } } try { delete(fileToBeDeleted); } catch (IOException e) { logger.debug("Could not delete %s: %s", fileToBeDeleted, e); } removeDirectoriesTreeOfBlobKey(container, blobKey); } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); } | FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public void removeBlob(final String container, final String blobKey) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(blobKey); String fileName = buildPathStartingFromBaseDir(container, blobKey); logger.debug("Deleting blob %s", fileName); File fileToBeDeleted = new File(fileName); if (fileToBeDeleted.isDirectory()) { try { UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(fileToBeDeleted.toPath()); if (view != null) { for (String s : view.list()) { view.delete(s); } } } catch (IOException e) { logger.debug("Could not delete attributes from %s: %s", fileToBeDeleted, e); } } try { delete(fileToBeDeleted); } catch (IOException e) { logger.debug("Could not delete %s: %s", fileToBeDeleted, e); } removeDirectoriesTreeOfBlobKey(container, blobKey); } @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,
@Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,
@Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,
FilesystemContainerNameValidator filesystemContainerNameValidator,
FilesystemBlobKeyValidator filesystemBlobKeyValidator,
Supplier<Location> defaultLocation); @Override boolean containerExists(String container); @Override Collection<String> getAllContainerNames(); @Override boolean createContainerInLocation(String container, Location location, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override void deleteContainer(String container); @Override void clearContainer(final String container); @Override void clearContainer(String container, ListContainerOptions options); @Override StorageMetadata getContainerMetadata(String container); @Override boolean blobExists(String container, String key); @Override Iterable<String> getBlobKeysInsideContainer(String container, String prefix); @Override Blob getBlob(final String container, final String key); @Override String putBlob(final String containerName, final Blob blob); @Override void removeBlob(final String container, final String blobKey); @Override BlobAccess getBlobAccess(String containerName, String blobName); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override Location getLocation(final String containerName); @Override String getSeparator(); boolean createContainer(String container); Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name); File getFileForBlobKey(String container, String blobKey); boolean directoryExists(String container, String directory); void createDirectory(String container, String directory); void deleteDirectory(String container, String directory); long countBlobs(String container, ListContainerOptions options); } |
@Test public void testRollbackPayload() { RollbackSnapshotRequestBinder binder = new RollbackSnapshotRequestBinder(); Snapshot.Request.RollbackPayload payload = Snapshot.Request.createRollbackPayload("snapshot-id", "storage-id"); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Snapshot.Request.RollbackPayload payload) { requestBuilder.append("<ws:rollbackSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.snapshotId())) .append(format("<storageId>%s</storageId>", payload.storageId())) .append("</request>") .append("</ws:rollbackSnapshot>"); return requestBuilder.toString(); } | RollbackSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.RollbackPayload> { @Override protected String createPayload(Snapshot.Request.RollbackPayload payload) { requestBuilder.append("<ws:rollbackSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.snapshotId())) .append(format("<storageId>%s</storageId>", payload.storageId())) .append("</request>") .append("</ws:rollbackSnapshot>"); return requestBuilder.toString(); } } | RollbackSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.RollbackPayload> { @Override protected String createPayload(Snapshot.Request.RollbackPayload payload) { requestBuilder.append("<ws:rollbackSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.snapshotId())) .append(format("<storageId>%s</storageId>", payload.storageId())) .append("</request>") .append("</ws:rollbackSnapshot>"); return requestBuilder.toString(); } protected RollbackSnapshotRequestBinder(); } | RollbackSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.RollbackPayload> { @Override protected String createPayload(Snapshot.Request.RollbackPayload payload) { requestBuilder.append("<ws:rollbackSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.snapshotId())) .append(format("<storageId>%s</storageId>", payload.storageId())) .append("</request>") .append("</ws:rollbackSnapshot>"); return requestBuilder.toString(); } protected RollbackSnapshotRequestBinder(); } | RollbackSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.RollbackPayload> { @Override protected String createPayload(Snapshot.Request.RollbackPayload payload) { requestBuilder.append("<ws:rollbackSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.snapshotId())) .append(format("<storageId>%s</storageId>", payload.storageId())) .append("</request>") .append("</ws:rollbackSnapshot>"); return requestBuilder.toString(); } protected RollbackSnapshotRequestBinder(); } |
@Test public void test401MakesAuthorizationException() { fn.handleError(command, HttpResponse.builder().statusCode(401).message("Unauthorized").build()); assertEquals(command.getException().getClass(), AuthorizationException.class); assertEquals(command.getException().getMessage(), "POST https: } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test404MakesResourceNotFoundException() { fn.handleError(command, HttpResponse.builder().statusCode(404).message("Not Found").build()); assertEquals(command.getException().getClass(), ResourceNotFoundException.class); assertEquals(command.getException().getMessage(), "POST https: } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test400MakesIllegalStateExceptionOnQuotaExceededOnNoFixedIps() { fn.handleError(command, noFixedIps); assertEquals(command.getException().getClass(), IllegalStateException.class); assertEquals(command.getException().getMessage(), noFixedIps.getPayload().getRawContent()); } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test400MakesIllegalStateExceptionOnAlreadyExists() { fn.handleError(command, alreadyExists); assertEquals(command.getException().getClass(), IllegalStateException.class); assertEquals(command.getException().getMessage(), alreadyExists.getPayload().getRawContent()); } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test400MakesInsufficientResourcesExceptionOnQuotaExceeded() { fn.handleError(command, quotaExceeded); assertEquals(command.getException().getClass(), InsufficientResourcesException.class); assertEquals(command.getException().getMessage(), quotaExceeded.getPayload().getRawContent()); } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test413MakesInsufficientResourcesException() { fn.handleError(command, tooLarge); assertEquals(command.getException().getClass(), InsufficientResourcesException.class); assertEquals(command.getException().getMessage(), tooLarge.getPayload().getRawContent()); } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test413WithRetryAtExceptionParsesDelta() { fn.handleError(command, retryAt); assertEquals(command.getException().getClass(), RetryAfterException.class); assertEquals(command.getException().getMessage(), "retry in 3600 seconds"); } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test413WithRetryAfterExceptionFolsom() { fn.handleError(command, retryAfter); assertEquals(command.getException().getClass(), RetryAfterException.class); assertEquals(command.getException().getMessage(), "retry in 54 seconds"); } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test413WithRetryAfterTrumpsRetryAt() { fn.handleError(command, retryAfterTrumps); assertEquals(command.getException().getClass(), RetryAfterException.class); assertEquals(command.getException().getMessage(), "retry in 54 seconds"); } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void test413WithBadRetryAtFormatFallsBack() { fn.handleError(command, badRetryAt); assertEquals(command.getException().getClass(), InsufficientResourcesException.class); assertEquals(command.getException().getMessage(), badRetryAt.getPayload().getRawContent()); } | public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } | NovaErrorHandler implements HttpErrorHandler { public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String content = data != null ? emptyToNull(new String(data)) : null; Exception exception = content != null ? new HttpResponseException(command, response, content) : new HttpResponseException(command, response, logSensitiveInformation); String requestLine = command.getCurrentRequest().getRequestLine(); String message = content != null ? content : String.format("%s -> %s", requestLine, response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.indexOf("quota exceeded") != -1) exception = new InsufficientResourcesException(message, exception); else if (message.indexOf("has no fixed_ips") != -1) exception = new IllegalStateException(message, exception); else if (message.indexOf("already exists") != -1) exception = new IllegalStateException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST") && message.indexOf("The server has either erred or is incapable of performing the requested operation.") != -1 && command.getCurrentRequest().getEndpoint().getPath().indexOf("os-floating-ips") != -1) { exception = new InsufficientResourcesException(message, exception); } break; case 413: if (content == null) { exception = new InsufficientResourcesException(message, exception); break; } exception = parseAndBuildRetryException(content, message, exception); } command.setException(exception); } protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser); @Inject NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser); void handleError(HttpCommand command, HttpResponse response); } |
@Test public void testUpdatePayload() { UpdateSnapshotRequestBinder binder = new UpdateSnapshotRequestBinder(); Snapshot.Request.UpdatePayload payload = Snapshot.Request.updatingBuilder() .id("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh") .description("description") .name("snapshot-name") .bootable(true) .osType(OsType.LINUX) .isCpuHotPlug(true) .isCpuHotUnPlug(true) .isRamHotPlug(true) .isRamHotUnPlug(true) .isNicHotPlug(true) .isNicHotUnPlug(true) .isDiscVirtioHotPlug(true) .isDiscVirtioHotUnPlug(true) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } | @Override protected String createPayload(Snapshot.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.id())) .append(format("<description>%s</description>", payload.description())) .append(format("<snapshotName>%s</snapshotName>", payload.name())) .append(formatIfNotEmpty("<bootable>%s</bootable>", payload.bootable())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<cpuHotUnPlug>%s</cpuHotUnPlug>", payload.isCpuHotUnPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<ramHotUnPlug>%s</ramHotUnPlug>", payload.isRamHotUnPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateSnapshot>"); return requestBuilder.toString(); } | UpdateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.UpdatePayload> { @Override protected String createPayload(Snapshot.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.id())) .append(format("<description>%s</description>", payload.description())) .append(format("<snapshotName>%s</snapshotName>", payload.name())) .append(formatIfNotEmpty("<bootable>%s</bootable>", payload.bootable())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<cpuHotUnPlug>%s</cpuHotUnPlug>", payload.isCpuHotUnPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<ramHotUnPlug>%s</ramHotUnPlug>", payload.isRamHotUnPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateSnapshot>"); return requestBuilder.toString(); } } | UpdateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.UpdatePayload> { @Override protected String createPayload(Snapshot.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.id())) .append(format("<description>%s</description>", payload.description())) .append(format("<snapshotName>%s</snapshotName>", payload.name())) .append(formatIfNotEmpty("<bootable>%s</bootable>", payload.bootable())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<cpuHotUnPlug>%s</cpuHotUnPlug>", payload.isCpuHotUnPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<ramHotUnPlug>%s</ramHotUnPlug>", payload.isRamHotUnPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateSnapshot>"); return requestBuilder.toString(); } protected UpdateSnapshotRequestBinder(); } | UpdateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.UpdatePayload> { @Override protected String createPayload(Snapshot.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.id())) .append(format("<description>%s</description>", payload.description())) .append(format("<snapshotName>%s</snapshotName>", payload.name())) .append(formatIfNotEmpty("<bootable>%s</bootable>", payload.bootable())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<cpuHotUnPlug>%s</cpuHotUnPlug>", payload.isCpuHotUnPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<ramHotUnPlug>%s</ramHotUnPlug>", payload.isRamHotUnPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateSnapshot>"); return requestBuilder.toString(); } protected UpdateSnapshotRequestBinder(); } | UpdateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.UpdatePayload> { @Override protected String createPayload(Snapshot.Request.UpdatePayload payload) { requestBuilder.append("<ws:updateSnapshot>") .append("<request>") .append(format("<snapshotId>%s</snapshotId>", payload.id())) .append(format("<description>%s</description>", payload.description())) .append(format("<snapshotName>%s</snapshotName>", payload.name())) .append(formatIfNotEmpty("<bootable>%s</bootable>", payload.bootable())) .append(formatIfNotEmpty("<osType>%s</osType>", payload.osType())) .append(formatIfNotEmpty("<cpuHotPlug>%s</cpuHotPlug>", payload.isCpuHotPlug())) .append(formatIfNotEmpty("<cpuHotUnPlug>%s</cpuHotUnPlug>", payload.isCpuHotUnPlug())) .append(formatIfNotEmpty("<ramHotPlug>%s</ramHotPlug>", payload.isRamHotPlug())) .append(formatIfNotEmpty("<ramHotUnPlug>%s</ramHotUnPlug>", payload.isRamHotUnPlug())) .append(formatIfNotEmpty("<nicHotPlug>%s</nicHotPlug>", payload.isNicHotPlug())) .append(formatIfNotEmpty("<nicHotUnPlug>%s</nicHotUnPlug>", payload.isNicHotUnPlug())) .append(formatIfNotEmpty("<discVirtioHotPlug>%s</discVirtioHotPlug>", payload.isDiscVirtioHotPlug())) .append(formatIfNotEmpty("<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>", payload.isDiscVirtioHotUnPlug())) .append("</request>") .append("</ws:updateSnapshot>"); return requestBuilder.toString(); } protected UpdateSnapshotRequestBinder(); } |
Subsets and Splits