auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void visitEnumConstant(EnumConstantTree tree) { START scan(((NewClassTree) tree.initializer()).classBody()); END } I created ticket and fixed it : https://github.com/SonarSource/sonar-java/pull/291

Target:
public void visitEnumConstant(EnumConstantTree tree) { scan(tree.initializer().classBody()); }
Source:
public final void visitNewArray(NewArrayTree tree) { scan(tree.dimensions()); scan(tree.initializers()); SymbolicValue value = createSymbolicInstanceValue(); for (ExecutionState executionState : currentStates) { START for (int i = tree.dimensions().size() + tree.initializers().size() - 1; i >= 0; i -= 1) { END executionState.pop(); } executionState.push(value); } } @merciesa maybe matter of taste, but why not `i--` instead of `i -= 1`?

Target:
public final void visitNewArray(NewArrayTree tree) { scan(tree.dimensions()); scan(tree.initializers()); SymbolicValue value = createSymbolicInstanceValue(); for (ExecutionState executionState : currentStates) { for (int i = tree.dimensions().size() + tree.initializers().size() - 1; i >= 0; i--) { executionState.pop(); } executionState.push(value); } }
Source:
public void visitMethod(MethodTree tree) { boolean isUnitTest = isUnitTest(tree); inUnitTest.push(isUnitTest); START methodContainsAssertion.push(Boolean.FALSE); END super.visitMethod(tree); inUnitTest.pop(); if (isUnitTest && !methodContainsAssertion.pop()) { context.addIssue(tree, this, "Add at least one assertion to this test case."); } } matter of taste but why not rely on autoboxing ?

Target:
public void visitMethod(MethodTree tree) { boolean isUnitTest = isUnitTest(tree); inUnitTest.push(isUnitTest); methodContainsAssertion.push(false); super.visitMethod(tree); inUnitTest.pop(); if (isUnitTest && !methodContainsAssertion.pop()) { context.addIssue(tree, this, "Add at least one assertion to this test case."); } }
Source:
public State merge(State s) { if (s instanceof Null) { return this; } START if(!(s instanceof CloseableState)) { END throw new IllegalStateException("Merging incompatible states"); } return s; } Why only throwing this exception for the `Closed` state and not for every `CloseableState`? (same remark for the `Unlocked` state of `LockState`)

Target:
public State merge(State s) { return s; }
Source:
private void ignoreVariable(VariableTree variableTree) { Symbol symbol = variableTree.symbol(); if (isCloseableOrAutoCloseableSubtype(symbol.type())) { START executionState.markValueAs(symbol, new CloseableState.Ignored(variableTree)); END } } It is useless to test before marking as ignored, as only the symbol which are already known could be marked. Note that to be known the symbol have to pass the "isSymbolRelevant" test, which is equivalent.

Target:
private void ignoreVariable(VariableTree variableTree) { executionState.markValueAs(variableTree.symbol(), new CloseableState.Ignored(variableTree)); }
Source:
public void visitNode(Tree tree) { Symbol.TypeSymbol symbol = ((ClassTree) tree).symbol(); START if (symbol.owner().isTypeSymbol() && symbol.isStatic()) { END addIssue(tree, "Remove this redundant \"static\" qualifier."); } } This check should not rely on semantic !!!

Target:
public void visitNode(Tree tree) { if (isStatic((ClassTree) tree)) { addIssue(tree, "Remove this redundant \"static\" qualifier."); } }
Source:
public void visitReturnStatement(ReturnStatementTree tree) { START super.visitReturnStatement(tree); END executionState.checkUsageOfClosables(tree.expression()); } I am really doubting about this call to super: What about something like : ``` return new Foo() { //some stuff closing }; ``` The new ClassTree will be checked twice, once with the override of visitNewClass (via the call to super) and once with the checkUsageOfCloseable of the expression of the return statement.

Target:
public void visitReturnStatement(ReturnStatementTree tree) { executionState.checkUsageOfClosables(tree.expression()); }
Source:
ParametrizedTypeType(Symbol.TypeSymbol symbol, Map<TypeVariableType, Type> typeSubstitution) { super(symbol); this.rawType = symbol.getType(); this.typeSubstitution = typeSubstitution; START if (rawType.isTagged(UNKNOWN)) { END // force unknown instead of keeping CLASS this.tag = UNKNOWN; } } I don't think this should be done at this level. I tend to think that when constructing a ParametrizedTypeType using the ParametrizedTypeCache we should return the unknown type altogether rather than an unknown ParametrizedTypeType which can (IMO) lead to confusion.

Target:
ParametrizedTypeType(Symbol.TypeSymbol symbol, Map<TypeVariableType, Type> typeSubstitution) { super(symbol); this.rawType = symbol.getType(); this.typeSubstitution = typeSubstitution; }
Source:
private String getTypeName(Tree tree) { Type type = ((AbstractTypedTree) tree).getSymbolType(); START TypeSymbol symbol = type.getSymbol(); END String name = symbol.getName(); if (name.isEmpty()) { name = getAnonymousClassTypeName(symbol); } return name; } To allow further reuse I would split this into a method getting a name from TypeSymbol.

Target:
private String getTypeName(Tree tree) { Type type = ((AbstractTypedTree) tree).getSymbolType(); String name = getTypeName(type); if (name.isEmpty()) { name = getAnonymousClassTypeName(type.getSymbol()); } return name; }
Source:
private boolean isField(Tree tree) { START return tree.is(Kind.VARIABLE) && !((VariableTree) tree).modifiers().modifiers().containsAll(Lists.newArrayList(Modifier.FINAL, Modifier.STATIC)); END } What about a static member ? class A extends B { public static String staticMember; }

Target:
private boolean isField(Tree tree) { return tree.is(Kind.VARIABLE) && !((VariableTree) tree).modifiers().modifiers().contains(Modifier.STATIC); }
Source:
public void visitNode(Tree tree) { Long identityElement = getBitwiseOperationIdentityElement(tree); Long evaluatedExpression = evaluateExpression(getExpression(tree)); START if (evaluatedExpression != null && evaluatedExpression == identityElement) { END addIssue(tree, "Remove this silly bit operation."); } } use equals instead of ==

Target:
public void visitNode(Tree tree) { Long identityElement = getBitwiseOperationIdentityElement(tree); Long evaluatedExpression = evaluateExpression(getExpression(tree)); if (evaluatedExpression != null && identityElement.equals(evaluatedExpression)) { addIssue(tree, "Remove this silly bit operation."); } }
Source:
private boolean isFinalizeDeclaration(MethodTree tree) { START return hasSemantic() && isMethodNamedFinalize(tree) && isOverriding(tree) && hasNoParameters(tree); END } Check for overriding is uncessary.

Target:
private boolean isFinalizeDeclaration(MethodTree tree) { return hasSemantic() && isMethodNamedFinalize(tree) && hasNoParameters(tree); }
Source:
public void visitReturnStatement(ReturnStatementTree tree) { if (isWithinCallingMethodBody(tree) && returnsIntegerMinValue(tree.expression())) { addIssue(tree, "Simply return -1"); } START super.visitReturnStatement(tree); END } uncessary call to super. No need to visit further.

Target:
public void visitReturnStatement(ReturnStatementTree tree) { if (returnsIntegerMinValue(tree.expression())) { addIssue(tree, "Simply return -1"); } }
Source:
default ScheduledExecutorService getTimerExecutor() { START return Executors.newScheduledThreadPool(1); END } The default impl is disputable. Each invocation of this method would result in new pool and the caller would be responsible for shutdown etc. I think we should rather throw unsupported operation exception or something like that.

Target:
default ScheduledExecutorService getTimerExecutor() { return null; }
Source:
public ScsiController build() { START disks(disks() != null ? ImmutableList.copyOf(disks()) : new ArrayList<ScsiDisk>()); END return autoBuild(); } Enforce an immutable list in all cases.

Target:
public ScsiController build() { disks(disks() != null ? ImmutableList.copyOf(disks()) : null); return autoBuild(); }
Source:
public void testListCustomerImages() { FluentIterable<CustomerImage> customerImages = api.getServerImageApi().listCustomerImages().concat(); assertNotNull(customerImages); START customerImages.anyMatch(new Predicate<CustomerImage>() { END @Override public boolean apply(CustomerImage input) { return input.id().equals(cloneImageId); } }); } `assertTrue(customerImages.anyMatch(new Predicate<CustomerImage>() {`

Target:
public void testListCustomerImages() { FluentIterable<CustomerImage> customerImages = api.getServerImageApi().listCustomerImages().concat(); assertNotNull(customerImages); assertTrue(customerImages.anyMatch(new Predicate<CustomerImage>() { @Override public boolean apply(CustomerImage input) { return input.id().equals(cloneImageId); } })); }
Source:
public static IpProtocol fromValue(String value) { Optional<IpProtocol> ipProtocol = Enums.getIfPresent(IpProtocol.class, value.toUpperCase()); START checkArgument(ipProtocol.isPresent(), "Expected one of %s but was %s", Joiner.on(',').join(Permission.Policy.values()), value); END return ipProtocol.get(); } `IpProtocol.values()`

Target:
public static IpProtocol fromValue(String value) { Optional<IpProtocol> ipProtocol = Enums.getIfPresent(IpProtocol.class, value.toUpperCase()); checkArgument(ipProtocol.isPresent(), "Expected one of %s but was %s", Joiner.on(',').join(IpProtocol.values()), value); return ipProtocol.get(); }
Source:
public static NicType fromValue(String value) { Optional<NicType> nicType = Enums.getIfPresent(NicType.class, value.toUpperCase()); START checkArgument(nicType.isPresent(), "Expected one of %s but was %s", Joiner.on(',').join(Policy.values()), value); END return nicType.get(); } `NicType.values()`

Target:
public static NicType fromValue(String value) { Optional<NicType> nicType = Enums.getIfPresent(NicType.class, value.toUpperCase()); checkArgument(nicType.isPresent(), "Expected one of %s but was %s", Joiner.on(',').join(NicType.values()), value); return nicType.get(); }
Source:
private void validateInput(final String input, int maxLength) { checkNotNull(input); checkState(input.length() <= maxLength, String.format("input must be <= %d chars", maxLength)); START checkState(Iterables.any(FORBIDDEN_PREFIX, new Predicate<String>() { END @Override public boolean apply(@Nullable String input) { return input.startsWith(input); } }), "Cannot starts with " + Iterables.toString(FORBIDDEN_PREFIX)); } Negate the condition, otherwise you are failing if the value is correct.

Target:
private void validateInput(final String input, int maxLength) { checkNotNull(input); checkState(input.length() <= maxLength, String.format("input must be <= %d chars", maxLength)); checkState(!Iterables.any(FORBIDDEN_PREFIX, new Predicate<String>() { @Override public boolean apply(@Nullable String input) { return input.startsWith(input); } }), "Cannot starts with " + Iterables.toString(FORBIDDEN_PREFIX)); }
Source:
START private AliyunDateAdapter(DateService dateService) { END super(dateService); } Remove the `private` modifier so you can properly test it.

Target:
AliyunDateAdapter(DateService dateService) { super(dateService); }
Source:
START public void testListImagesReturns404() throws InterruptedException { END server.enqueue(response404()); Iterable<Image> images = api.imageApi().list(Regions.EU_CENTRAL_1.getName()).concat(); assertTrue(isEmpty(images)); assertEquals(server.getRequestCount(), 1); } We should also verify that we're sending the page size parameter.

Target:
public void testListImagesReturns404() { server.enqueue(response404()); Iterable<Image> images = api.imageApi().list(Regions.EU_CENTRAL_1.getName()).concat(); assertTrue(isEmpty(images)); assertEquals(server.getRequestCount(), 1); }
Source:
START public OperatingSystemToOperatingSystem(final OperatingSystemToOsFamily operatingSystemToOsFamily) { END this.operatingSystemToOsFamily = operatingSystemToOsFamily; } Add the `@Inject` annotation and remove the public modifier from the constructor to make it package private ([background](https://github.com/google/guice/wiki/KeepConstructorsHidden)).

Target:
OperatingSystemToOperatingSystem(final OperatingSystemToOsFamily operatingSystemToOsFamily) { this.operatingSystemToOsFamily = operatingSystemToOsFamily; }
Source:
public void cleanup() { START if (!tagKeyId.isEmpty()) { END api().deleteTagKey(tagKeyId); } } Unlikely, but this could throw an NPE. Better check for `null` too.

Target:
public void cleanup() { if (tagKeyId != null && !tagKeyId.isEmpty()) { api().deleteTagKey(tagKeyId); } }
Source:
START public ServerToServerWithExternalIp(DimensionDataCloudControlApi api) { END this.api = checkNotNull(api, "api"); } Remove the public modifier.

Target:
ServerToServerWithExternalIp(DimensionDataCloudControlApi api) { this.api = checkNotNull(api, "api"); }
Source:
START public CleanupServer(final DimensionDataCloudControlApi api, final Timeouts timeouts) { END this.api = api; this.timeouts = timeouts; } Remove the public modifier

Target:
CleanupServer(final DimensionDataCloudControlApi api, final Timeouts timeouts) { this.api = api; this.timeouts = timeouts; }
Source:
public void testGet() { Vault vaultFound = api().getVault(vaultName); START assertTrue(!vaultFound.name().isEmpty()); END } Better `assertNotNull(vaultFound)` to avoid an unexpected NPE?

Target:
public void testGet() { Vault vaultFound = api().getVault(vaultName); assertNotNull(vaultFound); }
Source:
public void testList() { for (Vault vault : api().listVaults()) { assertNotNull(vault.name()); VaultProperties props = vault.properties(); START assertNotNull(props); END } } If properties are not nullable there is no need to check this. Deserialization will already fail.

Target:
public void testList() { for (Vault vault : api().listVaults()) { assertTrue(!vault.name().isEmpty()); } }
Source:
public void setup() { super.setup(); // Providing system properties for specifying the required Azure KeyVault configurations for Live tests // They have to be externally provided, because azurecompute-arm doesn't support creating KeyVaults yet // // TODO Replace the used configurations once full KeyVault implementation is added to azurecompute-arm vaultResourceGroup = System.getProperty("test.azurecompute-arm.vault.resource.group"); vaultName = System.getProperty("test.azurecompute-arm.vault.name"); vaultCertificateUrl = System.getProperty("test.azurecompute-arm.vault.certificate.url"); START tenantId = System.getProperty("test.azurecompute-arm.tenantId"); END } Change to: `tenantId = injector.getInstance(Key.get(String.class, Tenant.class));`

Target:
public void setup() { super.setup(); // Providing system properties for specifying the required Azure KeyVault configurations for Live tests // They have to be externally provided, because azurecompute-arm doesn't support creating KeyVaults yet // // TODO Replace the used configurations once full KeyVault implementation is added to azurecompute-arm vaultResourceGroup = System.getProperty("test.azurecompute-arm.vault.resource.group"); vaultName = System.getProperty("test.azurecompute-arm.vault.name"); vaultCertificateUrl = System.getProperty("test.azurecompute-arm.vault.certificate.url"); }
Source:
public void testDelete() { boolean result = api().deleteVault(vaultName); assertTrue(result); START Object[] args = { resourceGroupName, vaultName, true }; END checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName), "vault was not deleted before timeout"); } Unused args?

Target:
public void testDelete() { boolean result = api().deleteVault(vaultName); assertTrue(result); checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName), "vault was not deleted before timeout"); }
Source:
public void testDelete() throws InterruptedException { server.enqueue(response202WithHeader()); final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup); START vmssAPI.delete(vmssname); END assertSent(server, "DELETE", "/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/" + "Microsoft.Compute" + "/VirtualMachineScaleSets/jclouds-vmssname?api-version=2017-03-30"); } Verify that returns a non-null URI.

Target:
public void testDelete() throws InterruptedException { server.enqueue(response202WithHeader()); final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup); assertNotNull(vmssAPI.delete(vmssname)); assertSent(server, "DELETE", "/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/" + "Microsoft.Compute" + "/VirtualMachineScaleSets/jclouds-vmssname?api-version=2017-03-30"); }
Source:
protected void configure() { START bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); END super.configure(); } Call `super` first.

Target:
protected void configure() { super.configure(); bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); }
Source:
START public ParseResponse(Json json, String propertyName) { END this.json = json; this.propertyName = propertyName; } Make this protected?

Target:
protected ParseResponse(Json json, String propertyName) { this.json = json; this.propertyName = propertyName; }
Source:
protected Function<Object, IterableWithMarker<OperatingSystem>> markerToNextForArg0( final Optional<Object> arg) { return new Function<Object, IterableWithMarker<OperatingSystem>>() { @Override public IterableWithMarker<OperatingSystem> apply(Object input) { PaginationOptions paginationOptions = PaginationOptions.class.cast(input); START return api.getInfrastructureApi().listOperatingSystems(arg.toString(), paginationOptions); END } }; } Take care! `arg.get().toString()`. Otherwise you're passing the `Optional` object.

Target:
protected Function<Object, IterableWithMarker<OperatingSystem>> markerToNextForArg0( final Optional<Object> arg) { return new Function<Object, IterableWithMarker<OperatingSystem>>() { @Override public IterableWithMarker<OperatingSystem> apply(Object input) { PaginationOptions paginationOptions = PaginationOptions.class.cast(input); return api.getInfrastructureApi().listOperatingSystems(arg.get().toString(), paginationOptions); } }; }
Source:
protected void configure() { START Names.bindProperties(binder(), Collections.singletonMap(Constants.PROPERTY_PRETTY_PRINT_PAYLOADS, "true")); END bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); } There is no need to bind this. It is already bound to the context and users will be able to configure this property when creating it. Let's remove this line.

Target:
protected void configure() { }
Source:
START public OrganisationIdFilter(@Memoized Supplier<String> organisationIdSupplier) { END this.organisationIdSupplier = organisationIdSupplier; } Remove the `public` modifier. It is a best-practice in Guice to make all injection constructors visible just to the default scope.

Target:
OrganisationIdFilter(@Memoized Supplier<String> organisationIdSupplier) { this.organisationIdSupplier = organisationIdSupplier; }
Source:
START public String injectOrganisationId(String path) { END String organisationId = organisationIdSupplier.get(); List<String> list = Lists.newArrayList(Splitter.on("/").split(path)); if (list.size() > ORGANIZATION_ID_INDEX && !list.get(ORGANIZATION_ID_INDEX).equals(organisationId)) { list.add(ORGANIZATION_ID_INDEX, organisationId); } return Joiner.on("/").join(list); } Don't make it public if it is just visible for testing. Remove the public modifier and leave it in default scope.

Target:
String injectOrganisationId(String path) { String organisationId = organisationIdSupplier.get(); List<String> list = Lists.newArrayList(Splitter.on("/").split(path)); if (list.size() > ORGANIZATION_ID_INDEX && !list.get(ORGANIZATION_ID_INDEX).equals(organisationId)) { list.add(ORGANIZATION_ID_INDEX, organisationId); } return Joiner.on("/").join(list); }
Source:
public void testCaasUrl() { START Supplier<String> orgIdSupplier = new OrganisationIdForAccount(api); END String expectedPath = "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/server/0896551e-4fe3-4450-a627-ad5548e7e83a?clone=trevor-test2&desc=trevor-description2"; String updatedPath = new OrganisationIdFilter(orgIdSupplier).injectOrganisationId( "/caas/2.4/server/0896551e-4fe3-4450-a627-ad5548e7e83a?clone=trevor-test2&desc=trevor-description2"); assertEquals(updatedPath, expectedPath); } You can just return a mock supplier for this test: `Suppliers.ofInstance("6ac1e746-b1ea-4da5-a24e-caf1a978789d/")`. This way you don't need the overhead of starting a mock server, creating the context, etc.

Target:
public void testCaasUrl() { String expectedPath = "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/server/0896551e-4fe3-4450-a627-ad5548e7e83a?clone=trevor-test2&desc=trevor-description2"; String updatedPath = new OrganisationIdFilter(orgIdSupplier).injectOrganisationId( "/caas/2.4/server/0896551e-4fe3-4450-a627-ad5548e7e83a?clone=trevor-test2&desc=trevor-description2"); assertEquals(updatedPath, expectedPath); }
Source:
public void copyTo(TemplateOptions to) { super.copyTo(to); if (to instanceof AzureTemplateOptions) { AzureTemplateOptions eTo = AzureTemplateOptions.class.cast(to); eTo.virtualNetworkName(virtualNetworkName); eTo.subnetId(subnetId); eTo.blob(blob); eTo.availabilitySet(availabilitySet); eTo.availabilitySet(availabilitySetName); START if (!dataDisks.isEmpty()) { END eTo.dataDisks(dataDisks); } } } Redundant check. We allow passing an empty list.

Target:
public void copyTo(TemplateOptions to) { super.copyTo(to); if (to instanceof AzureTemplateOptions) { AzureTemplateOptions eTo = AzureTemplateOptions.class.cast(to); eTo.virtualNetworkName(virtualNetworkName); eTo.subnetId(subnetId); eTo.blob(blob); eTo.availabilitySet(availabilitySet); eTo.availabilitySet(availabilitySetName); eTo.dataDisks(dataDisks); } }
Source:
ImageSupplier(Function<Collection<B>, Collection<B>> outdatedBoxesFilter, VagrantBoxApiFacade.Factory<B> cliFactory, Function<B, Image> boxToImage) { this.outdatedBoxesFilter = checkNotNull(outdatedBoxesFilter, "outdatedBoxesFilter"); this.cliFactory = checkNotNull(cliFactory, "cliFactory"); START this.boxToImage = checkNotNull(boxToImage, "boxToImage"); END } Remove the redundant null checks.

Target:
ImageSupplier(Function<Collection<B>, Collection<B>> outdatedBoxesFilter, VagrantBoxApiFacade.Factory<B> cliFactory, Function<B, Image> boxToImage) { this.outdatedBoxesFilter = outdatedBoxesFilter; this.cliFactory = cliFactory; this.boxToImage = boxToImage; }
Source:
VagrantExistingMachines(@Named(VagrantConstants.JCLOUDS_VAGRANT_HOME) String home, MachineConfig.Factory machineConfigFactory, Supplier<Collection<Image>> imageLister, Supplier<? extends Map<String, Hardware>> hardwareSupplier) { this.home = new File(checkNotNull(home, "home")); this.machineConfigFactory = checkNotNull(machineConfigFactory, "machineConfigFactory"); this.imageLister = checkNotNull(imageLister, "imageLister"); START this.hardwareSupplier = checkNotNull(hardwareSupplier, "hardwareSupplier"); END } Remove the redundant null checks.

Target:
VagrantExistingMachines(@Named(VagrantConstants.JCLOUDS_VAGRANT_HOME) String home, MachineConfig.Factory machineConfigFactory, Supplier<Collection<Image>> imageLister, Supplier<? extends Map<String, Hardware>> hardwareSupplier) { this.home = new File(home); this.machineConfigFactory = machineConfigFactory; this.imageLister = imageLister; this.hardwareSupplier = hardwareSupplier; }
Source:
START public ProfitBricksImageExtension(ProfitBricksApi client, END @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, @Memoized Supplier<Set<? extends Location>> locations, @Named(POLL_PREDICATE_SNAPSHOT) Predicate<String> snapshotAvailablePredicate, Trackables trackables) { this.client = checkNotNull(client, "client"); this.userExecutor = checkNotNull(userExecutor, "userExecutor"); this.locations = checkNotNull(locations, "locations"); this.snapshotAvailablePredicate = checkNotNull(snapshotAvailablePredicate, "snapshotAvailablePredicate"); this.trackables = checkNotNull(trackables); } Remove the public modifier, and all null checks, since the injector already enforces that.

Target:
ProfitBricksImageExtension(ProfitBricksApi client, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, @Memoized Supplier<Set<? extends Location>> locations, @Named(POLL_PREDICATE_SNAPSHOT) Predicate<String> snapshotAvailablePredicate, Trackables trackables) { this.client = client; this.userExecutor = userExecutor; this.locations = locations; this.snapshotAvailablePredicate = snapshotAvailablePredicate; this.trackables = trackables; }
Source:
public ImageTemplate buildImageTemplateFromNode(String name, String id) { DataCenterAndId datacenterAndId = DataCenterAndId.fromSlashEncoded(id); Server server = client.serverApi().getServer(datacenterAndId.getDataCenter(), datacenterAndId.getId()); if (server == null) { START throw new NoSuchElementException("Cannot find server with id: " + id); END } CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); return template; } Better throw an `IllegalArgumentException`.

Target:
public ImageTemplate buildImageTemplateFromNode(String name, String id) { DataCenterAndId datacenterAndId = DataCenterAndId.fromSlashEncoded(id); Server server = client.serverApi().getServer(datacenterAndId.getDataCenter(), datacenterAndId.getId()); if (server == null) { throw new IllegalArgumentException("Cannot find server with id: " + id); } CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); return template; }
Source:
DeviceToNodeMetadata(PlanToHardware planToHardware, OperatingSystemToImage operatingSystemToImage, FacilityToLocation facilityToLocation, Function<Device.State, NodeMetadata.Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention) { START this.planToHardware = checkNotNull(planToHardware, "planToHardware cannot be null"); END this.operatingSystemToImage = checkNotNull(operatingSystemToImage, "operatingSystemToImage cannot be null"); this.facilityToLocation = checkNotNull(facilityToLocation, "facilityToLocation cannot be null"); this.toPortableStatus = checkNotNull(toPortableStatus, "toPortableStatus cannot be null"); this.groupNamingConvention = checkNotNull(groupNamingConvention, "groupNamingConvention cannot be null") .createWithoutPrefix(); } No need for null checks in the injection constructors.

Target:
DeviceToNodeMetadata(PlanToHardware planToHardware, OperatingSystemToImage operatingSystemToImage, FacilityToLocation facilityToLocation, Function<Device.State, NodeMetadata.Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention) { this.planToHardware = planToHardware; this.operatingSystemToImage = operatingSystemToImage; this.facilityToLocation = facilityToLocation; this.toPortableStatus = toPortableStatus; this.groupNamingConvention = groupNamingConvention.createWithoutPrefix(); }
Source:
protected ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) { START this.api = checkNotNull(api, "api"); END this.hrefToOptions = hrefToOptions; } Remove the redundant check and the protected modifier from the constructor

Target:
ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) { this.api = api; this.hrefToOptions = hrefToOptions; }
Source:
public AddApiVersionToRequest(@ApiVersion String apiVersion) { START this.apiVersion = checkNotNull(apiVersion, "apiVersion"); END } Remove the public modifier from the constructor and remove the null check.

Target:
AddApiVersionToRequest(@ApiVersion String apiVersion) { this.apiVersion = apiVersion; }
Source:
protected Builder() { id("oneandone") .name("OneAndOne REST Compute") .apiMetadata(new OneAndOneApiMetadata()) .homepage(URI.create("https://cloudpanel-api.1and1.com")) .console(URI.create("https://account.1and1.com")) START .iso3166Codes("de", "us", "es", "gb") END .endpoint("https://cloudpanel-api.1and1.com/v1/") .defaultProperties(OneAndOneProviderMetadata.defaultProperties()); } This should contain the iso codes, not the region id.

Target:
protected Builder() { id("oneandone") .name("OneAndOne REST Compute") .apiMetadata(new OneAndOneApiMetadata()) .homepage(URI.create("https://cloudpanel-api.1and1.com")) .console(URI.create("https://account.1and1.com")) .endpoint("https://cloudpanel-api.1and1.com/v1/") .defaultProperties(OneAndOneProviderMetadata.defaultProperties()); }
Source:
public boolean apply(Server server) { checkNotNull(server, "Server"); server = api.serverApi().get(server.id()); if ((server.status().state() != Types.ServerState.POWERED_OFF && server.status().state() != Types.ServerState.POWERED_ON) || server.status().percent() != 0) { return false; } else { return true; START } END } Try to avoid conditionals like `if (condition) return true else return false`. Just `return condition`.

Target:
public boolean apply(Server server) { checkNotNull(server, "Server"); server = api.serverApi().get(server.id()); return !((server.status().state() != Types.ServerState.POWERED_OFF && server.status().state() != Types.ServerState.POWERED_ON) || server.status().percent() != 0); }
Source:
public void testList() { dataCenters = dataCenterApi().list(); currentDataCenter = dataCenters.get(0); START assertNotNull(dataCenters); END assertFalse(dataCenters.isEmpty()); Assert.assertTrue(dataCenters.size() > 0); } Check this before calling get.

Target:
public void testList() { dataCenters = dataCenterApi().list(); assertNotNull(dataCenters); currentDataCenter = dataCenters.get(0); assertFalse(dataCenters.isEmpty()); Assert.assertTrue(dataCenters.size() > 0); }
Source:
public void testList() { appliances = serverApplianceApi().list(); currentAppliance = appliances.get(0); START Assert.assertTrue(appliances.size() > 0); END } Assert this before calling get.

Target:
public void testList() { appliances = serverApplianceApi().list(); Assert.assertTrue(appliances.size() > 0); currentAppliance = appliances.get(0); }
Source:
public void testList() { List<MonitoringCenter> result = monitoringCenterApi().list(); START assertNotNull(result); END } Verify that at least returns one element?

Target:
public void testList() { List<MonitoringCenter> result = monitoringCenterApi().list(); assertNotNull(result); Assert.assertTrue(result.size() >= 1); }
Source:
public void testListWithOption() { GenericQueryOptions options = new GenericQueryOptions(); options.options(1, 1, null, null, null); List<MonitoringCenter> resultWithQuery = monitoringCenterApi().list(options); START assertNotNull(resultWithQuery); END } Same here, verify that at least one element is returned?

Target:
public void testListWithOption() { GenericQueryOptions options = new GenericQueryOptions(); options.options(1, 1, null, null, null); List<MonitoringCenter> resultWithQuery = monitoringCenterApi().list(options); assertNotNull(resultWithQuery); Assert.assertTrue(resultWithQuery.size() >= 1); }
Source:
public ZipInputStream apply(VPNConfig input) { try { byte[] decoded = base64().decode(input.content()); ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(decoded)); return zipStream; } catch (Exception ex) { START Logger.getLogger(VPNConfigParser.class.getName()).log(Level.SEVERE, null, ex); END return null; } } Don't use java logging. jclouds provides a logging abstraction that allows users to configure their preferred logging framework. In order to get the right log, just declare the following class variable of type `org.jclouds.logging.Logger`: ``` java @Resource protected Logger logger = Logger.NULL; ``` This will configure a null logger by default, but use the one configured by users providing a logging module when creating the jclouds context.

Target:
public ZipInputStream apply(VPNConfig input) { byte[] decoded = base64().decode(input.content()); ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(decoded)); return zipStream; }
Source:
public void testList() { publicIps = publicIpApi().getList(); assertNotNull(publicIps); assertFalse(publicIps.isEmpty()); START Assert.assertTrue(publicIps.size() > 0); END } This is redundant.

Target:
public void testList() { publicIps = publicIpApi().list(); Assert.assertTrue(publicIps.size() > 0); }
Source:
public static void deleteContainerIfExists(String storage, String key, String containerName) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storage, key) .buildApi(AzureBlobClient.class); try { azureBlob.deleteContainer(containerName); } catch (Exception e) { e.printStackTrace(); START } END finally { Closeables2.closeQuietly(azureBlob); } } This will not fail if the container does not exist (see [here](https://github.com/jclouds/jclouds/blob/master/providers/azureblob/src/main/java/org/jclouds/azureblob/AzureBlobClient.java#L196])). Should we better not catch any exception, leave just the try/finally and let the method fail if the container can't be deleted?

Target:
public static void deleteContainerIfExists(String storage, String key, String containerName) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storage, key) .buildApi(AzureBlobClient.class); try { azureBlob.deleteContainer(containerName); } finally { Closeables2.closeQuietly(azureBlob); } }
Source:
START public void testListAccessCredentials() throws InterruptedException { END List<SharedStorageAccess> access = sharedStorageApi().getAccessCredentials(); assertNotNull(access); assertTrue(access.size() > 0); } Remove the `InterruptedException` from the signature.

Target:
public void testListAccessCredentials() { List<SharedStorageAccess> access = sharedStorageApi().getAccessCredentials(); assertNotNull(access); assertTrue(access.size() > 0); }
Source:
START public void testChangePassword() throws InterruptedException { END List<SharedStorageAccess> response = sharedStorageApi().changePassword(SharedStorageAccess.UpdateSharedStorageAccess.create("Test123!")); assertNotNull(response); } Remove the `InterruptedException` from the signature.

Target:
public void testChangePassword() { List<SharedStorageAccess> response = sharedStorageApi().changePassword(SharedStorageAccess.UpdateSharedStorageAccess.create("Test123!")); assertNotNull(response); }
Source:
public ProfitBricksTemplateBuilderLiveTest() { this.provider = "profitbricks-rest"; System.setProperty("http.proxyHost", "127.0.0.1"); System.setProperty("https.proxyHost", "127.0.0.1"); System.setProperty("http.proxyPort", "8888"); System.setProperty("https.proxyPort", "8888"); System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_73\\jre\\lib\\security\\FiddlerKeystore"); START System.setProperty("javax.net.ssl.trustStorePassword", "testme"); END } Remove all these properties.

Target:
public ProfitBricksTemplateBuilderLiveTest() { this.provider = "profitbricks-rest"; }
Source:
public static String[] decodeFieldsFromUniqueId(final String id) { final String[] parts = checkNotNull(id, "id").split("/"); START return parts; END } Just `return checkNotNull(id, "id").split("/");`

Target:
public static String[] decodeFieldsFromUniqueId(final String id) { return checkNotNull(id, "id").split("/"); }
Source:
private List<VMImage> listImagesByLocation(String location) { final List<VMImage> osImages = Lists.newArrayList(); Iterable<String> publishers = Splitter.on(',').trimResults().omitEmptyStrings().split(this.azureComputeConstants.azureImagePublishers()); for (String publisher : publishers) { START publisher = publisher.trim(); END getImagesFromPublisher(publisher, osImages, location); } return osImages; } I don't think you need to trim again

Target:
private List<VMImage> listImagesByLocation(String location) { final List<VMImage> osImages = Lists.newArrayList(); Iterable<String> publishers = Splitter.on(',').trimResults().omitEmptyStrings().split(this.azureComputeConstants.azureImagePublishers()); for (String publisher : publishers) { getImagesFromPublisher(publisher, osImages, location); } return osImages; }
Source:
public HttpRequest filter(HttpRequest request) throws HttpException { START checkNotNull(authToken.identity, "credential returned null"); END return request.toBuilder().replaceHeader(AuthHeaders.AUTH_TOKEN, TokenBased()).build(); } Move this to the constructor.

Target:
public HttpRequest filter(HttpRequest request) throws HttpException { return request.toBuilder().replaceHeader(AuthHeaders.AUTH_TOKEN, authToken.identity).build(); }
Source:
public void testList() { servers = serverApi().getList(); assertNotNull(servers); assertFalse(servers.isEmpty()); START Assert.assertTrue(servers.size() > 0); END } This is redundant.

Target:
public void testList() { servers = serverApi().list(); assertNotNull(servers); Assert.assertTrue(servers.size() > 0); }
Source:
public void testListWithOption() { GenericQueryOptions options = new GenericQueryOptions(); options.options(0, 0, null, "test", null); List<Server> serversWithQuery = serverApi().getList(options); assertNotNull(serversWithQuery); assertFalse(serversWithQuery.isEmpty()); START Assert.assertTrue(serversWithQuery.size() > 0); END } Remove this redundant assertion and all similar ones.

Target:
public void testListWithOption() { GenericQueryOptions options = new GenericQueryOptions(); options.options(0, 0, null, "test", null); List<Server> serversWithQuery = serverApi().list(options); assertNotNull(serversWithQuery); Assert.assertTrue(serversWithQuery.size() > 0); }
Source:
public void testListHardwareHdds() throws InterruptedException { assertNodeAvailable(currentServer); //give time for harddisk to be added START Thread.sleep(60000); END List<Hdd> hdds = serverApi().listHdds(currentServer.id()); for (Hdd hdd : hdds) { if (!hdd.isMain()) { currentHdd = hdd; break; } } assertNotNull(hdds); assertFalse(hdds.isEmpty()); Assert.assertTrue(hdds.size() > 0); } Is there a smarter way to do this?

Target:
public void testListHardwareHdds() throws InterruptedException { assertNodeAvailable(currentServer); //give time for harddisk to be added // Thread.sleep(60000); List<Hdd> hdds = serverApi().listHdds(currentServer.id()); for (Hdd hdd : hdds) { if (!hdd.isMain()) { currentHdd = hdd; break; } } assertNotNull(hdds); assertFalse(hdds.isEmpty()); Assert.assertTrue(hdds.size() > 0); }
Source:
public void testListips() throws InterruptedException { List<ServerIp> ips = serverApi().listIps(currentServer.id()); currentIP = ips.get(0); assertNotNull(ips); assertFalse(ips.isEmpty()); START Assert.assertTrue(ips.size() > 0); END } Remove redundant assertions.

Target:
public void testListips() throws InterruptedException { List<ServerIp> ips = serverApi().listIps(currentServer.id()); currentIP = ips.get(0); assertNotNull(ips); Assert.assertTrue(ips.size() > 0); }
Source:
public void teardownTest() throws InterruptedException { //give time for operations to finish START Thread.sleep(10000); END if (currentServer != null) { assertNodeAvailable(currentServer); deleteServer(currentServer.id()); } if (cloneServer != null) { assertNodeAvailable(cloneServer); deleteServer(cloneServer.id()); } } Is it possible to get rid of this?

Target:
public void teardownTest() throws InterruptedException { //give time for operations to finish // Thread.sleep(10000); if (currentServer != null) { assertNodeAvailable(currentServer); deleteServer(currentServer.id()); } if (cloneServer != null) { assertNodeAvailable(cloneServer); deleteServer(cloneServer.id()); } }
Source:
public boolean apply(ServerPrivateNetworkRef networkRef) { checkNotNull(networkRef, "ServerPrivateNetworkRef"); PrivateNetwork server = api.serverApi().getPrivateNetwork(networkRef.serverId(), networkRef.privateNetworkId()); if (server.state() != Types.GenericState.ACTIVE) { return false; } else { return true; START } END } Just `return server.state() == Types.GenericState.ACTIVE`? Apply this to the other similar conditionals.

Target:
public boolean apply(ServerPrivateNetworkRef networkRef) { checkNotNull(networkRef, "ServerPrivateNetworkRef"); PrivateNetwork server = api.serverApi().getPrivateNetwork(networkRef.serverId(), networkRef.privateNetworkId()); return server.state() != Types.GenericState.ACTIVE; }
Source:
START private AuthenticateRequest(@Provider Supplier<Credentials> splr) { END authToken = splr.get(); checkNotNull(authToken.identity, "credential returned null"); } Package private visibility [is preferred](https://github.com/google/guice/wiki/KeepConstructorsHidden) for injection constructors. Change it to just: ``` java @Inject AuthenticateRequest(@Provider Supplier<Credentials> splr) { ```

Target:
AuthenticateRequest(@Provider Supplier<Credentials> splr) { authToken = splr.get(); checkNotNull(authToken.identity, "credential returned null"); }
Source:
public void testPublisher() { List<Publisher> publishers = api().listPublishers(); START System.out.println(publishers.size()); END assertTrue(publishers.size() > 0); } Remove all system outs.

Target:
public void testPublisher() { List<Publisher> publishers = api().listPublishers(); assertTrue(publishers.size() > 0); }
Source:
public B2Api api(String uri, String provider, Properties overrides) { return ContextBuilder.newBuilder(provider) .credentials("ACCOUNT_ID", "APPLICATION_KEY") .endpoint(uri) .overrides(overrides) .modules(modules) START .buildApi(new TypeToken<B2Api>(getClass()) {}); END } Just use `.buildApi(B2Api.class);`?

Target:
public B2Api api(String uri, String provider, Properties overrides) { return ContextBuilder.newBuilder(provider) .credentials("ACCOUNT_ID", "APPLICATION_KEY") .endpoint(uri) .overrides(overrides) .modules(modules) .buildApi(B2Api.class); }
Source:
protected Builder() { super(); id("azurecompute-arm") .name("Azure Resource Management ") .apiMetadata(new AzureManagementApiMetadata()) .endpoint("https://management.azure.com/subscriptions/SUBSCRIPTION_ID") .homepage(URI.create("https://www.windowsazure.com/")) .console(URI.create("https://windows.azure.com/default.aspx")) START .linkedServices("azureblob", "azurequeue", "azuretable") END .defaultProperties(AzureComputeProviderMetadata.defaultProperties()); } This should reference to _existing_ providers that can be accessed using the same account.

Target:
protected Builder() { super(); id("azurecompute-arm") .name("Azure Resource Management ") .apiMetadata(new AzureManagementApiMetadata()) .endpoint("https://management.azure.com/subscriptions/SUBSCRIPTION_ID") .homepage(URI.create("https://www.windowsazure.com/")) .console(URI.create("https://windows.azure.com/default.aspx")) .linkedServices("azureblob") .defaultProperties(AzureComputeProviderMetadata.defaultProperties()); }
Source:
public static Properties defaultProperties(Properties properties) { properties = properties == null ? new Properties() : properties; properties.put("oauth.identity", "foo"); properties.put("oauth.credential", "password"); properties.put("oauth.endpoint", "https://login.microsoftonline.com/oauth2/token"); START properties.put(AUDIENCE, "https://login.microsoftonline.com/oauth2/token"); END properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); return properties; } Remove this property.

Target:
public static Properties defaultProperties(Properties properties) { properties = properties == null ? new Properties() : properties; properties.put("oauth.identity", "foo"); properties.put("oauth.credential", "password"); properties.put("oauth.endpoint", "https://login.microsoftonline.com/oauth2/token"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); return properties; }
Source:
public DockerTemplateOptions configBuilder(Config.Builder configBuilder) { this.configBuilder = configBuilder != null START ? Config.builder().fromConfig(configBuilder.image(NO_IMAGE).build()).image(NO_IMAGE) END : null; return this; } Why setting the `NO_IMAGE` twice?

Target:
public DockerTemplateOptions configBuilder(Config.Builder configBuilder) { this.configBuilder = configBuilder != null ? Config.builder().fromConfig(configBuilder.image(NO_IMAGE).build()) : null; return this; }
Source:
protected void configure() { START bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Singleton.class); END } This is only used with the ComputeService implementation. Please remove it.

Target:
protected void configure()
Source:
protected void init() { String id = api.statisticsApi().self().id(); assertNotNull(id); START selfID = id; END } Avoid the intermediate variable and directly assign `selfID`.

Target:
protected void init() { selfID = api.statisticsApi().self().id(); assertNotNull(selfID); }
Source:
public void deleteBlobsByDirectory(String containerName, String directoryName, boolean recursive) { List<BlobEntity> blobs = findBlobsByDirectory(containerName, directoryName, false); for (BlobEntity blob : blobs) { if (!blob.isDirectory()) { deleteBlob(containerName, blob.getKey()); } else { if (recursive) { START deleteBlob(containerName, blob.getKey()); END deleteBlobsByDirectory(containerName, blob.getKey(), true); } } } } Shouldn't this be deleted _after_ all the blobs in the directory are deleted, after the recursive call?

Target:
public void deleteBlobsByDirectory(String containerName, String directoryName, boolean recursive) { List<BlobEntity> blobs = findBlobsByDirectory(containerName, directoryName, false); for (BlobEntity blob : blobs) { if (!blob.isDirectory()) { deleteBlob(containerName, blob.getKey()); } else { if (recursive) { deleteBlobsByDirectory(containerName, blob.getKey(), true); deleteBlob(containerName, blob.getKey()); } } } }
Source:
START public JPAInitializer(PersistService service) { END service.start(); } Injection constructors should be package private. Remove the `public` modifier.

Target:
private JPAInitializer(PersistService service) { service.start(); }
Source:
START public JdbcBlobUtils(LocalStorageStrategy storageStrategy, Provider<BlobBuilder> blobBuilders) { END this.storageStrategy = (JdbcStorageStrategy) checkNotNull(storageStrategy, "storageStrategy"); this.blobBuilders = checkNotNull(blobBuilders, "blobBuilders"); } Same here, remove the public modifier and the null checks.

Target:
JdbcBlobUtils(LocalStorageStrategy storageStrategy, Provider<BlobBuilder> blobBuilders) { this.storageStrategy = (JdbcStorageStrategy) storageStrategy; this.blobBuilders = blobBuilders; }
Source:
public VMImage.OSDiskConfiguration getResult() { VMImage.OSDiskConfiguration result = VMImage.OSDiskConfiguration .create(name, hostCaching, osState, os, mediaLink, logicalDiskSizeInGB, ioType); START return result; END } can we just return it directly?

Target:
public VMImage.OSDiskConfiguration getResult() { return VMImage.OSDiskConfiguration .create(name, hostCaching, osState, os, mediaLink, logicalDiskSizeInGB, ioType); }
Source:
protected ProviderMetadata createProviderMetadata() { synchronized (this) { if (providerMeta == null) { providerMeta = new AzureComputeProviderMetadata(); } } return providerMeta; START } END Is this really necessary? Isn't the base class method working?

Target:
protected ProviderMetadata createProviderMetadata() { if (providerMeta == null) { providerMeta = new AzureComputeProviderMetadata(); } return providerMeta; }
Source:
public void testAddRomDriveToServerPayload() { AddRomDriveToServerRequestBinder binder = new AddRomDriveToServerRequestBinder(); Drive.Request.AddRomDriveToServerPayload payload = Drive.Request.AddRomDriveToServerPayload.builder() .serverId("server-id") .storageId("image-id") .deviceNumber("device-number") .build(); String actual = binder.createPayload(payload); START assertNotNull(actual, "Binder returned null payload"); END assertEquals(expectedPayload, actual); } nit: This is redundant, the next check will also fail as the expected payload is not null.

Target:
public void testAddRomDriveToServerPayload() { AddRomDriveToServerRequestBinder binder = new AddRomDriveToServerRequestBinder(); Drive.Request.AddRomDriveToServerPayload payload = Drive.Request.AddRomDriveToServerPayload.builder() .serverId("server-id") .storageId("image-id") .deviceNumber("device-number") .build(); String actual = binder.createPayload(payload); assertEquals(expectedPayload, actual); }