auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public CodeVisitor[] checkClasses() { List<CodeVisitor> visitors = Lists.newArrayList(); // add issue filters BEFORE all the other checks for (JavaIssueFilter issueFilter : issueFilters) { visitors.add(issueFilter); } for (Checks<JavaCheck> checksElement : checks) { Collection<JavaCheck> checksCollection = checksElement.all(); if (!checksCollection.isEmpty()) { visitors.addAll(checksCollection); } } return visitors.toArray(new CodeVisitor[visitors.size()]); }

Target:
public CodeVisitor[] checkClasses() { List<CodeVisitor> visitors = Lists.newArrayList(); for (Checks<JavaCheck> checksElement : checks) { Collection<JavaCheck> checksCollection = checksElement.all(); if (!checksCollection.isEmpty()) { visitors.addAll(checksCollection); } } return visitors.toArray(new CodeVisitor[visitors.size()]); }
Source:
public @Nonnull String colorMix() { return null; // Noncompliant {{This method's return value is marked "javax.annotation.Nonnull" but null is returned.}} }

Target:
public String colorMix() { return null; // Noncompliant {{This method's return value is marked "javax.annotation.Nonnull" but null is returned.}} }
Source:
private boolean isSAM(ClassTree classBody) { if(hasOnlyOneMethod(classBody.members()) && classBody.symbol().isTypeSymbol()) { // Verify class body is a subtype of an interface JavaSymbol.TypeJavaSymbol symbol = (JavaSymbol.TypeJavaSymbol) classBody.symbol(); return symbol.getInterfaces().size() == 1 && symbol.getSuperclass().is("java.lang.Object"); } return false; }

Target:
private static boolean isSAM(ClassTree classBody) { if(hasOnlyOneMethod(classBody.members()) && classBody.symbol().isTypeSymbol()) { // Verify class body is a subtype of an interface JavaSymbol.TypeJavaSymbol symbol = (JavaSymbol.TypeJavaSymbol) classBody.symbol(); return symbol.getInterfaces().size() == 1 && symbol.getSuperclass().is("java.lang.Object"); } return false; }
Source:
protected BinaryRelation combineUnordered(BinaryRelation relation) { BinaryRelation combined = null; if (rightOp.equals(relation.leftOp)) { combined = relation.combineOrdered(this); } else if (rightOp.equals(relation.rightOp)) { combined = relation.symmetric().combineOrdered(this); } return combined; }

Target:
BinaryRelation combineUnordered(BinaryRelation relation) { BinaryRelation combined = null; if (rightOp.equals(relation.leftOp)) { combined = relation.combineOrdered(this); } else if (rightOp.equals(relation.rightOp)) { combined = relation.symmetric().combineOrdered(this); } return combined; }
Source:
public boolean isAnnotatedOverride() { for (AnnotationTree annotationTree : modifiers.annotations()) { if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER) && isOverride((IdentifierTree) annotationTree.annotationType())) { return true; } else if (annotationTree.annotationType().is(Kind.MEMBER_SELECT) && isJavaLangOverride((MemberSelectExpressionTree) annotationTree.annotationType())) { return true; } } return false; }

Target:
public boolean isAnnotatedOverride() { for (AnnotationTree annotationTree : modifiers.annotations()) { if (isJavaLangOverride(annotationTree.annotationType())) { return true; } } return false; }
Source:
static boolean isWithinTryHeader(Tree syntaxNode) { final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }

Target:
private static boolean isWithinTryHeader(Tree syntaxNode) { final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }
Source:
static boolean isTryStatementResource(VariableTree variable) { final TryStatementTree tryStatement = getEnclosingTryStatement(variable); if (tryStatement != null) { return tryStatement.resources().contains(variable); } return false; }

Target:
private static boolean isTryStatementResource(VariableTree variable) { final TryStatementTree tryStatement = getEnclosingTryStatement(variable); return tryStatement != null && tryStatement.resources().contains(variable); }
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:
public void newInstanceBis() throws IllegalAccessException, InstantiationException { if (constructor == null) { this.setDynaBeanClass(); } return ((DynaBean) constructor.newInstance(constructorValues)); }
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:
int increment_operator() { int i = 0; int b = 12; ++b; // Noncompliant int c = 0; foo(++c); // compliant not last element of block int j = -1; while ((j = foo(++j)) != -1) { System.out.println(""); } if(i != 0) { return i++; // Noncompliant } else { return ++i; } }
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:
ParametrizedTypeType(Symbol.TypeSymbol symbol, Map<TypeVariableType, Type> typeSubstitution) { super(symbol); this.rawType = symbol.getType(); this.typeSubstitution = typeSubstitution; }
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:
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()); checkArgument(ipProtocol.isPresent(), "Expected one of %s but was %s", Joiner.on(',').join(Permission.Policy.values()), value); return ipProtocol.get(); }

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 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:
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 ParseResponse(Json json, String propertyName) { this.json = json; this.propertyName = propertyName; }

Target:
protected ParseResponse(Json json, String propertyName) { this.json = json; this.propertyName = propertyName; }
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:
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 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:
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:
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:
public ProfitBricksTemplateBuilderLiveTest() { this.provider = "profitbricks-rest"; }
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:
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 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:
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 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:
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:
private AuthenticateRequest(@Provider Supplier<Credentials> splr) { authToken = splr.get(); checkNotNull(authToken.identity, "credential returned null"); }

Target:
AuthenticateRequest(@Provider Supplier<Credentials> splr) { authToken = splr.get(); checkNotNull(authToken.identity, "credential returned null"); }
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:
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"); properties.put(AUDIENCE, "https://login.microsoftonline.com/oauth2/token"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); return properties; }

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:
protected LoadBalancerListResponseHandler(DateCodecFactory dateCodec, ServerListResponseHandler balancedServerResponseHandler, FirewallListResponseHandler firewallListResponseHandler) { super(dateCodec, balancedServerResponseHandler, firewallListResponseHandler); this.loadBalancers = Lists.newArrayList(); }

Target:
LoadBalancerListResponseHandler(DateCodecFactory dateCodec, ServerListResponseHandler balancedServerResponseHandler, FirewallListResponseHandler firewallListResponseHandler) { super(dateCodec, balancedServerResponseHandler, firewallListResponseHandler); this.loadBalancers = Lists.newArrayList(); }
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:
private String parseMessage(HttpResponse response) { if (response.getPayload() == null) return null; try { return Strings2.toStringAndClose(response.getPayload().openStream()); } catch (IOException e) { throw Throwables.propagate(e); } }
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:
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 (IllegalArgumentException ex) { // expected exception } } }
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:
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(ComputeServiceProperties.IMAGE_LOGIN_USER, "root:password"); properties.setProperty(TEMPLATE, "osFamily=UBUNTU,os64Bit=true,osVersionMatches=1[012].[01][04]"); return properties; }
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:
public UserOptions build() { return addFilterOptions(this.options); }
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:
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(material.getBamboo().getLeaves().name()); }); }
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:
public static void init() { Debug.log("Loading Paper support module..."); // Events ScriptEvent.registerScriptEvent(new EntityKnocksbackEntityScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerEquipsArmorScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerJumpsPaperScriptEventImpl()); ScriptEvent.registerScriptEvent(new PlayerSpectatesEntityScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerStopsSpectatingScriptEvent()); ScriptEvent.registerScriptEvent(new ProjectileCollideScriptEvent()); ScriptEvent.registerScriptEvent(new TNTPrimesScriptEvent()); // Properties PropertyParser.registerProperty(EntityCanTick.class, EntityTag.class); }
Source:
public void adjust(Mechanism mechanism) { // <--[mechanism] // @object dEntity // @name max_fuse_ticks // @input Element(Integer) // @description // Sets the number of fuse ticks a creeper will default to when not triggered // @tags // <e@entity.max_fuse_ticks> // --> if (mechanism.matches("max_fuse_ticks") && entity.getBukkitEntity() instanceof Creeper && mechanism.requireInteger()) { ((Creeper) entity.getBukkitEntity()).setMaxFuseTicks(mechanism.getValue().asInt()); } }

Target:
public void adjust(Mechanism mechanism) { // <--[mechanism] // @object dEntity // @name max_fuse_ticks // @input Element(Number) // @description // Sets the default number of ticks until the creeper explodes when primed (NOT the time remaining if already primed). // @tags // <e@entity.max_fuse_ticks> // --> if (mechanism.matches("max_fuse_ticks") && mechanism.requireInteger()) { ((Creeper) entity.getBukkitEntity()).setMaxFuseTicks(mechanism.getValue().asInt()); } }
Source:
public String getAttribute(Attribute attribute) { if (attribute == null) { return null; } // <--[tag] // @attribute <e@entity.max_fuse_ticks> // @returns Element(Integer) // @mechanism dEntity.max_fuse_ticks // @group properties // @description // Returns the number of fuse ticks a creeper will default to when not triggered. // --> if (attribute.startsWith("max_fuse_ticks") && entity.getBukkitEntity() instanceof Creeper) { return new Element(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()) .getAttribute(attribute.fulfill(1)); } return null; }

Target:
public String getAttribute(Attribute attribute) { if (attribute == null) { return null; } // <--[tag] // @attribute <e@entity.max_fuse_ticks> // @returns Element(Number) // @mechanism dEntity.max_fuse_ticks // @group properties // @description // Returns the default number of ticks until the creeper explodes when primed (NOT the time remaining if already primed). // --> if (attribute.startsWith("max_fuse_ticks")) { return new Element(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()) .getAttribute(attribute.fulfill(1)); } return null; }
Source:
public synchronized void onSchoolDataWorkspaceUserDiscoveredEvent(@Observes SchoolDataWorkspaceUserDiscoveredEvent event) { //kun kurssille pelmahtaa uusi opiskelija UserEntity userEntity = userEntityController.findUserEntityByDataSourceAndIdentifier(event.getUserDataSource(), event.getUserIdentifier()); String userIdentifier = userEntity.getDefaultIdentifier(); String userDataSource = userEntity.getDefaultSchoolDataSource().getIdentifier(); SchoolDataIdentifier user = new SchoolDataIdentifier(userIdentifier, userDataSource); chatSyncController.syncStudent(user); }

Target:
public synchronized void onSchoolDataWorkspaceUserDiscoveredEvent(@Observes SchoolDataWorkspaceUserDiscoveredEvent event) { //kun kurssille pelmahtaa uusi opiskelija String userIdentifier = event.getUserIdentifier(); String userDataSource = event.getUserDataSource(); SchoolDataIdentifier user = new SchoolDataIdentifier(userIdentifier, userDataSource); chatSyncController.syncStudent(user); }
Source:
private boolean hasAccess(PID pid, String datastream) { // Defaults to jp2 surrogate if (datastream.equals("IMAGE_JP2000") || datastream == null) { datastream = JP2_ACCESS_COPY.getId(); } Permission permission = DatastreamPermissionUtil.getPermissionForDatastream(datastream); AgentPrincipals agent = AgentPrincipals.createFromThread(); LOG.debug("Checking if user has access to belonging to object {}.", agent.getUsername(), datastream, pid); return accessControlService.hasAccess(pid, agent.getPrincipals(), permission); }

Target:
private boolean hasAccess(PID pid, String datastream) { // Defaults to jp2 surrogate if (datastream == null) { datastream = JP2_ACCESS_COPY.getId(); } Permission permission = DatastreamPermissionUtil.getPermissionForDatastream(datastream); AgentPrincipals agent = AgentPrincipals.createFromThread(); LOG.debug("Checking if user has access to belonging to object {}.", agent.getUsername(), datastream, pid); return accessControlService.hasAccess(pid, agent.getPrincipals(), permission); }
Source:
byte[] textStream() { return "I am not an image".getBytes(); }

Target:
private byte[] textStream() { return "I am not an image".getBytes(); }
Source:
public static synchronized RegistryService getInstance() { RegistryService local = instance; if (local == null) { local = new RegistryService(); instance = local; // associates a reporter with the current registry ReporterFactory.getOrCreateReporter(); } return local; }

Target:
public static synchronized RegistryService getInstance() { if (instance == null) { instance = new RegistryService(); // associates a reporter with the current registry ReporterFactory.getOrCreateReporter(); } return instance; }
Source:
public BinaryObject replaceOriginalFile(InputStream contentStream, String filename, String mimetype, String sha1Checksum, String md5Checksum) { // Construct the path to where the original file will be created String objectPath = constructOriginalFilePath(); // Add the OriginalFile use type Model fileModel = ModelFactory.createDefaultModel(); Resource resc = fileModel.createResource(objectPath); resc.addProperty(RDF.type, PcdmUse.OriginalFile); return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, fileModel); }

Target:
public BinaryObject replaceOriginalFile(InputStream contentStream, String filename, String mimetype, String sha1Checksum, String md5Checksum) { return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, null); }
Source:
private URI createContentRoot(URI contentUri) { String contentRootString = URIUtil.join( contentUri, RepositoryPathConstants.CONTENT_ROOT_ID); URI contentRootUri = URI.create(contentRootString); // Don't initialize the object if it is already present. if (objectExists(contentRootUri)) { return contentUri; } Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(contentRootString); resc.addProperty(DC.title, "Content Collections Root"); objFactory.createContentRootObject(contentRootUri, model); return contentRootUri; }

Target:
private URI createContentRoot(URI contentUri) { String contentRootString = URIUtil.join( contentUri, RepositoryPathConstants.CONTENT_ROOT_ID); URI contentRootUri = URI.create(contentRootString); // Don't initialize the object if it is already present. if (objectExists(contentRootUri)) { return contentRootUri; } Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(contentRootString); resc.addProperty(DC.title, "Content Collections Root"); objFactory.createContentRootObject(contentRootUri, model); return contentRootUri; }
Source:
public void addCollectionObjectMemberTest() { CollectionObject childObj = new CollectionObject(workChildPid, repository, dataLoader); when(repository.createCollectionObject(any(PID.class), any(Model.class))) .thenReturn(childObj); collection.addMember(childObj); }

Target:
public void addCollectionObjectMemberTest() { CollectionObject childObj = new CollectionObject(workChildPid, repository, dataLoader); collection.addMember(childObj); }
Source:
public PremisEventBuilder addSoftwareAgent(String agent) { Model modelAgent = ModelFactory.createDefaultModel(); Resource softwareAgent = modelAgent.createResource("http://id.loc.gov/vocabulary/preservation/agentType/sof"); addAgent(Premis.hasEventRelatedAgentExecutor, softwareAgent, "#softwareAgent", agent); return this; }

Target:
public PremisEventBuilder addSoftwareAgent(String agent) { Model modelAgent = ModelFactory.createDefaultModel(); Resource softwareAgent = modelAgent.createResource(Premis.hasEventRelatedAgentExecutor); addAgent(Premis.hasEventRelatedAgentExecutor, softwareAgent, "#softwareAgent", agent); return this; }
Source:
public void testNonExistentVersion() throws Exception { // The referenced resource only an endpoint for v999.999 of the GlanceApi HttpResponse localVersionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload( payloadFromResourceWithContentType("/glanceVersionResponseVersionUnavailable.json", "application/json")).build(); GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, versionNegotiationRequest, localVersionNegotiationResponse); try { apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").list(); } catch (UncheckedExecutionException e) { if (e.getCause().getClass() == HttpException.class) return; } fail("Did not throw expected HttpException"); }

Target:
public void testNonExistentVersion() throws Exception { // The referenced resource only an endpoint for v999.999 of the GlanceApi HttpResponse localVersionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload( payloadFromResourceWithContentType("/glanceVersionResponseVersionUnavailable.json", "application/json")).build(); GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, versionNegotiationRequest, localVersionNegotiationResponse); apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").list(); }
Source:
protected static String getMessageId(String rawMessageHref) { // strip off everything but the message id return rawMessageHref.substring(rawMessageHref.lastIndexOf('/')+1); }

Target:
private static String getMessageId(String rawMessageHref) { // strip off everything but the message id return rawMessageHref.substring(rawMessageHref.lastIndexOf('/')+1); }
Source:
public HttpRequest filter(HttpRequest request) throws HttpException { String endpoint = request.getEndpoint().toString(); Pattern pattern = Pattern.compile("/[^/]*$"); // From last / to the end of the line Matcher matcher = pattern.matcher(endpoint); matcher.find(); String encodable = matcher.group(); String encoded = encodable.replace(".", "%2e"); String newEndpoint = matcher.replaceFirst(encoded); return request.toBuilder().endpoint(newEndpoint).build(); }

Target:
public HttpRequest filter(HttpRequest request) throws HttpException { String endpoint = request.getEndpoint().toString(); Matcher matcher = pattern.matcher(endpoint); if(!matcher.find()) return request; // do not modify if not found. This however is not expected to happen. String encodable = matcher.group(); String encoded = encodable.replace(".", "%2e"); String newEndpoint = matcher.replaceFirst(encoded); return request.toBuilder().endpoint(newEndpoint).build(); }
Source:
public CmdLineParser(Object bean, ParserProperties parserProperties) { // A 'return' in the constructor just skips the rest of the implementation // and returns the new object directly. if (bean==null) return; // Parse the metadata and create the setters new ClassParser().parse(bean,this); if (parserProperties.shouldSortOptions()) { // for display purposes, keep the arguments in argument order, but sort the options in alphabetical order Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } setUsageWidth(parserProperties.getUsageWidth()); }

Target:
public CmdLineParser(Object bean, ParserProperties parserProperties) { this.parserProperties = parserProperties; // A 'return' in the constructor just skips the rest of the implementation // and returns the new object directly. if (bean==null) return; // Parse the metadata and create the setters new ClassParser().parse(bean,this); if (parserProperties.shouldSortOptions()) { // for display purposes, keep the arguments in argument order, but sort the options in alphabetical order Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } }
Source:
public static void onUpgrade(Context context, SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion <= 2) { db.execSQL(QUERY_TABLE_DROP); onCreate(context, db); } else if (newVersion >= 3) { final String ALTER_TBL = "ALTER TABLE " + TABLENAME + " ADD COLUMN " + COLUMN_IS_PAID_ACCOUNT + " integer default 0;"; db.execSQL(ALTER_TBL); } }

Target:
public static void onUpgrade(Context context, SQLiteDatabase db, int oldVersion, int newVersion) { //Update database to add the Paid Account flag. This was introduced in DB version 3. if (oldVersion <= 2) { final String ALTER_TBL = "ALTER TABLE " + TABLENAME + " ADD COLUMN " + COLUMN_IS_PAID_ACCOUNT + " integer default 0;"; db.execSQL(ALTER_TBL); } }
Source:
public void testRetrieveKeyAndValueNull() { // setup target JdbcCodeList jdbcCodeList = new JdbcCodeList(); // setup parameters\ jdbcCodeList.setDataSource(dataSource); jdbcCodeList.setLabelColumn("valueColumn"); jdbcCodeList.setValueColumn("labelColumn"); jdbcCodeList.setQuerySql("Select code_id, code_name from codelist"); Map<String, String> mapOutput = jdbcCodeList.retrieveMap(); // assert assertThat(mapOutput.size(), is(0)); assertNull(mapOutput.get("valueColumn")); assertNull(mapOutput.get("labelColumn")); }

Target:
public void testRetrieveKeyAndValueNull() { // setup target JdbcCodeList jdbcCodeList = new JdbcCodeList(); // setup parameters\ jdbcCodeList.setDataSource(dataSource); jdbcCodeList.setLabelColumn("valueColumn"); jdbcCodeList.setValueColumn("labelColumn"); jdbcCodeList.setQuerySql("Select code_id, code_name from codelist"); Map<String, String> mapOutput = jdbcCodeList.retrieveMap(); // assert assertThat(mapOutput.size(), is(0)); }
Source:
public void onSaveButton(String scenarioType) { if (saveCommand != null) { simulationDescriptor.setSkipFromBuild(view.getSkipFromBuild().isChecked()); switch (ScenarioSimulationModel.Type.valueOf(scenarioType)) { case RULE: saveRuleSettings(); break; case DMN: saveDMNSettings(); break; } saveCommand.execute(); } }

Target:
public void onSaveButton(String scenarioType) { if (saveCommand != null) { simulationDescriptor.setSkipFromBuild(view.getSkipFromBuild().isChecked()); switch (ScenarioSimulationModel.Type.valueOf(scenarioType)) { case RULE: saveRuleSettings(); break; case DMN: saveDMNSettings(); break; default: // nop } saveCommand.execute(); } }
Source:
public void isExecutable_HeaderCellSelected() { when(scenarioGridModelMock.getSelectedCells()).thenReturn(Collections.emptyList()); when(scenarioGridModelMock.getSelectedHeaderCells()).thenReturn(Lists.create(selectedCell, selectedCell2)); assertTrue(handler.isExecutable(scenarioGridMock)); }

Target:
public void isExecutable_HeaderCellSelected() { when(scenarioGridModelMock.getSelectedCells()).thenReturn(Collections.emptyList()); when(scenarioGridModelMock.getSelectedHeaderCells()).thenReturn(Arrays.asList(selectedCell)); assertTrue(handler.isExecutable(scenarioGridMock)); }
Source:
public ScenarioGridColumn build() { List<GridColumn.HeaderMetaData> headerMetaDataList = headerBuilder.build(); ScenarioGridColumnRenderer actualScenarioGridColumnRenderer = scenarioGridColumnRenderer != null ? scenarioGridColumnRenderer : new ScenarioGridColumnRenderer(); ScenarioGridColumn scenarioGridColumn = new ScenarioGridColumn(headerMetaDataList, actualScenarioGridColumnRenderer, width, isMovable, factoryCell, placeHolder ); // by default scenario columns should be auto to have auto resize scenarioGridColumn.setColumnWidthMode(GridColumn.ColumnWidthMode.auto); scenarioGridColumn.setMinimumWidth(width); return scenarioGridColumn; }

Target:
public ScenarioGridColumn build() { List<GridColumn.HeaderMetaData> headerMetaDataList = headerBuilder.build(); ScenarioGridColumnRenderer actualScenarioGridColumnRenderer = scenarioGridColumnRenderer != null ? scenarioGridColumnRenderer : new ScenarioGridColumnRenderer(); return new ScenarioGridColumn(headerMetaDataList, actualScenarioGridColumnRenderer, width, isMovable, factoryCell, placeHolder ); }
Source:
public IndexBuilder fillIndexBuilder(final Path path) throws Exception { InputStream inputStream = null; try { inputStream = ioService.newInputStream(path, StandardOpenOption.READ); final String drl = DecisionTableFactory.loadFromInputStream(inputStream, null); return fillDrlIndexBuilder(path, drl); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // no-op } } } }

Target:
public IndexBuilder fillIndexBuilder(final Path path) throws Exception { try (final InputStream inputStream = ioService.newInputStream(path, StandardOpenOption.READ)) { final String drl = DecisionTableFactory.loadFromInputStream(inputStream, null); return fillDrlIndexBuilder(path, drl); } }
Source:
public ScenarioSimulationEditorPresenter(final Caller<ScenarioSimulationService> service, final ScenarioSimulationResourceType type, final ImportsWidgetPresenter importsWidget, final AsyncPackageDataModelOracleFactory oracleFactory) { super(); this.baseView = newScenarioSimulationView(); // Indirection added for test-purpose this.service = service; this.type = type; this.importsWidget = importsWidget; this.oracleFactory = oracleFactory; }

Target:
public ScenarioSimulationEditorPresenter(final Caller<ScenarioSimulationService> service, final ScenarioSimulationResourceType type, final ImportsWidgetPresenter importsWidget, final AsyncPackageDataModelOracleFactory oracleFactory) { super(); this.view = newScenarioSimulationView(); // Indirection added for test-purpose this.baseView = view; this.service = service; this.type = type; this.importsWidget = importsWidget; this.oracleFactory = oracleFactory; }
Source:
public int hashCode() { int result = severity != null ? severity.hashCode() : 0; result = 31 * result + (rowNumbers != null ? rowNumbers.hashCode() : 0); result = 31 * result + (checkType != null ? checkType.hashCode() : 0); result = 31 * result + (debugMessage != null ? debugMessage.hashCode() : 0); return result; }

Target:
public int hashCode() { int result = severity != null ? ~~severity.hashCode() : 0; result = 31 * result + (rowNumbers != null ? ~~rowNumbers.hashCode() : 0); result = 31 * result + (checkType != null ? ~~checkType.hashCode() : 0); result = 31 * result + (debugMessage != null ? ~~debugMessage.hashCode() : 0); return ~~result; }
Source:
protected String[] getDuplicates() { System.out.println("getting duplicates"); return duplicates; }

Target:
protected String[] getDuplicates() { return duplicates; }
Source:
void initialiseLockManager() { lockManager.init( new LockTarget( currentPath, parent.getView().asWidget(), placeRequest, new LockTarget.TitleProvider() { @Override public String getTitle() { return currentPath.getFileName() + " - " + resourceType.getDescription(); } }, new Runnable() { @Override public void run() { //Nothing to do } } ), parent ); }

Target:
void initialiseLockManager() { lockManager.init( new LockTarget( currentPath, parent.getView().asWidget(), placeRequest, () -> currentPath.getFileName() + " - " + resourceType.getDescription(), () -> {/*nothing*/} ), parent ); }
Source:
public static Boolean isZip(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(ZIP_SUFFIX); // Technically a file named `.zip` would be fine }

Target:
public static boolean isZip(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(ZIP_SUFFIX); // Technically a file named `.zip` would be fine }
Source:
public void enableFirewall(boolean enabled) { if(this.enabled != enabled) { logger.info("Setting firewall to {}", enabled); this.enabled = enabled; List<Masked<U64>> changes = new ArrayList<Masked<U64>>(); changes.add(Masked.of(DEFAULT_COOKIE, AppCookie.getAppFieldMask())); // Add announcement that all firewall decisions changed routingService.handleRoutingDecisionChange(changes); } }

Target:
public void enableFirewall(boolean enabled) { if(this.enabled != enabled) { logger.info("Setting firewall to {}", enabled); this.enabled = enabled; List<Masked<U64>> changes = ImmutableList.of( Masked.of(DEFAULT_COOKIE, AppCookie.getAppFieldMask()) ); // Add announcement that all firewall decisions changed routingService.handleRoutingDecisionChange(changes); } }
Source:
public void destroyNode(String id) { // stop it first try { suspendNode(id); // wait until fully stopped serverStopped.apply(id); } catch (Exception e) { // ignore e.printStackTrace(); } api.getVirtualServerApi().destroy(id); // wait until fully destroyed String systemId = toSystemId.apply(id); systemNormal.apply(systemId); }

Target:
public void destroyNode(String id) { // stop it first suspendNode(id); // wait until fully stopped serverStopped.apply(id); api.getVirtualServerApi().destroy(id); // wait until fully destroyed String systemId = toSystemId.apply(id); systemNormal.apply(systemId); }
Source:
private Map<TopicPartition, Long> committedOffsetForChangelogs(final Set<TopicPartition> partitions) { final Map<TopicPartition, Long> committedOffsets; try { committedOffsets = fetchCommittedOffsets(partitions, mainConsumer); } catch (final StreamsException e) { if (e.getCause() instanceof TimeoutException) { // if it timed out we just retry next time return Collections.emptyMap(); } else { throw e; } } lastUpdateOffsetTime = time.milliseconds(); return committedOffsets; }

Target:
private Map<TopicPartition, Long> committedOffsetForChangelogs(final Set<TopicPartition> partitions) { final Map<TopicPartition, Long> committedOffsets; try { committedOffsets = fetchCommittedOffsets(partitions, mainConsumer); } catch (final TimeoutException e) { // if it timed out we just retry next time return Collections.emptyMap(); } lastUpdateOffsetTime = time.milliseconds(); return committedOffsets; }
Source:
public void awaitAllFutures() { Future<?> future = null; while ((future = futures.poll()) != null) { try { future.get(); } catch (InterruptedException | ExecutionException e) { log.error("Encountered an error while awaiting an errant record future's completion."); throw new ConnectException(e); } } }

Target:
public void awaitAllFutures() { Future<?> future; while ((future = futures.poll()) != null) { try { future.get(); } catch (InterruptedException | ExecutionException e) { log.error("Encountered an error while awaiting an errant record future's completion."); throw new ConnectException(e); } } }
Source:
public RemoveMembersFromConsumerGroupOptions() { this.members = Collections.emptySet();; }

Target:
public RemoveMembersFromConsumerGroupOptions() { this.members = Collections.emptySet(); }
Source:
public Map<String, String> connectorConfig(String connName) { FutureCallback<Map<String, String>> connectorConfigCallback = new FutureCallback<>(); herder.connectorConfig(connName, connectorConfigCallback); try { return new HashMap<>(connectorConfigCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS);); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new ConnectException( String.format("Failed to retrieve configuration for connector '%s'", connName), e ); } }

Target:
public Map<String, String> connectorConfig(String connName) { FutureCallback<Map<String, String>> connectorConfigCallback = new FutureCallback<>(); herder.connectorConfig(connName, connectorConfigCallback); try { return new HashMap<>(connectorConfigCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS)); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new ConnectException( String.format("Failed to retrieve configuration for connector '%s'", connName), e ); } }
Source:
public void close() { ConnectException e = new ConnectException("Failed to close all reporters"); for (ErrorReporter reporter : reporters) { try { reporter.close(); } catch (Throwable t) { e.addSuppressed(t); } } if (e.getSuppressed().length > 0) { throw e; } }

Target:
public void close() { ConnectException e = null; for (ErrorReporter reporter : reporters) { try { reporter.close(); } catch (Throwable t) { e = e != null ? e : new ConnectException("Failed to close all reporters"); e.addSuppressed(t); } } if (e != null) { throw e; } }
Source:
public void close() { lock.writeLock().lock(); try { final LinkedList<RuntimeException> suppressed = executeAll( () -> cache.flush(cacheName), () -> cache.close(cacheName), wrapped()::close ); if (suppressed != null && !suppressed.isEmpty()) { throwSuppressed("Caught an exception while closing caching key value store for store " + name(), suppressed); } } finally { lock.writeLock().unlock(); } }

Target:
public void close() { lock.writeLock().lock(); try { final LinkedList<RuntimeException> suppressed = executeAll( () -> cache.flush(cacheName), () -> cache.close(cacheName), wrapped()::close ); if (!suppressed.isEmpty()) { throwSuppressed("Caught an exception while closing caching key value store for store " + name(), suppressed); } } finally { lock.writeLock().unlock(); } }
Source:
public void enforceRestoreActive() { if (state != ChangelogReaderState.ACTIVE_RESTORING) { log.debug("Transiting to restore active tasks: {}", changelogs); // pause all partitions that are for standby tasks from the restore consumer pauseChangelogsFromRestoreConsumer(standbyRestoringChangelogs()); } state = ChangelogReaderState.ACTIVE_RESTORING; }

Target:
public void enforceRestoreActive() { if (state != ChangelogReaderState.ACTIVE_RESTORING) { log.debug("Transiting to restore active tasks: {}", changelogs); // pause all partitions that are for standby tasks from the restore consumer pauseChangelogsFromRestoreConsumer(standbyRestoringChangelogs()); state = ChangelogReaderState.ACTIVE_RESTORING; } }
Source:
ClientMetadata(final String endPoint) { // get the host info if possible hostInfo = endPoint != null ? HostInfo.buildFromEndpoint(endPoint) : null; // initialize the consumer memberIds consumers = new HashSet<>(); // initialize the client state state = new ClientState(); }

Target:
ClientMetadata(final String endPoint) { // get the host info, or null if no endpoint is configured (ie endPoint == null) hostInfo = HostInfo.buildFromEndpoint(endPoint); // initialize the consumer memberIds consumers = new HashSet<>(); // initialize the client state state = new ClientState(); }
Source:
public void shouldNotPutIfSameValuesAndGreaterTimestamp() { expectLastCall(); init(); metered.put(key, valueAndTimestamp); final ValueAndTimestampSerde<String> stringSerde = new ValueAndTimestampSerde<>(Serdes.String()); final byte[] encodedOldValue = stringSerde.serializer().serialize("TOPIC", valueAndTimestamp); final ValueAndTimestamp<String> newValueAndTimestamp = ValueAndTimestamp.make("value", 98L); assertFalse(metered.putIfDifferentValues(key, newValueAndTimestamp, encodedOldValue)); verify(inner); }

Target:
public void shouldNotPutIfSameValuesAndGreaterTimestamp() { init(); metered.put(key, valueAndTimestamp); final ValueAndTimestampSerde<String> stringSerde = new ValueAndTimestampSerde<>(Serdes.String()); final byte[] encodedOldValue = stringSerde.serializer().serialize("TOPIC", valueAndTimestamp); final ValueAndTimestamp<String> newValueAndTimestamp = ValueAndTimestamp.make("value", 98L); assertFalse(metered.putIfDifferentValues(key, newValueAndTimestamp, encodedOldValue)); verify(inner); }
Source:
public ConsumerGroupListing(String groupId, boolean isSimpleConsumerGroup, Optional<ConsumerGroupState> state) { Objects.requireNonNull(state); this.groupId = groupId; this.isSimpleConsumerGroup = isSimpleConsumerGroup; this.state = state; }

Target:
public ConsumerGroupListing(String groupId, boolean isSimpleConsumerGroup, Optional<ConsumerGroupState> state) { this.groupId = groupId; this.isSimpleConsumerGroup = isSimpleConsumerGroup; this.state = Objects.requireNonNull(state); }