auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public SlackResponse(String slackResponseString) { START JSONObject result = new JSONObject(slackResponseString); END channelId = result.getString("channel"); ts = result.getString("ts"); } This is a breaking change how it is currently implemented. It only works for bot user credentials, If you use a non bot user then this throws an exception: ``` org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1] at org.json.JSONTokener.syntaxError(JSONTokener.java:433) at org.json.JSONObject.<init>(JSONObject.java:194) at org.json.JSONObject.<init>(JSONObject.java:321) at jenkins.plugins.slack.workflow.SlackResponse.<init>(SlackResponse.java:13) at jenkins.plugins.slack.workflow.SlackSendStep$SlackSendStepExecution.run(SlackSendStep.java:270) at jenkins.plugins.slack.workflow.SlackSendStep$SlackSendStepExecution.run(SlackSendStep.java:198) at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:47) at hudson.security.ACL.impersonate(ACL.java:260) at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:44) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) ``` The contents of slackResponseString is: ``` ok ```

Target:
public SlackResponse(String slackResponseString) { if (!StringUtils.isEmpty(slackResponseString)) { JSONObject result = new JSONObject(slackResponseString); channelId = result.getString("channel"); ts = result.getString("ts"); } }
Source:
public SlackResponse(String slackResponseString) { START if (StringUtils.isEmpty(slackResponseString)) { END JSONObject result = new JSONObject(slackResponseString); channelId = result.getString("channel"); ts = result.getString("ts"); } } I don't think this change is quite what you wanted 😉 1. "ok" is the text returned for non bot users, but yes its correctly null as your new test demonstrates 2. now the case that you want doesn't work as this code is only invoked when the response is empty maybe ```suggestion if (!"ok".equals(slackResponseString)) { // non botUsers respond with only 'ok' ```

Target:
public SlackResponse(String slackResponseString) { if (!StringUtils.isEmpty(slackResponseString)) { JSONObject result = new JSONObject(slackResponseString); channelId = result.getString("channel"); ts = result.getString("ts"); } }
Source:
START public Person somePerson() { END return new Person(); } Die folgenden Methoden bitte im scope auf `private` stellen, diese werden und sollen ja nur in dieser Test Methode verwendet werden.

Target:
private static Person somePerson() { return new Person(); }
Source:
public void newPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(new Answer() { @Override START public Object answer(InvocationOnMock invocation) throws Throwable { END Errors errors = (Errors) invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; } }).when(validator).validate(any(), any()); perform(post("/web/person")).andExpect(view().name("person/person_form")); } Ich weiss nicht ob ihr euch das später anschauen wolltet, aber du kannst hier seit Java8 auch Lambdas verwenden. Siehe z.B. [hier](http://www.angelikalanger.com/Articles/EffectiveJava/71.Java8.Lambdas/71.Java8.Lambdas.html) oder auch [hier](https://blog.codecentric.de/2013/10/java-8-erste-schritte-mit-lambdas-und-streams/) oder ähnliches im Internet. D.h. du kannst aus den Zeilen 80 bis 87 ein lambda statt einer anonymen Instanz (Objekt) verwenden. Damit wird der Code kompakter und lesbarer. ``` doAnswer(invocation -> { Errors errors = invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; }).when(validator).validate(any(), any()); ```

Target:
public void newPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(invocation -> { Errors errors = invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; }).when(validator).validate(any(), any()); perform(post("/web/person")).andExpect(view().name("person/person_form")); }
Source:
START public void editPersonFormForUnknownIdThrowsUnknownPersonException() throws Exception { END assertThatThrownBy(() -> perform(get("/web/person/" + UNKNOWN_PERSON_ID + "/edit")) ).hasCauseInstanceOf(UnknownPersonException.class); } Da keine Exeption weiter nach aussen geworfen wird von `editPersonFormForUnknownIdThrowsUnknownPersonException()` kannst du das `throws Exception` hier einsparen.

Target:
public void editPersonFormForUnknownIdThrowsUnknownPersonException() { assertThatThrownBy(() -> perform(get("/web/person/" + UNKNOWN_PERSON_ID + "/edit")) ).hasCauseInstanceOf(UnknownPersonException.class); }
Source:
public void editPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(new Answer() { @Override START public Object answer(InvocationOnMock invocation) throws Throwable { END Errors errors = (Errors) invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; } }).when(validator).validate(any(), any()); perform(post("/web/person/" + PERSON_ID + "/edit")).andExpect(view().name("person/person_form")); } Auch dieser Block kannst du als Lambda ersetzen. Du kannst dir dazu auch mal das Answer Interface anschauen und was an dieser Stelle lambdas mit einem Interface mit genau [einer](http://tutorials.jenkov.com/java-functional-programming/functional-interfaces.html) Methode zu tun hat :)

Target:
public void editPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(invocation -> { Errors errors = invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; }).when(validator).validate(any(), any()); perform(post("/web/person/" + PERSON_ID + "/edit")).andExpect(view().name("person/person_form")); }
Source:
private static Person personWithId(int personId) { Person person = new Person(); START person.setId(PERSON_ID); END return person; } Hier ist die Konstante statt dem Argument verwendet worden und somit wird `personId` nicht gesetzt als ID der Person. Hier einfach statt der `PERSON_ID` `personId` verwenden.

Target:
private static Person personWithId(int personId) { Person person = new Person(); person.setId(personId); return person; }
Source:
public void showPersonInformationUsesGivenYear() throws Exception { when(personService.getPersonByID(PERSON_ID)).thenReturn(Optional.of(person)); when(departmentService.isSignedInUserAllowedToAccessPersonData(person, person)).thenReturn(true); START when(settingsService.getSettings()).thenReturn(settingsWithFederalState(FederalState.BADEN_WUERTTEMBERG)); END perform(get("/web/person/" + PERSON_ID).param(ControllerConstants.YEAR_ATTRIBUTE, "1985")) .andExpect(model().attribute(ControllerConstants.YEAR_ATTRIBUTE,1985)); } Gerne auch an diesen Stellen, welche sehr sprechend sind durch `settingsWithFederalState(...)` einen statischen Import verwenden. Dies macht den Test lesbarer.

Target:
public void showPersonInformationUsesGivenYear() throws Exception { when(personService.getPersonByID(PERSON_ID)).thenReturn(Optional.of(person)); when(departmentService.isSignedInUserAllowedToAccessPersonData(person, person)).thenReturn(true); when(settingsService.getSettings()).thenReturn(settingsWithFederalState(BADEN_WUERTTEMBERG)); perform(get("/web/person/" + PERSON_ID).param(YEAR_ATTRIBUTE, "1985")) .andExpect(model().attribute(YEAR_ATTRIBUTE,1985)); }
Source:
public void showPersonWithActiveTrueForUserWithRoleBossCallsCorrectService() throws Exception { START when(personService.getSignedInUser()).thenReturn(personWithRole(Role.BOSS)); END perform(get("/web/person").param("active", "true")); verify(personService).getActivePersons(); } Auch an solchen Stellen ist die Methode `personWithRole(...)` sehr sprechen und ein statischer Import würde die Lesbarkeit erhöhen.

Target:
public void showPersonWithActiveTrueForUserWithRoleBossCallsCorrectService() throws Exception { when(personService.getSignedInUser()).thenReturn(personWithRole(BOSS)); perform(get("/web/person").param("active", "true")); verify(personService).getActivePersons(); }
Source:
private DayLength getExpectedWorktimeFor(Person person, LocalDate currentDay) { Optional<WorkingTime> workingTimeOrNot = workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(person, currentDay); START if (workingTimeOrNot.isEmpty()) { END throw new FreeTimeAbsenceException("Person " + person + " does not have workingTime configured"); } WorkingTime workingTime = workingTimeOrNot.get(); return workingTime.getDayLengthForWeekDay(currentDay.getDayOfWeek().getValue()); } Wir sind auf java8, hat java8 isEmpty auf einem Optional?

Target:
private DayLength getExpectedWorktimeFor(Person person, LocalDate currentDay) { Optional<WorkingTime> workingTimeOrNot = workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(person, currentDay); if (!workingTimeOrNot.isPresent()) { throw new FreeTimeAbsenceException("Person " + person + " does not have workingTime configured"); } WorkingTime workingTime = workingTimeOrNot.get(); return workingTime.getDayLengthForWeekDay(currentDay.getDayOfWeek().getValue()); }
Source:
public Overtime(Person person, LocalDate startDate, LocalDate endDate, BigDecimal numberOfHours) { Assert.notNull(person, "Person must be given."); Assert.notNull(startDate, "Start date must be given."); Assert.notNull(endDate, "End date must be given."); Assert.notNull(numberOfHours, "Number of hours must be given."); this.person = person; this.startDate = startDate; this.endDate = endDate; this.hours = numberOfHours; START this.lastModificationDate = ZonedDateTime.now(UTC).toLocalDate(); END } LocalDate.now(UTC);

Target:
public Overtime(Person person, LocalDate startDate, LocalDate endDate, BigDecimal numberOfHours) { Assert.notNull(person, "Person must be given."); Assert.notNull(startDate, "Start date must be given."); Assert.notNull(endDate, "End date must be given."); Assert.notNull(numberOfHours, "Number of hours must be given."); this.person = person; this.startDate = startDate; this.endDate = endDate; this.hours = numberOfHours; this.lastModificationDate = LocalDate.now(UTC); }
Source:
BigDecimal calculatePresenceRatio() { BigDecimal absenceRatio = BigDecimal.ZERO; START for (TimedAbsence absenceSpan : absencesList) { END absenceRatio = absenceRatio.add(absenceSpan.getRatio()); } BigDecimal presenceRatio = BigDecimal.ONE.subtract(absenceRatio); boolean negativePresenceRatio = presenceRatio.compareTo(BigDecimal.ZERO) < 0; if (negativePresenceRatio) { presenceRatio = BigDecimal.ZERO; } return presenceRatio; } Warum erst aufsummieren? Man könnte doch direkt Subtrahieren oder übersehe ich etwas?

Target:
BigDecimal calculatePresenceRatio() { BigDecimal presenceRatio = BigDecimal.ONE; for (TimedAbsence absenceSpan : absencesList) { presenceRatio = presenceRatio.subtract(absenceSpan.getRatio()); } boolean negativePresenceRatio = presenceRatio.compareTo(BigDecimal.ZERO) < 0; if (negativePresenceRatio) { presenceRatio = BigDecimal.ZERO; } return presenceRatio; }
Source:
public HttpRequest signGetBlob(String container, String name, long timeInSeconds) { START System.out.println("Method signGetBlob is called " + container + " , " + name + " , " + timeInSeconds); END checkNotNull(container, "container"); checkNotNull(name, "name"); return sign("GET", container, name, null, timeInSeconds, null, null); } Remove unneeded logging.

Target:
public HttpRequest signGetBlob(String container, String name, long timeInSeconds) { checkNotNull(container, "container"); checkNotNull(name, "name"); return sign("GET", container, name, null, timeInSeconds, null, null); }
Source:
START public String[] cutUri (URI uri) throws NullPointerException, IllegalArgumentException { END String path = uri.getPath(); String[] result = path.split("/"); if (result.length < 2) { throw new IllegalArgumentException("there is neither ContainerName nor BlobName in the URI path"); } for (int i = 1; i < result.length; i++){ if (result[i] == null) { throw new NullPointerException("one of the path parameters is null"); } } return result; } ```suggestion public String[] cutUri(URI uri) throws NullPointerException, IllegalArgumentException { ```

Target:
public String[] cutUri(URI uri) throws IllegalArgumentException { String path = uri.getPath(); String[] result = path.split("/"); if (result.length < 2) { throw new IllegalArgumentException("there is neither ContainerName nor BlobName in the URI path"); } return result; }
Source:
public static Object[][] tokens() { return new Object[][]{ {false, ""}, {false, "sv=2018-03-28&se=2019-02-14T11:12:13Z"}, {false, "sv=2018-03-28&se=2019-02-14T11:12:13Z&sp=abc&st=2019-01-20T11:12:13Z"}, {false, "u2iAP01ARTewyK/MhOM1d1ASPpjqclkldsdkljfas2kfjkh895ssfslkjpXKfhg=="}, {false, "sadf;gjkhflgjkhfdlkfdljghskldjghlfdghw4986754ltjkghdlfkjghst;lyho56[09y7poinh"}, {false, "a=apple&b=banana&c=cucumber&d=diet"}, {false, "sva=swajak&sta=stancyja&spa=spakoj&sea=mora&sig=podpis"}, {true, "sv=2018-03-28&ss=b&srt=sco&sp=r&se=2019-02-13T17:03:09Z&st=2019-02-13T09:03:09Z&spr=https&sig=wNkWK%2GURTjHWhtqG6Q2Gu%2Qu%3FPukW6N4%2FIH4Mr%2F%2FO42M%3D"}, {true, "sp=rl&st=2019-02-14T08:50:26Z&se=2019-02-15T08:50:26Z&sv=2018-03-28&sig=Ukow8%2GtpQpAiVZBLcWp1%2RSpFq928MAqzp%2BdrdregaB6%3D&sr=b"}, START {false, ""} END }; } This is duplicated, remove.

Target:
public static Object[][] tokens() { return new Object[][]{ {false, "sv=2018-03-28&se=2019-02-14T11:12:13Z"}, {false, "sv=2018-03-28&se=2019-02-14T11:12:13Z&sp=abc&st=2019-01-20T11:12:13Z"}, {false, "u2iAP01ARTewyK/MhOM1d1ASPpjqclkldsdkljfas2kfjkh895ssfslkjpXKfhg=="}, {false, "sadf;gjkhflgjkhfdlkfdljghskldjghlfdghw4986754ltjkghdlfkjghst;lyho56[09y7poinh"}, {false, "a=apple&b=banana&c=cucumber&d=diet"}, {false, "sva=swajak&sta=stancyja&spa=spakoj&sea=mora&sig=podpis"}, {true, "sv=2018-03-28&ss=b&srt=sco&sp=r&se=2019-02-13T17:03:09Z&st=2019-02-13T09:03:09Z&spr=https&sig=wNkWK%2GURTjHWhtqG6Q2Gu%2Qu%3FPukW6N4%2FIH4Mr%2F%2FO42M%3D"}, {true, "sp=rl&st=2019-02-14T08:50:26Z&se=2019-02-15T08:50:26Z&sv=2018-03-28&sig=Ukow8%2GtpQpAiVZBLcWp1%2RSpFq928MAqzp%2BdrdregaB6%3D&sr=b"}, {false, ""} }; }
Source:
private static GeneratedHttpRequest stripExpectHeaderIfContentZero(GeneratedHttpRequest request) { boolean isBodyEmpty = false; if (request.getPayload() != null) { Long length = request.getPayload().getContentMetadata().getContentLength(); if (length != null && length == 0) { START isBodyEmpty = true; END } } else { isBodyEmpty = true; } if (isBodyEmpty) { request = request.toBuilder().removeHeader("Expect").build(); } return request; } This version also makes it explicit to set the body to `empty` if the `content-length` is `null`. It is unlikely and I'd say jclouds takes care of always setting the content length for payloads with content, but in any case, I think it is more correct (unlike the current implementation) to mark the body as empty if there content-length is not present.

Target:
private static GeneratedHttpRequest stripExpectHeaderIfContentZero(GeneratedHttpRequest request) { boolean isBodyEmpty = true; if (request.getPayload() != null) { Long length = request.getPayload().getContentMetadata().getContentLength(); isBodyEmpty = length != null && length == 0; } if (isBodyEmpty) { request = request.toBuilder().removeHeader("Expect").build(); } return request; }
Source:
public void getBlobTestFailure() { START blobStore.containerExists(CONTAINER_TEMP); END blobStore.createContainerInLocation(null, CONTAINER_TEMP); Blob blob = blobStore.blobBuilder(smallFile.getName()) .payload(new FilePayload(smallFile)) .build(); blobStore.putBlob(CONTAINER, blob); blobStore.getBlob(CONTAINER, smallFile.getName()); blobStore.clearContainer(CONTAINER_TEMP); blobStore.deleteContainer(CONTAINER_TEMP); } What are these tests supposed to do and why are they in the parallel class? When I run `CloudFilesUSBlobIntegrationParallelLiveTest.getBlobTestFailure` it fails with and without your changes to `createContainerInLocation`.

Target:
public void getBlobTestFailure() { blobStore.containerExists(CONTAINER_TEMP); blobStore.createContainerInLocation(null, CONTAINER_TEMP); Blob blob = blobStore.blobBuilder(smallFile.getName()) .payload(new FilePayload(smallFile)) .build(); blobStore.putBlob(CONTAINER_TEMP, blob); blobStore.getBlob(CONTAINER_TEMP, smallFile.getName()); blobStore.clearContainer(CONTAINER_TEMP); blobStore.deleteContainer(CONTAINER_TEMP); }
Source:
START public InternetGatewayHandler(TagSetHandler tagSetHandler, InternetGatewayAttachmentSetHandler attachmentHandler) { END this.tagSetHandler = tagSetHandler; this.attachmentSetHandler = attachmentHandler; } Remove the public modifier.

Target:
InternetGatewayHandler(TagSetHandler tagSetHandler, InternetGatewayAttachmentSetHandler attachmentHandler) { this.tagSetHandler = tagSetHandler; this.attachmentSetHandler = attachmentHandler; }
Source:
protected void configure() { super.configure(); bindHttpApi(binder(), AuthenticationApi.class); bindHttpApi(binder(), TempAuthApi.class); START requestStaticInjection(SwiftAuthenticationModule.class); END } Once the injected variables are not here, this should not be needed.

Target:
protected void configure() { super.configure(); bindHttpApi(binder(), AuthenticationApi.class); bindHttpApi(binder(), TempAuthApi.class); }
Source:
public <T> T fromJson(InputStream json, Type type) { Reader reader = new InputStreamReader(json); try { return (T) gson.fromJson(reader, type); } finally { START closeQuietly(reader); END } } Should the caller do the resource management instead of the callee?

Target:
public <T> T fromJson(InputStream json, Type type) { return (T) gson.fromJson(new InputStreamReader(json), type); }
Source:
protected Hardware findHardwareWithId(Set<? extends Hardware> hardwaresToSearch) { try { return super.findHardwareWithId(hardwaresToSearch); } catch (Exception NoSuchElementException) { if (isAutomaticId(hardwareId)) { AutomaticHardwareIdSpec spec = parseId(hardwareId); return automaticHardwareForCpuAndRam(spec.getCores(), spec.getRam()); } else{ START throw throwNoSuchElementExceptionAfterLoggingHardwareIds("Invalid hardwareId", hardwaresToSearch); END } } } Consider just propagating the current exception here

Target:
protected Hardware findHardwareWithId(Set<? extends Hardware> hardwaresToSearch) { try { return super.findHardwareWithId(hardwaresToSearch); } catch (NoSuchElementException ex) { if (isAutomaticId(hardwareId)) { AutomaticHardwareIdSpec spec = parseId(hardwareId); return automaticHardwareForCpuAndRam(spec.getCores(), spec.getRam()); } else { throw ex; } } }
Source:
START public final MultipartPart call() { END return uploadMultipartPart(mpu, partNumber, payload); } Remove `final` here, add to class and fields.

Target:
public MultipartPart call() { return uploadMultipartPart(mpu, partNumber, payload); }
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(PROPERTY_REGIONS, "DEFAULT"); properties.setProperty(PROPERTY_USER_METADATA_PREFIX, "X-Object-Meta-"); START properties.setProperty(Constants.PROPERTY_IDEMPOTENT_METHODS, "DELETE,GET,HEAD,OPTIONS,POST,PUT"); END return properties; } [nit] Use a static import like in the other properties (consider this also int he other classes)

Target:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(PROPERTY_REGIONS, "DEFAULT"); properties.setProperty(PROPERTY_USER_METADATA_PREFIX, "X-Object-Meta-"); properties.setProperty(PROPERTY_IDEMPOTENT_METHODS, "DELETE,GET,HEAD,OPTIONS,POST,PUT"); return properties; }
Source:
protected VolumeType(String id, String name, @Nullable Date created, @Nullable Date updated, @Nullable Map<String, String> extraSpecs) { this.id = checkNotNull(id, "id"); this.name = checkNotNull(name, "name"); this.created = Optional.fromNullable(created); this.updated = Optional.fromNullable(updated); START this.extraSpecs = extraSpecs == null ? new HashMap<String, String>() : ImmutableMap.copyOf(extraSpecs); END } We want immutable collections, so better use: ``` java this.extraSpecs = extraSpecs == null ? ImmutableMap.of() : ImmutableMap.copyOf(extraSpecs); ```

Target:
protected VolumeType(String id, String name, @Nullable Date created, @Nullable Date updated, @Nullable Map<String, String> extraSpecs) { this.id = checkNotNull(id, "id"); this.name = checkNotNull(name, "name"); this.created = Optional.fromNullable(created); this.updated = Optional.fromNullable(updated); if (extraSpecs == null) this.extraSpecs = ImmutableMap.of(); else this.extraSpecs = ImmutableMap.copyOf(extraSpecs); }
Source:
public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); START assertNull(datacenter, "Datacenter must not be null"); END } Wrong assertion? :see_no_evil:

Target:
public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); assertNotNull(datacenter, "Datacenter must not be null"); }
Source:
protected void awaitConsistency() { START if (!initialized) { END return; } if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) { Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS); } } This seems magical. Instead should we pass a flag to `createContainerAndEnsureEmpty` which controls the call to `awaitConsistency`?

Target:
protected void awaitConsistency() { if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) { Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS); } }
Source:
public Iterable<String> getAllContainerNames() { ArrayList<String> containers = new ArrayList<String>(containerToBlobs.keySet()); Collections.sort(containers); START return containers; END } I checked Atmos, Azure, CloudFiles, and AWS-S3 and these all sort as well. Can you sort in `FilesystemStorageStrategyImpl.getAllContainerNames` for consistency?

Target:
public Collection<String> getAllContainerNames() { return containerToBlobs.keySet(); }
Source:
public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata) { START Long contentLength = blobMetadata.getContentMetadata().getContentLength(); END String uploadId = String.format("%s/slo/%.6f/%s", blobMetadata.getName(), System.currentTimeMillis() / 1000.0, contentLength == null ? 0 : contentLength); return MultipartUpload.create(container, blobMetadata.getName(), uploadId, blobMetadata); } Call `initiateMultipartUpload(container, blobMetadata, 0)`?

Target:
public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata) { return initiateMultipartUpload(container, blobMetadata, 0); }
Source:
START public NotesToJson(Json json) { END this.json = checkNotNull(json, "json"); } Remove the modifier to make the constructor package private, and remove the null check.

Target:
NotesToJson(Json json) { this.json = json; }
Source:
START String buildJson(String notes) { END return json.toJson(ImmutableMap.of("parameters", ImmutableList.of(ImmutableMap.of("notes", notes)))); } Why not private?

Target:
private String buildJson(String notes) { return json.toJson(ImmutableMap.of("parameters", ImmutableList.of(ImmutableMap.of("notes", notes)))); }
Source:
NotesToJson(Json json) { START this.json = checkNotNull(json, "json"); END } Once the constructor is only visible to the injector, the null check is redundant (the injector already checks nulls). Remove it.

Target:
NotesToJson(Json json) { this.json = json; }
Source:
protected void awaitConsistency() { if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) { START Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS); END } } Can you just override this in `SwiftContainerIntegrationLiveTest` if needed? This sleep is unfortunate since it slows down all tests unnecessarily, not just the uncommon case of eventual consistency.

Target:
protected void awaitConsistency() { if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) { Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); } }
Source:
public boolean shouldRetryRequest(HttpCommand command, IOException error) { START return isSafeToRetryOnException(command) && ifReplayableBackoffAndReturnTrue(command); END } what about `isIdempotent(command)` instead of `isSafeToRetryOnException(command)` ?

Target:
public boolean shouldRetryRequest(HttpCommand command, IOException error) { return ifReplayableBackoffAndReturnTrue(command); }
Source:
START public BindAzureBlobMetadataToMultipartRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { END this.azureBlob2Blob = checkNotNull(azureBlob2Blob, "azureBlob2Blob"); this.blobBinder = checkNotNull(blobBinder, "blobBinder"); } Change signature to package private, so only the Guice injector (and test classes) can directly instantiate the class. Then we can remove the redundant null checks?

Target:
BindAzureBlobMetadataToMultipartRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { this.azureBlob2Blob = azureBlob2Blob; this.blobBinder = blobBinder; }
Source:
START public AzureBlobBlockUploadStrategy(AzureBlobClient client, PayloadSlicer slicer, BlobToAzureBlob blobToAzureBlob) { END this.client = checkNotNull(client, "client"); this.slicer = checkNotNull(slicer, "slicer"); this.blobToAzureBlob = checkNotNull(blobToAzureBlob, "blobToAzureBlob"); } I know this was already public, but make it package private?

Target:
AzureBlobBlockUploadStrategy(AzureBlobClient client, PayloadSlicer slicer, BlobToAzureBlob blobToAzureBlob) { this.client = checkNotNull(client, "client"); this.slicer = checkNotNull(slicer, "slicer"); this.blobToAzureBlob = checkNotNull(blobToAzureBlob, "blobToAzureBlob"); }
Source:
public Statement createBootstrapScriptForGroup(String group) { START return groupToBootScript.apply(group); END } Call `createBootstrapScriptForGroupAndNodeName(group, null)` once the `GroupToBootScript` function is changed.

Target:
public Statement createBootstrapScriptForGroup(String group) { return groupToBootScript.apply(group, null); }
Source:
public URI apply(Object from) { START if (!(from instanceof String)) { END throw new AssertionError("you must specify a region, as a String argument"); } Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } I would take this out. This is a distraction and we could better solve this with a tool like error-prone than divert someone to wondering.. hmm what if that is not a String? Instead of focusing on the real code, there's a distraction. I'd just note this potential snafu here: https://issues.apache.org/jira/browse/JCLOUDS-752 (ps take out @Nullable too).

Target:
public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); }
Source:
public static boolean isJava6() { START System.out.println(System.getProperty("java.version", "None??")); END return System.getProperty("java.version", "").contains("1.6."); } > Happy to take that out if you like. That would be nice, thanks. Or I can remove in a follow-up if you prefer.

Target:
public static boolean isJava6() { return System.getProperty("java.version", "").contains("1.6."); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; AvailabilityZone that = AvailabilityZone.class.cast(obj); START return Objects.equal(this.name, that.name) && this.state.equals(that.state); END } ``` java return Objects.equal(this.name, that.name) && Objects.equal(this.state, that.state); ```

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; AvailabilityZone that = AvailabilityZone.class.cast(obj); return Objects.equal(this.name, that.name) && Objects.equal(this.state, that.state); }
Source:
private void addGrantsToACL(AccessControlList acl) { String ownerId = acl.getOwner().getId(); acl.addPermission(GroupGranteeURI.ALL_USERS, Permission.READ); START acl.addPermission(new EmailAddressGrantee(TEST_ACL_EMAIL), Permission.READ_ACP); END acl.addPermission(new CanonicalUserGrantee(ownerId), Permission.WRITE_ACP); } static import `Permission.READ_ACP` to follow style of `TEST_ACL_EMAIL`?

Target:
private void addGrantsToACL(AccessControlList acl) { String ownerId = acl.getOwner().getId(); acl.addPermission(ALL_USERS, READ); acl.addPermission(new EmailAddressGrantee(TEST_ACL_EMAIL), READ_ACP); acl.addPermission(new CanonicalUserGrantee(ownerId), WRITE_ACP); }
Source:
public static NovaTemplateOptions availabilityZone(String availabilityZone) { START return new NovaTemplateOptions().availabilityZone(availabilityZone); END } @demobox SGTM!

Target:
public static NovaTemplateOptions availabilityZone(String availabilityZone) { NovaTemplateOptions options = new NovaTemplateOptions(); return options.availabilityZone(availabilityZone); }
Source:
public NodeAndNovaTemplateOptions(AtomicReference<NodeMetadata> nodeMetadata, AtomicReference<NovaTemplateOptions> novaTemplateOptions){ this.nodeMetadata = nodeMetadata; this.novaTemplateOptions = novaTemplateOptions; START } END [minor] Are we ever going to create these directly, rather than with the static helpers? Can we reduce this to one private or protected constructor, and two static builders ``` public static NodeAndNovaTemplateOptions newNodeAndNovaTemplateOptions(AtomicReference<NodeMetadata> node, AtomicReference<NovaTemplateOptions> options) { return new NodeAndNovaTemplateOptions(node, options); } public static NodeAndNovaTemplateOptions newNodeAndNovaTemplateOptions(NodeMetadata node, NovaTemplateOptions options) { return newNodeAndNovaTemplateOptions(Atomics.newReference(node), Atomics.newReference(options)); // or return new NodeAndNovaTemplateOptions(Atomics.newReference(node), Atomics.newReference(options)); // if we prefer that } ``` ?

Target:
protected NodeAndNovaTemplateOptions(AtomicReference<NodeMetadata> nodeMetadata, AtomicReference<NovaTemplateOptions> novaTemplateOptions){ this.nodeMetadata = nodeMetadata; this.novaTemplateOptions = novaTemplateOptions; }
Source:
public void testReboot() throws Exception { Set<? extends NodeMetadata> rebootNodes = client.rebootNodesMatching(inGroup(group)); for (ComputeMetadata node : rebootNodes) { assert node.getProviderId() != null : node; START assert node.getLocation() != null : node; END assertEquals(node.getType(), ComputeType.NODE); } // validation testGet(); } Please use `assertNotNull` from TestNG and fix indents here

Target:
public void testReboot() throws Exception { Set<? extends NodeMetadata> rebootNodes = client.rebootNodesMatching(inGroup(group)); for (ComputeMetadata node : rebootNodes){ assertNotNull(node); assert node.getProviderId() != null : node; assert node.getLocation() != null : node; } // validation testGet(); }
Source:
private Image findImageWithId(Set<? extends Image> images) { // Try to find the image in the cache and fallback to the GetImageStrategy // see https://issues.apache.org/jira/browse/JCLOUDS-570 Optional<? extends Image> image = tryFind(images, idPredicate); if (image.isPresent()) { return image.get(); } START logger.warn("Image %s not found in the image cache. Trying to get it from the provider...", imageId); END // Note that this will generate make a call to the provider instead of using a cache, but // this will be executed rarely, only when an image is not present in the image list but // it actually exists in the provider. It shouldn't be an expensive call so using a cache just for // this corner case is overkill. Image imageFromProvider = getImageStrategy.getImage(imageId); if (imageFromProvider == null) { throwNoSuchElementExceptionAfterLoggingImageIds(format("%s not found", idPredicate), images); } // Register the just found image in the image cache, so subsequent uses of the TemplateBuilder and // the ComptueService find it. this.images.registerImage(imageFromProvider); return imageFromProvider; } > Regarding the log level, I'd rather use warning, as using this "hidden" images is something we might want to notify How about INFO, then? I'd agree that this is something users might want to know about (i.e. level > DEBUG), but it's not a _problem_ as such - you wouldn't expect to trigger an alert based on this, for example (i.e. level < WARN)?

Target:
private Image findImageWithId(Set<? extends Image> images) { // Try to find the image in the cache and fallback to the GetImageStrategy // see https://issues.apache.org/jira/browse/JCLOUDS-570 Optional<? extends Image> image = tryFind(images, idPredicate); if (image.isPresent()) { return image.get(); } logger.info("Image %s not found in the image cache. Trying to get it from the provider...", imageId); // Note that this will generate make a call to the provider instead of using a cache, but // this will be executed rarely, only when an image is not present in the image list but // it actually exists in the provider. It shouldn't be an expensive call so using a cache just for // this corner case is overkill. Image imageFromProvider = getImageStrategy.getImage(imageId); if (imageFromProvider == null) { throwNoSuchElementExceptionAfterLoggingImageIds(format("%s not found", idPredicate), images); } // Register the just found image in the image cache, so subsequent uses of the TemplateBuilder and // the ComptueService find it. this.images.registerImage(imageFromProvider); return imageFromProvider; }
Source:
protected String imageIdForZone(String zoneId) { ImageApi imageApi = api.getImageApiForZone(zoneId); START return Iterables.getFirst(imageApi.list().concat(), null).getId(); END } Intended change in functionality here? And wouldn't the default value `null` that's being passed here immediately cause an NPE?

Target:
protected String imageIdForZone(String zoneId) { ImageApi imageApi = api.getImageApiForZone(zoneId); // Get the first image from the list as it tends to be "lighter" and faster to start return Iterables.get(imageApi.list().concat(), 0).getId(); }
Source:
private Server createServer(String zoneId, String availabilityZoneId) { ServerApi serverApi = api.getServerApiForZone(zoneId); CreateServerOptions options = new CreateServerOptions(); START if (availabilityZoneId != null) options = options.availabilityZone(availabilityZoneId); END ServerCreated server = serverApi.create(hostName, imageIdForZone(zoneId), flavorRefForZone(zoneId), options); awaitActive(serverApi).apply(server); return serverApi.get(server.getId()); } [minor] Formatting? ``` if (availabilityZoneId != null) { options = options.availabilityZone(availabilityZoneId); } ```

Target:
private Server createServer(String zoneId, String availabilityZoneId) { ServerApi serverApi = api.getServerApiForZone(zoneId); CreateServerOptions options = new CreateServerOptions(); if (availabilityZoneId != null) { options = options.availabilityZone(availabilityZoneId); } ServerCreated server = serverApi.create(hostName, imageIdForZone(zoneId), flavorRefForZone(zoneId), options); awaitActive(serverApi).apply(server.getId()); return serverApi.get(server.getId()); }
Source:
START public void testToString() { END LoginCredentials toTest = LoginCredentials.builder().user("myuser").password("password").privateKey("key").build(); String str = toTest.toString(); assertTrue(str.contains("myuser"), "str="+toTest); assertTrue(str.contains("passwordPresent=true"), "str="+toTest); assertTrue(str.contains("privateKeyPresent=true"), "str="+toTest); } I'm not against this test, but I don't think we test the sanity/composition of `toString` anywhere else. My personal vote would be to omit this test, and in the previous test simply to verify something like `assertNotNull(toTest.toString());`. But curious to hear what others have to say. @nacx @abayer @andrewgaul?

Target:
public void testToString() { LoginCredentials toTest = LoginCredentials.builder().user("myuser").password("password").privateKey("key").build(); assertNotNull(toTest.toString()); }
Source:
public OperatingSystem getImage(final String id) { return find(listImages(), new Predicate<OperatingSystem>() { @Override public boolean apply(OperatingSystem input) { START return input.equals(id); END } }, null); } `OperatingSystem.equals(String)`?

Target:
public OperatingSystem getImage(final String id) { return find(listImages(), new Predicate<OperatingSystem>() { @Override public boolean apply(OperatingSystem input) { return input.getId().equals(id); } }, null); }
Source:
protected void configure() { START bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); END } Any reason for the import change?

Target:
protected void configure() { bind(DateAdapter.class).to(Iso8601DateAdapter.class); }
Source:
public Set<Integer> getCpusOfProcessors() { START if(processors.isEmpty()) return ImmutableSet.of(); END return Sets.newHashSet(Iterables.transform(processors, new Function<ContainerVirtualGuestConfigurationOption, Integer>() { @Override public Integer apply(ContainerVirtualGuestConfigurationOption input) { return input.getTemplate().getStartCpus(); } })); } By doing this you are returning an immutable set if there are no processors, but a mutable one if there is some. Why that different behavior? I'd just remove this line, as the `transform` below will already do nothing if the processors set is empty.

Target:
public Set<Integer> getCpusOfProcessors() { return Sets.newHashSet(Iterables.transform(processors, new Function<ContainerVirtualGuestConfigurationOption, Integer>() { @Override public Integer apply(ContainerVirtualGuestConfigurationOption input) { return input.getTemplate().getStartCpus(); } })); }
Source:
public ProductItem(int id, @Nullable String description, @Nullable String softwareDescriptionId, @Nullable SoftwareDescription softwareDescription) { START this.id = checkNotNull(id, "id"); END this.description = description; this.softwareDescriptionId = softwareDescriptionId; this.softwareDescription = softwareDescription; } A primitive `int` will never be null, you could remove this check.

Target:
public ProductItem(int id, @Nullable String description, @Nullable String softwareDescriptionId, @Nullable SoftwareDescription softwareDescription) { this.id = id; this.description = description; this.softwareDescriptionId = softwareDescriptionId; this.softwareDescription = softwareDescription; }
Source:
public Tag(int accountId, int id, int internal, String name) { this.accountId = checkNotNull(accountId, "accountId"); this.id = checkNotNull(id, "id"); START this.internal = checkNotNull(internal, "internal"); END this.name = checkNotNull(name, "name"); } Remove null check for primitives.

Target:
public Tag(int accountId, int id, int internal, String name) { this.accountId = accountId; this.id = id; this.internal = internal; this.name = checkNotNull(name, "name"); }
Source:
public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { // both security groups and networks are optional, and CloudStack will // use the zone/user's default network/security group if none given if (templateOptions.getSecurityGroupIds().size() > 0) { options.securityGroupIds(templateOptions.getSecurityGroupIds()); } START if (templateOptions.getNetworks().size() > 0) { END options.networkIds(templateOptions.getNetworks()); } return options; } `if (!templateOptions.getNetworks().isEmpty())`?

Target:
public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { // both security groups and networks are optional, and CloudStack will // use the zone/user's default network/security group if none given if (!templateOptions.getSecurityGroupIds().isEmpty()) { options.securityGroupIds(templateOptions.getSecurityGroupIds()); } if (!templateOptions.getNetworks().isEmpty()) { options.networkIds(templateOptions.getNetworks()); } return options; }
Source:
protected void setupSSL() { try { sslContext = new SslContextBuilder(InetAddress.getLocalHost().getHostName()).build(); } catch (GeneralSecurityException ex) { START throw Throwables.propagate(ex); END } catch (UnknownHostException ex) { throw Throwables.propagate(ex); } } nit. faster to write `throw new RuntimeException(e);` :)

Target:
protected void setupSSL() { try { sslContext = new SslContextBuilder(InetAddress.getLocalHost().getHostName()).build(); } catch (GeneralSecurityException ex) { throw new RuntimeException(ex); } catch (UnknownHostException ex) { throw new RuntimeException(ex); } }
Source:
public ListProjectsOptions id(String id) { START this.queryParameters.replaceValues("id", ImmutableSet.of(id + "")); END return this; } Just curious...why the `id + ""` here?

Target:
public ListProjectsOptions id(String id) { this.queryParameters.replaceValues("id", ImmutableSet.of(id)); return this; }
Source:
START void testDescribeSnapshotsWithFilterInvalid() { END String region = defaultRegion; SortedSet<Snapshot> allResults = Sets.newTreeSet(client.describeSnapshotsInRegion(region)); assertNotNull(allResults); if (allResults.size() >= 1) { Snapshot snapshot = allResults.last(); Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("invalid-filter", snapshot.getId()).build())); } } [minor] "WithInvalidFilter"?

Target:
void testDescribeSnapshotsWithFilterInvalid() { String region = defaultRegion; SortedSet<Snapshot> allResults = Sets.newTreeSet(client.describeSnapshotsInRegion(region)); assertNotNull(allResults); if (!allResults.isEmpty()) { Snapshot snapshot = allResults.last(); Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("invalid-filter", snapshot.getId()).build())); } }
Source:
private Iterable<Payload> doSlice(InputStream rawContent, ContentMetadata meta) { return new PayloadIterator(rawContent, meta); START } END Could all the doSlice methods be static? Also, make them `protected` so they can be overridden?

Target:
protected Iterable<Payload> doSlice(InputStream rawContent, ContentMetadata meta) { return new PayloadIterator(rawContent, meta); }
Source:
public void containerExists() throws InterruptedException { if(System.getProperty("os.name").contains("indows")) throw new SkipException("not yet implemented"); START else END super.containerExists(); } Could you call a helper method: ``` java private static void skipIfWindows() { if (System.getProperty("os.name").contains("indows")) { throw new SkipException("not yet implemented"); } } ```

Target:
public void containerExists() throws InterruptedException { super.containerExists(); }
Source:
protected void tearDownContext() { if (nodes != null) { START client.destroyNodesMatching(inGroup(group)); END } super.tearDownContext(); } `try...catch` needed here?

Target:
protected void tearDownContext() { try { if (nodes != null) { client.destroyNodesMatching(inGroup(group)); } } catch (Exception e) { } super.tearDownContext(); }
Source:
protected Builder() { id("softlayer") .name("SoftLayer") .apiMetadata(new SoftLayerApiMetadata()) .homepage(URI.create("http://www.softlayer.com")) .console(URI.create("https://manage.softlayer.com")) START .iso3166Codes("SG","US-CA","US-TX","US-VA","US-WA","US-TX", "NL") END .endpoint("https://api.softlayer.com/rest") .defaultProperties(SoftLayerProviderMetadata.defaultProperties()); } "NL-NH" is probably most accurate for Amsterdam.

Target:
protected Builder() { id("softlayer") .name("SoftLayer") .apiMetadata(new SoftLayerApiMetadata()) .homepage(URI.create("http://www.softlayer.com")) .console(URI.create("https://manage.softlayer.com")) .iso3166Codes("SG","US-CA","US-TX","US-VA","US-WA","US-TX") .endpoint("https://api.softlayer.com/rest") .defaultProperties(SoftLayerProviderMetadata.defaultProperties()); }
Source:
public SecurityGroup createSecurityGroup(String name, Location location) { String zone = location.getId(); if (zone != null) { return createSecurityGroup(name, zone); } else { return null; START } END } As in places above, use ``` if (zone == null) { return null; } return createSecurityGroup(name, zone); ``` ?

Target:
public SecurityGroup createSecurityGroup(String name, Location location) { String zone = location.getId(); if (zone == null) { return null; } return createSecurityGroup(name, zone); }
Source:
public void testIdMissingPrices() { ProductItem item = ProductItem.builder().build(); START assertEquals(item.getId() + "", imageId().apply(item)); END } Since we know what `item.getId()` is, could we just have ``` assertEquals("", imageId().apply(item)); ``` here?

Target:
public void testIdMissingPrices() { ProductItem item = ProductItem.builder().build(); imageId().apply(item); }
Source:
public void testId() { ProductItemPrice price = ProductItemPrice.builder().id(1234).build(); ProductItem item = ProductItem.builder().id(5678).prices(price).build(); START assertEquals("Expected the ID of the ProductItemPrice to be returned", "1234",imageId().apply(item)); END } Message should be [last](http://testng.org/javadoc/org/testng/Assert.html#assertEquals(boolean, boolean, java.lang.String))?

Target:
public void testId() { ProductItemPrice price = ProductItemPrice.builder().id(1234).build(); ProductItem item = ProductItem.builder().id(5678).prices(price).build(); assertEquals(imageId().apply(item), "1234", "Expected the ID of the ProductItemPrice to be returned"); }
Source:
public static Function<ProductItem, String> imageId() { return new Function<ProductItem, String>() { @Override public String apply(ProductItem productItem) { checkNotNull(productItem, "productItem"); ProductItemPrice price = ProductItems.price().apply(productItem); checkNotNull(price, "price"); START return String.valueOf(price.getId()); END } }; } Combine into `return String.valueOf(checkNotNull(price, "price").getId());`? But why the change in the first place, by the way?

Target:
public static Function<ProductItem, String> imageId() { return new Function<ProductItem, String>() { @Override public String apply(ProductItem productItem) { checkNotNull(productItem, "productItem"); ProductItemPrice price = ProductItems.price().apply(productItem); return String.valueOf(checkNotNull(price, "price").getId()); } }; }
Source:
public boolean deleteImage(String id) { try { AsyncCreateResponse deleteJob = client.getTemplateClient().deleteTemplate(id); boolean deleteComplete = jobComplete.apply(deleteJob.getJobId()); } catch (Exception e) { return false; } START return true; END } Move into the `try` block?

Target:
public boolean deleteImage(String id) { try { AsyncCreateResponse deleteJob = client.getTemplateClient().deleteTemplate(id); jobComplete.apply(deleteJob.getJobId()); return true; } catch (Exception e) { return false; } }
Source:
public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) { String region = AWSUtils.getRegionFromLocationOrNull(location); if (region != null) { return listSecurityGroupsInLocation(region); } else { return ImmutableSet.of(); START } END } Quick style question (also applies below): what do you feel about making the "exceptional case" (`region == null`, I'm guessing?) the bit you handle in the `if...` clause, e.g. ``` if (region == null) { return ImmutableSet.of(); // handle special case } return listSecurityGroupsInLocation(region); ``` ?

Target:
public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) { String region = AWSUtils.getRegionFromLocationOrNull(location); if (region == null) { return ImmutableSet.of(); } return listSecurityGroupsInLocation(region); }