auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Boolean implies(SymbolicValueRelation relation) { if (v1.equals(relation.v1) && v2.equals(relation.v2)) { return relation.isImpliedBy(this); } else if (v1.equals(relation.v2) && v2.equals(relation.v1)) { return relation.isImpliedBy(symmetric()); } return null; }

Target:
why `public` when all the other are `protected`.
Source:
public void visitNode(Tree tree) { MethodTreeImpl methodTree = (MethodTreeImpl) tree; Symbol.MethodSymbol methodSymbol = methodTree.symbol(); if (methodSymbol.isMethodSymbol()) { JavaSymbol.MethodJavaSymbol overridee = ((JavaSymbol.MethodJavaSymbol) methodSymbol).overriddenSymbol(); if (overridee != null && overridee.isMethodSymbol()) { checkContractChange(methodTree, overridee); } } }

Target:
As you know it's a method symbol from getting it the `methodTree`, why testing it again? Is it to cover the case of unknown symbol? If it's the case, I would prefer to test it by using `!methodSymbol.isUnknown()`. Moreover, this case is not covered by your test cases. The same remarks apply to the overridee below.
Source:
static boolean isWithinTryHeader(Tree syntaxNode) { final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }

Target:
should be private.
Source:
static boolean isTryStatementResource(VariableTree variable) { final TryStatementTree tryStatement = getEnclosingTryStatement(variable); if (tryStatement != null) { return tryStatement.resources().contains(variable); } return false; }

Target:
should be private.
Source:
public JavaVersionImpl(int javaVersion) { this.javaVersion = javaVersion; this.initialized = true; }

Target:
Should deserve a @VisibleForTesting ?
Source:
public Set<SymbolicValue> getFieldValues() { final HashSet<SymbolicValue> fieldValues = new HashSet<>(); values.forEach(new PMap.Consumer<Symbol, SymbolicValue>() { @Override public void accept(Symbol key, SymbolicValue value) { if (isField(key)) { fieldValues.add(value); } } }); return fieldValues; }

Target:
No special need for final and please use interface. No need to know implementation. I would even recommend to use ImmutableSet from guava for safety.
Source:
public void newInstanceBis() throws IllegalAccessException, InstantiationException { try { // Refind the constructor after a deserialization (if needed) if (constructor == null) { this.setDynaBeanClass(); } // Invoke the constructor to create a new bean instance return ((DynaBean) constructor.newInstance(constructorValues)); } catch (final InvocationTargetException e) { throw new InstantiationException (e.getTargetException().getMessage()); } }

Target:
This test case seems overcomplicated. All what is not necessary should be removed : (generics, try catch, etc).
Source:
public Resolution findMethod(Env env, JavaType site, String name, List<JavaType> argTypes) { return findMethod(env, site, site, name, argTypes, ImmutableList.<JavaType>of()); }

Target:
Maybe you could have let the `false` parameter to avoid the initial call to the new method `findMethod`
Source:
private String registerClassInternalName(String name) { int num; if (internalNames.containsKey(name)) { num = internalNames.get(name) + 1; } else { num = 1; } internalNames.put(name, num); return num + name; }

Target:
initialize num to 1 and get rid of else.
Source:
public Set<Symbol> getOut(CFG.Block block) { return ImmutableSet.copyOf(out.get(block)); }

Target:
@benzonico copy should be done outside of getter - at the end of analysis
Source:
int increment_operator() { int i = 0; int b = 12; ++b; int j = -1; while ((j = foo(++j)) != -1) { System.out.println(""); } if(i != 0) { return i++; // Noncompliant } else { return ++i; } }

Target:
@benzonico false-negative
Source:
private boolean isSearchedVariable(ExpressionTree variable) { return variable.is(Tree.Kind.IDENTIFIER) && usages.contains((IdentifierTree) variable); }

Target:
@m-g-sonar `(IdentifierTree)` cast not needed.
Source:
private boolean operandsAreOnSameLine(BinaryExpressionTree formatStringTree) { return FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.leftOperand()).line() == FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.rightOperand()).line(); }

Target:
![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "operandsAreOnSameLine" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://nemo.sonarqube.org/coding_rules#rule_key=squid%3AS2325)
Source:
private ExpressionTree getPackageName(CompilationUnitTree cut) { return cut.packageDeclaration() != null ? cut.packageDeclaration().packageName() : null; }

Target:
![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "getPackageName" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://nemo.sonarqube.org/coding_rules#rule_key=squid%3AS2325)
Source:
public void visitEnumConstant(EnumConstantTree tree) { scan(((NewClassTree) tree.initializer()).classBody()); }

Target:
I created ticket and fixed it : https://github.com/SonarSource/sonar-java/pull/291
Source:
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 -= 1) { executionState.pop(); } executionState.push(value); } }

Target:
@merciesa maybe matter of taste, but why not `i--` instead of `i -= 1`?
Source:
public void visitMethod(MethodTree tree) { boolean isUnitTest = isUnitTest(tree); inUnitTest.push(isUnitTest); methodContainsAssertion.push(Boolean.FALSE); super.visitMethod(tree); inUnitTest.pop(); if (isUnitTest && !methodContainsAssertion.pop()) { context.addIssue(tree, this, "Add at least one assertion to this test case."); } }

Target:
matter of taste but why not rely on autoboxing ?
Source:
public State merge(State s) { if (s instanceof Null) { return this; } if(!(s instanceof CloseableState)) { throw new IllegalStateException("Merging incompatible states"); } return s; }

Target:
Why only throwing this exception for the `Closed` state and not for every `CloseableState`? (same remark for the `Unlocked` state of `LockState`)
Source:
private void ignoreVariable(VariableTree variableTree) { Symbol symbol = variableTree.symbol(); if (isCloseableOrAutoCloseableSubtype(symbol.type())) { executionState.markValueAs(symbol, new CloseableState.Ignored(variableTree)); } }

Target:
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.
Source:
public void visitNode(Tree tree) { Symbol.TypeSymbol symbol = ((ClassTree) tree).symbol(); if (symbol.owner().isTypeSymbol() && symbol.isStatic()) { addIssue(tree, "Remove this redundant \"static\" qualifier."); } }

Target:
This check should not rely on semantic !!!
Source:
public void visitReturnStatement(ReturnStatementTree tree) { super.visitReturnStatement(tree); executionState.checkUsageOfClosables(tree.expression()); }

Target:
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.
Source:
ParametrizedTypeType(Symbol.TypeSymbol symbol, Map<TypeVariableType, Type> typeSubstitution) { super(symbol); this.rawType = symbol.getType(); this.typeSubstitution = typeSubstitution; if (rawType.isTagged(UNKNOWN)) { // force unknown instead of keeping CLASS this.tag = UNKNOWN; } }

Target:
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.
Source:
private String getTypeName(Tree tree) { Type type = ((AbstractTypedTree) tree).getSymbolType(); TypeSymbol symbol = type.getSymbol(); String name = symbol.getName(); if (name.isEmpty()) { name = getAnonymousClassTypeName(symbol); } return name; }

Target:
To allow further reuse I would split this into a method getting a name from TypeSymbol.
Source:
private boolean isField(Tree tree) { return tree.is(Kind.VARIABLE) && !((VariableTree) tree).modifiers().modifiers().containsAll(Lists.newArrayList(Modifier.FINAL, Modifier.STATIC)); }

Target:
What about a static member ? class A extends B { public static String staticMember; }
Source:
public void visitNode(Tree tree) { Long identityElement = getBitwiseOperationIdentityElement(tree); Long evaluatedExpression = evaluateExpression(getExpression(tree)); if (evaluatedExpression != null && evaluatedExpression == identityElement) { addIssue(tree, "Remove this silly bit operation."); } }

Target:
use equals instead of ==
Source:
private boolean isFinalizeDeclaration(MethodTree tree) { return hasSemantic() && isMethodNamedFinalize(tree) && isOverriding(tree) && hasNoParameters(tree); }

Target:
Check for overriding is uncessary.
Source:
public void visitReturnStatement(ReturnStatementTree tree) { if (isWithinCallingMethodBody(tree) && returnsIntegerMinValue(tree.expression())) { addIssue(tree, "Simply return -1"); } super.visitReturnStatement(tree); }

Target:
uncessary call to super. No need to visit further.
Source:
default ScheduledExecutorService getTimerExecutor() { return Executors.newScheduledThreadPool(1); }

Target:
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.
Source:
public ScsiController build() { disks(disks() != null ? ImmutableList.copyOf(disks()) : new ArrayList<ScsiDisk>()); return autoBuild(); }

Target:
Enforce an immutable list in all cases.
Source:
public void testListCustomerImages() { FluentIterable<CustomerImage> customerImages = api.getServerImageApi().listCustomerImages().concat(); assertNotNull(customerImages); customerImages.anyMatch(new Predicate<CustomerImage>() { @Override public boolean apply(CustomerImage input) { return input.id().equals(cloneImageId); } }); }

Target:
`assertTrue(customerImages.anyMatch(new Predicate<CustomerImage>() {`
Source:
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(Permission.Policy.values()), value); return ipProtocol.get(); }

Target:
`IpProtocol.values()`
Source:
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(Policy.values()), value); return nicType.get(); }

Target:
`NicType.values()`
Source:
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)); }

Target:
Negate the condition, otherwise you are failing if the value is correct.
Source:
private AliyunDateAdapter(DateService dateService) { super(dateService); }

Target:
Remove the `private` modifier so you can properly test it.
Source:
public void testListImagesReturns404() throws InterruptedException { server.enqueue(response404()); Iterable<Image> images = api.imageApi().list(Regions.EU_CENTRAL_1.getName()).concat(); assertTrue(isEmpty(images)); assertEquals(server.getRequestCount(), 1); }

Target:
We should also verify that we're sending the page size parameter.
Source:
public OperatingSystemToOperatingSystem(final OperatingSystemToOsFamily operatingSystemToOsFamily) { this.operatingSystemToOsFamily = operatingSystemToOsFamily; }

Target:
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)).
Source:
public void cleanup() { if (!tagKeyId.isEmpty()) { api().deleteTagKey(tagKeyId); } }

Target:
Unlikely, but this could throw an NPE. Better check for `null` too.
Source:
public ServerToServerWithExternalIp(DimensionDataCloudControlApi api) { this.api = checkNotNull(api, "api"); }

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

Target:
Remove the public modifier
Source:
public void testGet() { Vault vaultFound = api().getVault(vaultName); assertTrue(!vaultFound.name().isEmpty()); }

Target:
Better `assertNotNull(vaultFound)` to avoid an unexpected NPE?
Source:
public void testList() { for (Vault vault : api().listVaults()) { assertNotNull(vault.name()); VaultProperties props = vault.properties(); assertNotNull(props); } }

Target:
If properties are not nullable there is no need to check this. Deserialization will already fail.
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"); tenantId = System.getProperty("test.azurecompute-arm.tenantId"); }

Target:
Change to: `tenantId = injector.getInstance(Key.get(String.class, Tenant.class));`
Source:
public void testDelete() { boolean result = api().deleteVault(vaultName); assertTrue(result); Object[] args = { resourceGroupName, vaultName, true }; checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName), "vault was not deleted before timeout"); }

Target:
Unused args?
Source:
public void testDelete() throws InterruptedException { server.enqueue(response202WithHeader()); final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup); vmssAPI.delete(vmssname); assertSent(server, "DELETE", "/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/" + "Microsoft.Compute" + "/VirtualMachineScaleSets/jclouds-vmssname?api-version=2017-03-30"); }

Target:
Verify that returns a non-null URI.
Source:
protected void configure() { bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); super.configure(); }

Target:
Call `super` first.
Source:
public ParseResponse(Json json, String propertyName) { this.json = json; this.propertyName = propertyName; }

Target:
Make this protected?
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); return api.getInfrastructureApi().listOperatingSystems(arg.toString(), paginationOptions); } }; }

Target:
Take care! `arg.get().toString()`. Otherwise you're passing the `Optional` object.
Source:
protected void configure() { Names.bindProperties(binder(), Collections.singletonMap(Constants.PROPERTY_PRETTY_PRINT_PAYLOADS, "true")); bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); }

Target:
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.
Source:
public OrganisationIdFilter(@Memoized Supplier<String> organisationIdSupplier) { this.organisationIdSupplier = organisationIdSupplier; }

Target:
Remove the `public` modifier. It is a best-practice in Guice to make all injection constructors visible just to the default scope.
Source:
public 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); }

Target:
Don't make it public if it is just visible for testing. Remove the public modifier and leave it in default scope.
Source:
public void testCaasUrl() { Supplier<String> orgIdSupplier = new OrganisationIdForAccount(api); 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); }

Target:
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.
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); if (!dataDisks.isEmpty()) { eTo.dataDisks(dataDisks); } } }

Target:
Redundant check. We allow passing an empty list.
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"); this.boxToImage = checkNotNull(boxToImage, "boxToImage"); }

Target:
Remove the redundant null checks.
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"); this.hardwareSupplier = checkNotNull(hardwareSupplier, "hardwareSupplier"); }

Target:
Remove the redundant null checks.
Source:
public 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 = checkNotNull(client, "client"); this.userExecutor = checkNotNull(userExecutor, "userExecutor"); this.locations = checkNotNull(locations, "locations"); this.snapshotAvailablePredicate = checkNotNull(snapshotAvailablePredicate, "snapshotAvailablePredicate"); this.trackables = checkNotNull(trackables); }

Target:
Remove the public modifier, and all null checks, since the injector already enforces that.
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) { throw new NoSuchElementException("Cannot find server with id: " + id); } CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); return template; }

Target:
Better throw an `IllegalArgumentException`.
Source:
DeviceToNodeMetadata(PlanToHardware planToHardware, OperatingSystemToImage operatingSystemToImage, FacilityToLocation facilityToLocation, Function<Device.State, NodeMetadata.Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention) { this.planToHardware = checkNotNull(planToHardware, "planToHardware cannot be null"); 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(); }

Target:
No need for null checks in the injection constructors.
Source:
protected ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) { this.api = checkNotNull(api, "api"); this.hrefToOptions = hrefToOptions; }

Target:
Remove the redundant check and the protected modifier from the constructor
Source:
public AddApiVersionToRequest(@ApiVersion String apiVersion) { this.apiVersion = checkNotNull(apiVersion, "apiVersion"); }

Target:
Remove the public modifier from the constructor and remove the null check.
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")) .iso3166Codes("de", "us", "es", "gb") .endpoint("https://cloudpanel-api.1and1.com/v1/") .defaultProperties(OneAndOneProviderMetadata.defaultProperties()); }

Target:
This should contain the iso codes, not the region id.
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; } }

Target:
Try to avoid conditionals like `if (condition) return true else return false`. Just `return condition`.
Source:
public void testList() { dataCenters = dataCenterApi().list(); currentDataCenter = dataCenters.get(0); assertNotNull(dataCenters); assertFalse(dataCenters.isEmpty()); Assert.assertTrue(dataCenters.size() > 0); }

Target:
Check this before calling get.
Source:
public void testList() { appliances = serverApplianceApi().list(); currentAppliance = appliances.get(0); Assert.assertTrue(appliances.size() > 0); }

Target:
Assert this before calling get.
Source:
public void testList() { List<MonitoringCenter> result = monitoringCenterApi().list(); assertNotNull(result); }

Target:
Verify that at least returns one element?
Source:
public void testListWithOption() { GenericQueryOptions options = new GenericQueryOptions(); options.options(1, 1, null, null, null); List<MonitoringCenter> resultWithQuery = monitoringCenterApi().list(options); assertNotNull(resultWithQuery); }

Target:
Same here, verify that at least one element is returned?
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) { Logger.getLogger(VPNConfigParser.class.getName()).log(Level.SEVERE, null, ex); return null; } }

Target:
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.
Source:
public void testList() { publicIps = publicIpApi().getList(); assertNotNull(publicIps); assertFalse(publicIps.isEmpty()); Assert.assertTrue(publicIps.size() > 0); }

Target:
This is redundant.
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(); } finally { Closeables2.closeQuietly(azureBlob); } }

Target:
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?
Source:
public void testListAccessCredentials() throws InterruptedException { List<SharedStorageAccess> access = sharedStorageApi().getAccessCredentials(); assertNotNull(access); assertTrue(access.size() > 0); }

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

Target:
Remove the `InterruptedException` from the signature.
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"); System.setProperty("javax.net.ssl.trustStorePassword", "testme"); }

Target:
Remove all these properties.
Source:
public static String[] decodeFieldsFromUniqueId(final String id) { final String[] parts = checkNotNull(id, "id").split("/"); return parts; }

Target:
Just `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) { publisher = publisher.trim(); getImagesFromPublisher(publisher, osImages, location); } return osImages; }

Target:
I don't think you need to trim again
Source:
public HttpRequest filter(HttpRequest request) throws HttpException { checkNotNull(authToken.identity, "credential returned null"); return request.toBuilder().replaceHeader(AuthHeaders.AUTH_TOKEN, TokenBased()).build(); }

Target:
Move this to the constructor.
Source:
public void testList() { servers = serverApi().getList(); assertNotNull(servers); assertFalse(servers.isEmpty()); Assert.assertTrue(servers.size() > 0); }

Target:
This is redundant.
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()); Assert.assertTrue(serversWithQuery.size() > 0); }

Target:
Remove this redundant assertion and all similar ones.
Source:
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); }

Target:
Is there a smarter way to do this?
Source:
public void testListips() throws InterruptedException { List<ServerIp> ips = serverApi().listIps(currentServer.id()); currentIP = ips.get(0); assertNotNull(ips); assertFalse(ips.isEmpty()); Assert.assertTrue(ips.size() > 0); }

Target:
Remove redundant assertions.
Source:
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()); } }

Target:
Is it possible to get rid of this?
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; } }

Target:
Just `return server.state() == Types.GenericState.ACTIVE`? Apply this to the other similar conditionals.
Source:
private AuthenticateRequest(@Provider Supplier<Credentials> splr) { authToken = splr.get(); checkNotNull(authToken.identity, "credential returned null"); }

Target:
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) { ```
Source:
public void testPublisher() { List<Publisher> publishers = api().listPublishers(); System.out.println(publishers.size()); assertTrue(publishers.size() > 0); }

Target:
Remove all system outs.
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) .buildApi(new TypeToken<B2Api>(getClass()) {}); }

Target:
Just use `.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")) .linkedServices("azureblob", "azurequeue", "azuretable") .defaultProperties(AzureComputeProviderMetadata.defaultProperties()); }

Target:
This should reference to _existing_ providers that can be accessed using the same account.
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"); properties.put(AUDIENCE, "https://login.microsoftonline.com/oauth2/token"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); return properties; }

Target:
Remove this property.
Source:
public DockerTemplateOptions configBuilder(Config.Builder configBuilder) { this.configBuilder = configBuilder != null ? Config.builder().fromConfig(configBuilder.image(NO_IMAGE).build()).image(NO_IMAGE) : null; return this; }

Target:
Why setting the `NO_IMAGE` twice?
Source:
protected void configure() { bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Singleton.class); }

Target:
This is only used with the ComputeService implementation. Please remove it.
Source:
protected void init() { String id = api.statisticsApi().self().id(); assertNotNull(id); selfID = id; }

Target:
Avoid the intermediate variable and directly assign `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) { deleteBlob(containerName, blob.getKey()); deleteBlobsByDirectory(containerName, blob.getKey(), true); } } } }

Target:
Shouldn't this be deleted _after_ all the blobs in the directory are deleted, after the recursive call?
Source:
public JPAInitializer(PersistService service) { service.start(); }

Target:
Injection constructors should be package private. Remove the `public` modifier.
Source:
public JdbcBlobUtils(LocalStorageStrategy storageStrategy, Provider<BlobBuilder> blobBuilders) { this.storageStrategy = (JdbcStorageStrategy) checkNotNull(storageStrategy, "storageStrategy"); this.blobBuilders = checkNotNull(blobBuilders, "blobBuilders"); }

Target:
Same here, remove the public modifier and the null checks.
Source:
public VMImage.OSDiskConfiguration getResult() { VMImage.OSDiskConfiguration result = VMImage.OSDiskConfiguration .create(name, hostCaching, osState, os, mediaLink, logicalDiskSizeInGB, ioType); return result; }

Target:
can we just return it directly?
Source:
protected ProviderMetadata createProviderMetadata() { synchronized (this) { if (providerMeta == null) { providerMeta = new AzureComputeProviderMetadata(); } } return providerMeta; }

Target:
Is this really necessary? Isn't the base class method working?
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); assertNotNull(actual, "Binder returned null payload"); assertEquals(expectedPayload, actual); }

Target:
nit: This is redundant, the next check will also fail as the expected payload is not null.
Source:
protected String createPayload(LoadBalancer.Request.DeregisterPayload payload) { requestBuilder.append("<ws:deregisterServersOnLoadBalancer>") .append("<request>"); for (String s : payload.serverIds()) { requestBuilder.append(format("<serverIds>%s</serverIds>", s)); } requestBuilder.append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())) .append("</request>") .append("</ws:deregisterServersOnLoadBalancer>"); return requestBuilder.toString().replaceAll("\\s+", ""); }

Target:
Is this really needed?
Source:
protected LoadBalancerListResponseHandler(DateCodecFactory dateCodec, ServerListResponseHandler balancedServerResponseHandler, FirewallListResponseHandler firewallListResponseHandler) { super(dateCodec, balancedServerResponseHandler, firewallListResponseHandler); this.loadBalancers = Lists.newArrayList(); }

Target:
Make this package private.
Source:
public void testGetAllLoadBalancers() { List<LoadBalancer> loadBalancers = api.loadBalancerApi().getAllLoadBalancers(); assertNotNull(loadBalancers); assertFalse(loadBalancers.isEmpty()); }

Target:
The API should never return null lists. Remove this. Also, should this be executed after creating the load balancer?
Source:
public void testGetLoadBalancer() { LoadBalancer loadBalancer = api.loadBalancerApi().getLoadBalancer(loadBalancerID); System.out.println(loadBalancer); assertNotNull(loadBalancer); }

Target:
Remove this
Source:
protected void checkPortRange() { checkArgument((portRangeEnd == null && portRangeStart == null) || (portRangeEnd != null && portRangeStart != null), "Port range must be both present or null"); if (portRangeEnd != null) { checkArgument(protocol == Protocol.TCP || protocol == Protocol.UDP, "Port range can only be set for TCP or UDP"); checkArgument(portRangeEnd > portRangeStart, "portRangeEnd must be greater than portRangeStart"); checkArgument(portRangeEnd >= 1 && portRangeEnd <= 65534, "Port range end must be 1 to 65534"); checkArgument(portRangeStart >= 1 && portRangeStart <= 65534, "Port range start must be 1 to 65534"); } }

Target:
[nit] This can be more concise: ``` java checkArgument(!(portRangeEnd == null ^ portRangeStart == null), "Port range must be both present or null"); ```
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(Constants.PROPERTY_MAX_RETRIES, "5"); properties.setProperty(ShipyardProperties.SHIPYARD_CREDENTIAL, "<remote-service-key-given-by-shipyard-cli>"); return properties; }

Target:
Is this a _good_ value for this property? Will the Api work if users don't override it? Should this value be passed as the credential?
Source:
public ServiceKeyAuthentication(@Provider Supplier<Credentials> creds) { this.creds = checkNotNull(creds, "creds"); }

Target:
Make the constructor package protected. This way you make sure it is only used by the Guice injector, which will already enforce the parameters to be present. Then you can also remove the `checkNotNull` check.
Source:
public String parseMessage(HttpResponse response) { if (response.getPayload() == null) return null; try { return Strings2.toStringAndClose(response.getPayload().openStream()); } catch (IOException e) { throw Throwables.propagate(e); } }

Target:
Make this method private
Source:
public Builder securityOpts(List<String> securityOpts) { this.securityOpts = ImmutableList.copyOf(checkNotNull(securityOpts, "securityOpts")); return this; }

Target:
weird indent. also this class is inconsistent on safe copies. as auto will likely generate builders and these won't do safe copies, better to just not do it, and ensure whoever is calling this safe copies in.
Source:
public void testList() { List<CloudService> response = api().list(); for (CloudService cloudService : api().list()) { checkHostedService(cloudService); } if (!response.isEmpty()) { CloudService cloudService = response.iterator().next(); assertEquals(api().get(cloudService.name()), cloudService); } }

Target:
[minor] `for (CS cloudService : response)`?
Source:
public String toString() { return MoreObjects.toStringHelper(this).omitNullValues().add("code", code).add("message", message).toString(); }

Target:
[minor] The new implementations elsewhere seem to remove `omitNullValues`. Intentionally left here? What does `@AutoValue` do?
Source:
public BaseDataCenterResponseHandler(DateCodecFactory dateCodecFactory) { super(dateCodecFactory); this.builder = DataCenter.builder(); }

Target:
Guice best practices: make this constructor visible only at package level.
Source:
public DataCenterListResponseHandler(DateCodecFactory dateCodec) { super(dateCodec); this.dataCenters = Lists.newArrayList(); }

Target:
Injected constructor should be package private.
Source:
public BaseProfitBricksRequestBinder(String paramName) { this.paramName = checkNotNull(paramName, "Initialize 'paramName' in constructor"); }

Target:
This should be only created by the Guice injector. Make the constructor `protected`.
Source:
public CreateDataCenterRequestBinder() { super("dataCenter"); this.requestBuilder = new StringBuilder(128); }

Target:
This constructor should be only called by the Guice injector. Make it package private by removing the `public` modifier.
Source:
public void testCreateDataCenterWithIllegalArguments() throws Exception { String[] names = {"JCl@ouds", "JC|ouds", "^clouds", ""}; for (String name : names) try { DataCenter.Request.CreatePayload.create(name, Location.US_LAS); fail("Should have failed for name: ".concat(name)); } catch (Exception ex) { assertTrue(ex instanceof IllegalArgumentException); } }

Target:
Why not just catching the `IllegalArgumentException`?
Source:
public Volume apply(ServerDrive serverDrive) { VolumeBuilder builder = new VolumeBuilder(); DriveInfo driveInfo = api.getDriveInfo(serverDrive.getDriveUuid()); builder.id(driveInfo.getUuid()); builder.size(driveInfo.getSize().floatValue()); builder.durable(true); builder.type(Volume.Type.NAS); builder.bootDevice(serverDrive.getBootOrder() > 0); return builder.build(); }

Target:
Just checking...boot order _greater_ than zero means this is a boot device?
Source:
private Function<String, OsFamily> osFamily() { return new Function<String, OsFamily>() { OsFamily osFamily = OsFamily.UNRECOGNIZED; @Override public OsFamily apply(final String description) { if (description != null) { if (description.contains(CENTOS)) osFamily = OsFamily.CENTOS; else if (description.contains(UBUNTU)) osFamily = OsFamily.UBUNTU; } logger.debug("os family for item: %s is %s", description, osFamily); return osFamily; } }; }

Target:
There is no need for this local variable. Just return directly the detected os family.
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(Constants.PROPERTY_MAX_RETRIES, "15"); properties.setProperty("jclouds.ssh.retry-auth", "true"); properties.setProperty(Constants.PROPERTY_CONNECTION_TIMEOUT, "1200000"); // 15 minutes properties.setProperty("image.login-user", "root"); properties.setProperty(ComputeServiceProperties.IMAGE_LOGIN_USER, "root:password"); properties.setProperty(TEMPLATE, "osFamily=UBUNTU,os64Bit=true,osVersionMatches=1[012].[01][04]"); return properties; }

Target:
Where is this property (without the jclouds prefix) used?
Source:
public String parseMessage(HttpResponse response) { if (response.getPayload() == null) return null; try { return Strings2.toString(response.getPayload()); } catch (IOException e) { throw Throwables.propagate(e); } finally { try { response.getPayload().getInput().close(); } catch (IOException e) { throw Throwables.propagate(e); } } }

Target:
The payload itself is already closeable. Close the payload to avoid the deprecation warning?
Source:
public void write(JsonWriter out, PublicKey value) throws IOException { checkArgument(value instanceof RSAPublicKey || value instanceof DSAPublicKey, "Only RSA and DSA keys are supported"); if (value instanceof RSAPublicKey) { out.value(SshKeys.encodeAsOpenSSH((RSAPublicKey) value)); } else { out.value(DSAKeys.encodeAsOpenSSH((DSAPublicKey) value)); } }

Target:
Could save one check like this, but up to you: ``` if (value instanceof RSAPublicKey) { .. } else if (value instanceof DSAPublicKey) { .. } else { throw new ... } ```
Source:
public static Distribution fromValue(String value) { return tryFind(asList(Distribution.values()), hasValue(value)).or(UNRECOGNIZED); }

Target:
Make a static variable for `asList(Distribution.values()`?
Source:
public ImageTemplate buildImageTemplateFromNode(String name, String id) { Droplet droplet = null; try { droplet = api.getDropletApi().get(Integer.valueOf(id)); } catch (Exception ex) { throw new NoSuchElementException("Cannot find droplet with id: " + id); } if (droplet == null) { throw new NoSuchElementException("Cannot find droplet with id: " + id); } return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); }

Target:
That catch should be removed. It was just a guard, before the provider had properly implemented the error/retry handlers.
Source:
public CalcSubscription build() { return new CalcSubscription(amount, discountAmount, discountPercent, endTime, period, price, resource , startTime); }

Target:
Formatting: move `,` to the end of the previous line?
Source:
protected Function<Object, IterableWithMarker<Discount>> markerToNextForArgs(List<Object> args) { return new Function<Object, IterableWithMarker<Discount>>() { @Override public IterableWithMarker<Discount> apply(@Nullable Object input) { PaginationOptions paginationOptions = PaginationOptions.class.cast(input); return api.listDiscounts(paginationOptions); } }; }

Target:
This function will only be called when the marker is present, so in practice the `input` parameter won't be null. Remove the `@Nullable` annotation (apply this to all parser classes).
Source:
VLANs(Iterable<VLANInfo> objects, PaginationOptions paginationOptions) { super(objects, paginationOptions); }

Target:
Why is this constructor package protected?
Source:
public UserOptions build() { UserOptions options = new UserOptions(); if ( limit != null ) { options.queryParameters.put("numResults", String.valueOf(limit)); // Remove the "limit" parameter: it has been replaced by "numResults" limit = null; } if ( page != null ) { options.queryParameters.put("page", String.valueOf(page)); } return addFilterOptions(options); }

Target:
You could avoid the `if` statements by simply declaring the `UserOptions` instance in the builder directly, and modifying that: ``` public Builder { private final UserOptions options = new UserOptions(); public Builder page(int page) { options.queryParameters.put("page", String.valueOf(page)); return this; } ... public UserOptions build() { return addFilterOptions(options); } } ```
Source:
protected Image(String id, Date creationTimestamp, URI selfLink, String name, String description, String sourceType, URI preferredKernel, RawDisk rawDisk, Deprecated deprecated) { super(Kind.IMAGE, id, creationTimestamp, selfLink, name, description); this.sourceType = checkNotNull(sourceType, "sourceType of %s", name); this.preferredKernel = fromNullable(preferredKernel); this.rawDisk = checkNotNull(rawDisk, "rawDisk of %s", name); this.deprecated = fromNullable(deprecated); ; }

Target:
Remove?
Source:
public void deleteTempFileAndFolder() { try { if ( aliasingIsActive() ) { FileObject srcFile = KettleVFS.getFileObject( temporaryFilePath, variableSpace ); srcFile.getParent().deleteAll(); } } catch ( FileSystemException | KettleFileException e ) { log.logError( e.getMessage() ); } }

Target:
Can you add the exception as the second parameter? Otherwise we won't be able to tell where the error happened from just the message.
Source:
public Builder addMember(MemberRef member) { this.members.add(member); return this; }

Target:
You can omit the `this.`.
Source:
public void onEntityPathfind(EntityPathfindEvent event) { this.event = event; Entity entity = event.getEntity(); Entity target = event.getTargetEntity(); this.entity = new EntityTag(entity); this.target = target != null ? new EntityTag(target) : null; EntityTag.rememberEntity(entity); EntityTag.rememberEntity(target); fire(event); EntityTag.forgetEntity(entity); EntityTag.forgetEntity(target); }

Target:
These remember/forgets shouldn't be here.
Source:
public static void registerTags() { // <--[tag] // @attribute <MaterialTag.leaf_size> // @returns ElementTag // @mechanism MaterialTag.leaf_size // @group properties // @description // Returns the size of the leaves for this bamboo block. // Output is SMALL, LARGE, or NONE. // --> PropertyParser.<MaterialBamboo>registerTag("leaf_size", (attribute, material) -> { return new ElementTag(String.valueOf(material.getBamboo().getLeaves())); }); }

Target:
`.name()` to stringify an enum.
Source:
public int getMax() { if (isCake()) { return getCake().getMaximumBites(); } if (isSnow()) { return getSnow().getMaximumLayers(); } else if (isHive()) { return getMaxHoneyLevel(); } return getLevelled().getMaximumLevel(); }

Target:
This should be an `else`
Source:
public static void init() { Debug.log("Loading Paper support module..."); // Events ScriptEvent.registerScriptEvent(new PlayerEquipsArmorScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerJumpsPaperScriptEventImpl()); ScriptEvent.registerScriptEvent(new PlayerSpectatesEntityScriptEvent()); ScriptEvent.registerScriptEvent(new EntityKnocksbackEntityScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerStopsSpectatingScriptEvent()); ScriptEvent.registerScriptEvent(new ProjectileCollideScriptEvent()); ScriptEvent.registerScriptEvent(new TNTPrimesScriptEvent()); // Properties PropertyParser.registerProperty(EntityCanTick.class, EntityTag.class); }

Target:
This list should be alphabetized (just look at the order of events in your IntelliJ class listing)
Source:
public ScriptEntryData getScriptEntryData() { return new BukkitScriptEntryData(event != null ? EntityTag.getPlayerFrom(event.getPlayer()) : null, null); }

Target:
What's with the null check?
Source:
public String getPropertyString() { return entity.getBukkitEntity() instanceof Creeper ? ((Creeper) entity.getBukkitEntity()).getMaxFuseTicks() + "" : null; }

Target:
Unneeded tern (it's always a creeper if it's reading this line)