auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void makeRollback(OMicroTransaction microTransaction, Exception e) { // WE NEED TO CALL ROLLBACK HERE, IN THE LOCK OLogManager.instance().debug(this, "Error during micro-transaction commit, micro-transaction will be rolled back (tx-id=%d)", e, microTransaction.getId()); rollback(microTransaction); if (e instanceof OException) throw ((OException) e); else throw OException.wrapException(new OStorageException("Error during micro-transaction commit"), e); }

Target:
private void makeRollback(OMicroTransaction microTransaction, Exception e) { // WE NEED TO CALL ROLLBACK HERE, IN THE LOCK OLogManager.instance().debug(this, "Error during micro-transaction commit, micro-transaction will be rolled back (tx-id=%d)", e, microTransaction.getId()); rollback(microTransaction); if (e instanceof RuntimeException) throw ((RuntimeException) e); else throw OException.wrapException(new OStorageException("Error during micro-transaction commit"), e); }
Source:
private String buildKeyName(long keynum) { if (!orderedinserts) { keynum = Utils.hash(keynum); } String value = Long.toString(keynum); int fill = zeropadding - value.length(); String prekey = "user"; for (int i = 0; i < fill; i++) { prekey += '0'; } return prekey + value; }

Target:
protected String buildKeyName(long keynum) { if (!orderedinserts) { keynum = Utils.hash(keynum); } String value = Long.toString(keynum); int fill = zeropadding - value.length(); String prekey = "user"; for (int i = 0; i < fill; i++) { prekey += '0'; } return prekey + value; }
Source:
public void run() { try { Thread.sleep(timeout); this.timedout.setIsSatisfied(true); } catch (InterruptedException e) { // Do nothing. Kept just to remove Check-style build error. byte a = 0; } }

Target:
public void run() { try { Thread.sleep(timeout); this.timedout.setIsSatisfied(true); } catch (InterruptedException e) { // Do nothing. } }
Source:
public void setup() { try { orientDBClient = new OrientDBClient(); Properties p = new Properties(); // TODO: Extract the property names into final variables in OrientDBClient p.setProperty("orientdb.url", TEST_DB_URL); orientDBClient.setProperties(p); orientDBClient.init(); orientDBConnection = new ODatabaseDocumentTx(TEST_DB_URL).open("admin","admin"); orientDBDictionary = orientDBConnection.getMetadata().getIndexManager().getDictionary(); } catch (DBException e) { e.printStackTrace(); fail("Could not create OrientDBClient instance"); } }

Target:
public void setup() throws DBException { orientDBClient = new OrientDBClient(); Properties p = new Properties(); // TODO: Extract the property names into final variables in OrientDBClient p.setProperty("orientdb.url", TEST_DB_URL); orientDBClient.setProperties(p); orientDBClient.init(); orientDBConnection = new ODatabaseDocumentTx(TEST_DB_URL).open("admin","admin"); orientDBDictionary = orientDBConnection.getMetadata().getIndexManager().getDictionary(); }
Source:
@Test public void injectingView() { final JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( "package test;", "import android.app.Activity;", "import android.view.View;", "import butterknife.InjectView;", "public class Test extends Activity {", " @InjectView(1) View thing;", "}")); ASSERT.about(javaSource()).that(source) .processedWith(butterknifeProcessors()) .compilesWithoutError(); // TODO: confirm generated source (should expect test.Test$$ViewInjector.java) }

Target:
public void injectingView() { final JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( "package test;", "import android.app.Activity;", "import android.view.View;", "import butterknife.InjectView;", "public class Test extends Activity {", " @InjectView(1) View thing;", "}")); ASSERT.about(javaSource()).that(source) .processedWith(butterknifeProcessors()) .compilesWithoutError(); // TODO: confirm generated source (should expect test.Test$$ViewInjector.java) }
Source:
public TrackStatistics (final long trackId, ContentResolver cr) { this.trackId = trackId; contentResolver = cr; length = 0; maxSpeed = 0; pointCount = 0; timeMoving = 0; update(); }

Target:
public TrackStatistics (final long trackId, ContentResolver cr) { this.trackId = trackId; contentResolver = cr; // pointCount, length, maxSpeed and timeMoving are all implicitly initialized to // zero, which is what we need update(); }
Source:
public void cleanTriggers() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.addTrigger(new PeriodicFolderTrigger("30m")); s.removeTrigger(new PeriodicFolderTrigger("30m")); assertEquals(0, s.getTriggers().size()); }

Target:
public void cleanTriggers() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.addTrigger(new PeriodicFolderTrigger("30m")); assertEquals(1, s.getTriggers().size()); s.removeTrigger(new PeriodicFolderTrigger("30m")); assertEquals(0, s.getTriggers().size()); }
Source:
public synchronized HttpResponse doStop() throws IOException, ServletException { Executor e = Executor.of(this); if (e == null) { for (Computer c : Jenkins.getActiveInstance().getComputers()) { for (Executor e1 : c.getOneOffExecutors()) { if (e1.getCurrentExecutable() == this) e = e1; } } } if (e != null) { return e.doStop(); } else { // nothing is building return HttpResponses.forwardToPreviousPage(); } }

Target:
public synchronized HttpResponse doStop() throws IOException, ServletException { Executor e = Executor.of(this); if (e != null) { return e.doStop(); } else { // nothing is building return HttpResponses.forwardToPreviousPage(); } }
Source:
public void onRenamed(I item, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName, (I) item); // For compatibility with old views: for (View v : views) { v.onJobRenamed(item, oldName, newName); } save(); }

Target:
public void onRenamed(I item, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName, item); // For compatibility with old views: for (View v : views) { v.onJobRenamed(item, oldName, newName); } save(); }
Source:
protected HttpURLConnection openConnection(String url) throws IOException { URL requestedURL; try { requestedURL = new URL(url); } catch (MalformedURLException e) { throw new IOException("Attempted to use malformed url: " + url); } HttpURLConnection connection = (HttpURLConnection)requestedURL.openConnection(); connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS); connection.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("User-Agent", USER_AGENT); connection.setDoInput(true); return connection; }

Target:
protected HttpURLConnection openConnection(String url) throws IOException { URL requestedURL; try { requestedURL = new URL(url); } catch (MalformedURLException e) { throw new IOException("Attempted to use malformed url: " + url, e); } HttpURLConnection connection = (HttpURLConnection) requestedURL.openConnection(); connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS); connection.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("User-Agent", USER_AGENT); connection.setDoInput(true); return connection; }
Source:
@Override public void initialize(Analytics analytics, ValueMap settings) throws IllegalStateException { if (!isOnClassPath("android.support.v4.app.Fragment")) { throw new IllegalStateException("Kahuna requires the support library to be bundled."); } trackAllPages = settings.getBoolean("trackAllPages", true); KahunaAnalytics.onAppCreate(analytics.getApplication(), settings.getString("apiKey"), settings.getString("pushSenderId")); LogLevel logLevel = analytics.getLogLevel(); KahunaAnalytics.setDebugMode(logLevel == INFO || logLevel == VERBOSE); }

Target:
@Override public void initialize(Analytics analytics, ValueMap settings) throws IllegalStateException { if (!isOnClassPath("android.support.v4.app.Fragment")) { throw new IllegalStateException("Kahuna requires the support library to be bundled."); } trackAllPages = settings.getBoolean("trackAllPages", false); KahunaAnalytics.onAppCreate(analytics.getApplication(), settings.getString("apiKey"), settings.getString("pushSenderId")); LogLevel logLevel = analytics.getLogLevel(); KahunaAnalytics.setDebugMode(logLevel == INFO || logLevel == VERBOSE); }
Source:
@Override void initialize(Context context, JsonMap settings) throws InvalidConfigurationException { if (!hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) { throw new InvalidConfigurationException( "AppsFlyer requires the ACCESS_NETWORK_STATE permission"); } AppsFlyerLib.setAppsFlyerKey(settings.getString("appsFlyerDevKey")); AppsFlyerLib.setUseHTTPFalback(settings.getBoolean("httpFallback")); this.context = context; }

Target:
@Override void initialize(Context context, JsonMap settings) throws InvalidConfigurationException { if (!hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) { throw new InvalidConfigurationException( "AppsFlyer requires the ACCESS_NETWORK_STATE permission"); } AppsFlyerLib.setAppsFlyerKey(settings.getString("appsFlyerDevKey")); AppsFlyerLib.setUseHTTPFalback(settings.getBoolean("httpFallback", false)); this.context = context; }
Source:
public AbstractPool(ConnectionManager cm, PoolConfiguration pc) { this.cm = cm; this.poolConfiguration = pc; this.pools = new ConcurrentHashMap<Credential, ManagedConnectionPool>(); this.transactionMap = new ConcurrentHashMap<Object, Map<ManagedConnectionPool, ConnectionListener>>(); this.semaphore = new Semaphore(poolConfiguration.getMaxSize()); this.shouldPrefill = pc.isPrefill(); // || pc.isStrictMin(); }

Target:
public AbstractPool(ConnectionManager cm, PoolConfiguration pc) { this.cm = cm; this.poolConfiguration = pc; this.pools = new ConcurrentHashMap<Credential, ManagedConnectionPool>(); this.transactionMap = new ConcurrentHashMap<Object, Map<ManagedConnectionPool, ConnectionListener>>(); this.semaphore = new Semaphore(poolConfiguration.getMaxSize()); }
Source:
private void changePassword(User user, JsonObject json) { String password = JsonUtils.getString(json, "password"); if (Strings.isNullOrEmpty(password)) { // Dont' change the password throw BennuCoreDomainException.passwordIsEmpty(); } String passwordCheck = JsonUtils.getString(json, "passwordCheck"); if (!Objects.equals(password, passwordCheck)) { throw BennuCoreDomainException.passwordCheckDoesNotMatch(); } //avoid same password if (user.matchesPassword(password)) { throw BennuCoreDomainException.passwordIsTheSame(); } user.changePassword(password); }

Target:
private void changePassword(User user, JsonObject json) { String password = JsonUtils.getString(json, "password"); if (Strings.isNullOrEmpty(password)) { // Don't change the password. return; } String passwordCheck = JsonUtils.getString(json, "passwordCheck"); if (!Objects.equals(password, passwordCheck)) { throw BennuCoreDomainException.passwordCheckDoesNotMatch(); } //avoid same password if (user.matchesPassword(password)) { throw BennuCoreDomainException.passwordIsTheSame(); } user.changePassword(password); }
Source:
public void onClick(View v) { if(v.getId() == R.id.twitter_login){ TwitterAuthorizationTask task = new TwitterAuthorizationTask(); getInjector().injectMembers(task); task.execute(); } }

Target:
public void onClick(View v) { if(v.getId() == R.id.twitter_login){ TwitterAuthorizationTask task = new TwitterAuthorizationTask(); task.execute(); } }
Source:
private void getData(String sessionId) { if (sessionId.equals(this.sessionId)) { // data already fetched return; } // fetch data this.sessionId = sessionId; SessionMatchingSetup sessionMatchingSetup = new SessionMatchingSetup( databaseService.getWebClientProperties().isShowOnlyMatchedTests(), EnumSet.of(SessionMatchingSetup.MatchBy.ALL)); RootNode controlTree = databaseService.getControlTreeForSessions( new HashSet<String>(Arrays.asList(sessionId)), sessionMatchingSetup); fetchSessionScopeData(controlTree); fetchPerTestData(controlTree); }

Target:
private void getData(String sessionId) { if (sessionId.equals(this.sessionId)) { // data already fetched return; } // fetch data this.sessionId = sessionId; SessionMatchingSetup sessionMatchingSetup = new SessionMatchingSetup( true, EnumSet.of(SessionMatchingSetup.MatchBy.ALL)); RootNode controlTree = databaseService.getControlTreeForSessions( new HashSet<String>(Arrays.asList(sessionId)), sessionMatchingSetup); fetchSessionScopeData(controlTree); fetchPerTestData(controlTree); }
Source:
public synchronized List<TagDto> getAllTags() { List<TagEntity> tags = (List<TagEntity>) (entityManager.createQuery("select te from TagEntity as te")).getResultList(); List<TagDto> allTags = new ArrayList<TagDto>(); if (!tags.isEmpty()) { for (TagEntity tagEntity : tags) { allTags.add(new TagDto(tagEntity.getName(), tagEntity.getDescription())); } } return allTags; }

Target:
public List<TagDto> getAllTags() { List<TagEntity> tags = (List<TagEntity>) (entityManager.createQuery("select te from TagEntity as te")).getResultList(); List<TagDto> allTags = new ArrayList<TagDto>(); if (!tags.isEmpty()) { for (TagEntity tagEntity : tags) { allTags.add(new TagDto(tagEntity.getName(), tagEntity.getDescription())); } } return allTags; }
Source:
private boolean shouldProcess(final Triple triple) { return triple != null && triple.getSubject().isURI() && triple.getSubject().toString() .startsWith(prefix == null ? "" : prefix) && TO_RESOLVE.contains(triple.getPredicate().toString()) & !(triple.getObject().isLiteral()); }

Target:
private boolean shouldProcess(final Triple triple) { return triple != null && triple.getSubject().isURI() && triple.getSubject().toString() .startsWith(prefix == null ? "" : prefix) && TO_RESOLVE.contains(triple.getPredicate().toString()) && !(triple.getObject().isLiteral()); }
Source:
public void onActivate(ActivateEvent event, EntityRef entity) { blockFactory = new BlockItemFactory(entityManager); inventoryManager = new InventoryAuthoritySystem(); EntityRef flagTaker = event.getInstigator(); // If the flag being taken is a red flag and the player is on the black team, let them take the flag if (!playerTeamMatchesFlagTeam(entity, flagTaker)) { giveFlagToPlayer(entity, flagTaker); attachParticleEmitterToPlayer(flagTaker); } }

Target:
public void onActivate(ActivateEvent event, EntityRef entity) { EntityRef flagTaker = event.getInstigator(); // If the flag being taken is a red flag and the player is on the black team, let them take the flag if (!playerTeamMatchesFlagTeam(entity, flagTaker)) { giveFlagToPlayer(entity, flagTaker); } }
Source:
public void initialise() { for (EntityRef entity : entityManager.getEntitiesWith(ScoreComponent.class)) { scoreEntity = entity; score = scoreEntity.getComponent(ScoreComponent.class); } if (!scoreEntity.equals(EntityRef.NULL)) { scoreArea = find("scoreArea", UIText.class); scoreArea.bindText(new ReadOnlyBinding<String>() { @Override public String get() { return String.valueOf(score.blackScore); } }); } // String scoreText = "Red Team: " + redScore + " " + // "Black Team: " + blackScore; // scoreArea.setText(String.format(scoreText)); }

Target:
public void initialise() { }
Source:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class).extendBy(0, 0, 0); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }

Target:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }
Source:
public JsonElement serialize(JsonSerializationContext context) { JsonObject serialized = context.serialize(flag).getAsJsonObject(); // Alias "comment" (the flag field containing the comment that the user submitted) to avoid ambiguity. // Should match the field name used for org.ambraproject.rhino.view.comment.CommentFlagInputView.body. serialized.add("body", serialized.remove("comment")); if (flag.getUserProfileId() != null) { serialized.remove("userProfileID"); serialized.add("creator", context.serialize(new UserIdView(flag.getUserProfileId()))); } serialized.add("flaggedComment", context.serialize(flaggedComment)); return serialized; }

Target:
public JsonElement serialize(JsonSerializationContext context) { JsonObject serialized = context.serialize(flag).getAsJsonObject(); // Alias "comment" (the flag field containing the comment that the user submitted) to avoid ambiguity. // Should match the field name used for org.ambraproject.rhino.view.comment.CommentFlagInputView.body. serialized.add("body", serialized.remove("comment")); serialized.remove("userProfileID"); if (flag.getUserProfileId() != null) { serialized.add("creator", context.serialize(new UserIdView(flag.getUserProfileId()))); } serialized.add("flaggedComment", context.serialize(flaggedComment)); return serialized; }
Source:
public BurstableUnlimitedMode getBurstableUnlimitedMode() { if (burstableUnlimitedMode == null) { // For backward-compatibility. return t2Unlimited ? BurstableUnlimitedMode.ENABLED : BurstableUnlimitedMode.DEFAULT; } return burstableUnlimitedMode; }

Target:
public BurstableUnlimitedMode getBurstableUnlimitedMode() { return burstableUnlimitedMode; }
Source:
private PrintLayer createMyPlacesPrintLayer(int categoryId, LayerProperties requestedLayer) { int opacity = requestedLayer.getOpacity() != null ? requestedLayer.getOpacity() : 100; if (opacity <= 0) { // Ignore fully transparent layers return null; } PrintLayer layer = new PrintLayer(); layer.setId(categoryId); layer.setType("myplaces"); layer.setVersion("1.3.0"); layer.setName("oskari:my_places_categories"); layer.setSrsName("EPSG:3067"); layer.setOpacity(opacity); return layer; }

Target:
private PrintLayer createMyPlacesPrintLayer(int categoryId, LayerProperties requestedLayer) { int opacity = requestedLayer.getOpacity() != null ? requestedLayer.getOpacity() : 100; if (opacity <= 0) { // Ignore fully transparent layers return null; } PrintLayer layer = new PrintLayer(); layer.setId(categoryId); layer.setType("myplaces"); layer.setVersion("1.3.0"); layer.setName("oskari:my_places_categories"); layer.setOpacity(opacity); return layer; }
Source:
private Set<String> getSchemaSQLServerNames(DatabaseMetaData metaData) throws SQLException { // Distinct schema names. metaData.getTables() is a denormalized // resultset Set<String> schemas = new HashSet<>(); ResultSet rs = metaData.getTables(_catalogName, null, null, JdbcUtils.getTableTypesAsStrings(_tableTypes)); while (rs.next()) { schemas.add(rs.getString("TABLE_SCHEM")); } FileHelper.safeClose(rs); return schemas; }

Target:
private Set<String> getSchemaSQLServerNames(DatabaseMetaData metaData) throws SQLException { // Distinct schema names. metaData.getTables() is a denormalized // resultset Set<String> schemas = new HashSet<>(); ResultSet rs = null; try { rs = metaData.getTables(_catalogName, null, null, JdbcUtils.getTableTypesAsStrings(_tableTypes)); while (rs.next()) { schemas.add(rs.getString("TABLE_SCHEM")); } }finally { FileHelper.safeClose(rs); } return schemas; }
Source:
private boolean isEnabled() { DataSourceInitializationMode mode = this.properties.getInitializationMode(); if (mode == DataSourceInitializationMode.NEVER) { return false; } return mode != DataSourceInitializationMode.EMBEDDED || isEmbedded(); }

Target:
private boolean isEnabled() { DataSourceInitializationMode mode = this.properties.getInitializationMode(); if (mode == DataSourceInitializationMode.NEVER) { return false; } if (mode == DataSourceInitializationMode.EMBEDDED && !isEmbedded()) { return false; } return true; }
Source:
private boolean isHelpShown(Command command) { return !(command instanceof HelpCommand) && !(command instanceof HintCommand); }

Target:
private boolean isHelpShown(Command command) { if (command instanceof HelpCommand || command instanceof HintCommand) { return false; } return true; }
Source:
private List<Mojo> parseMojos(Node plugin) throws XPathExpressionException { List<Mojo> mojos = new ArrayList<>(); for (Node mojoNode : nodesAt("//plugin/mojos/mojo", plugin)) { mojos.add(new Mojo(textAt("goal", mojoNode), format(requireNonNull(textAt("description", mojoNode))), parseParameters(mojoNode))); } return mojos; }

Target:
private List<Mojo> parseMojos(Node plugin) throws XPathExpressionException { List<Mojo> mojos = new ArrayList<>(); for (Node mojoNode : nodesAt("//plugin/mojos/mojo", plugin)) { mojos.add(new Mojo(textAt("goal", mojoNode), format(textAt("description", mojoNode)), parseParameters(mojoNode))); } return mojos; }
Source:
default String getServletUrlMapping() { if ("".equals(getPath()) || "/".equals(getPath())) { return "/"; } if (getPath().contains("*")) { return getPath(); } if (getPath().endsWith("/")) { return getPath() + "*"; } return getPath() + "/*"; }

Target:
default String getServletUrlMapping() { if (getPath().equals("") || getPath().equals("/")) { return "/"; } if (getPath().contains("*")) { return getPath(); } if (getPath().endsWith("/")) { return getPath() + "*"; } return getPath() + "/*"; }
Source:
default String getUrlMapping() { String path = getPath(); if (!path.startsWith("/")) { path = "/" + path; } if ("/".equals(path)) { return "/*"; } if (path.contains("*")) { return path; } if (path.endsWith("/")) { return path + "*"; } return path + "/*"; }

Target:
default String getUrlMapping() { String path = getPath(); if (!path.startsWith("/")) { path = "/" + path; } if (path.equals("/")) { return "/*"; } if (path.contains("*")) { return path; } if (path.endsWith("/")) { return path + "*"; } return path + "/*"; }
Source:
private void disableGrabResolvers(List<? extends AnnotatedNode> nodes) { for (AnnotatedNode classNode : nodes) { List<AnnotationNode> annotations = classNode.getAnnotations(); for (AnnotationNode node : new ArrayList<>(annotations)) { if ("GrabResolver".equals(node.getClassNode().getNameWithoutPackage())) { node.setMember("initClass", new ConstantExpression(false)); } } } }

Target:
private void disableGrabResolvers(List<? extends AnnotatedNode> nodes) { for (AnnotatedNode classNode : nodes) { List<AnnotationNode> annotations = classNode.getAnnotations(); for (AnnotationNode node : new ArrayList<>(annotations)) { if (node.getClassNode().getNameWithoutPackage().equals("GrabResolver")) { node.setMember("initClass", new ConstantExpression(false)); } } } }
Source:
private void addUrl(URL url) { if ("file".equals(url.getProtocol()) && url.getPath().endsWith("/")) { try { this.folders.add(ResourceUtils.getFile(url)); } catch (Exception ex) { logger.warn(LogMessage.format("Unable to get classpath URL %s", url)); logger.trace(LogMessage.format("Unable to get classpath URL %s", url), ex); } } }

Target:
private void addUrl(URL url) { if (url.getProtocol().equals("file") && url.getPath().endsWith("/")) { try { this.folders.add(ResourceUtils.getFile(url)); } catch (Exception ex) { logger.warn(LogMessage.format("Unable to get classpath URL %s", url)); logger.trace(LogMessage.format("Unable to get classpath URL %s", url), ex); } } }
Source:
protected boolean isMain(Thread thread) { return "main".equals(thread.getName()) && thread.getContextClassLoader().getClass().getName().contains("AppClassLoader"); }

Target:
protected boolean isMain(Thread thread) { return thread.getName().equals("main") && thread.getContextClassLoader().getClass().getName().contains("AppClassLoader"); }
Source:
public void execute() throws MojoExecutionException, MojoFailureException { if ("pom".equals(this.project.getPackaging())) { getLog().debug("repackage goal could not be applied to pom project."); return; } if (this.skip) { getLog().debug("skipping repackaging as per configuration."); return; } repackage(); }

Target:
public void execute() throws MojoExecutionException, MojoFailureException { if (this.project.getPackaging().equals("pom")) { getLog().debug("repackage goal could not be applied to pom project."); return; } if (this.skip) { getLog().debug("skipping repackaging as per configuration."); return; } repackage(); }
Source:
private boolean isJava13OrLater() { for (Method method : String.class.getMethods()) { if ("stripIndent".equals(method.getName())) { return true; } } return false; }

Target:
private boolean isJava13OrLater() { for (Method method : String.class.getMethods()) { if (method.getName().equals("stripIndent")) { return true; } } return false; }
Source:
private boolean isSet(ConfigurableEnvironment environment, String property) { String value = environment.getProperty(property); return (value != null && !"false".equals(value)); }

Target:
private boolean isSet(ConfigurableEnvironment environment, String property) { String value = environment.getProperty(property); return (value != null && !value.equals("false")); }
Source:
public int getRequestedChannelMax() { return this.requestedChannelMax; }

Target:
public Integer getRequestedChannelMax() { return this.requestedChannelMax; }
Source:
public Object findFilterId(Annotated a) { Object id = super.findFilterId(a); return (id != null) ? id : CONFIGURATION_PROPERTIES_FILTER_ID; }

Target:
public Object findFilterId(Annotated a) { Object id = super.findFilterId(a); if (id == null) { id = CONFIGURATION_PROPERTIES_FILTER_ID; } return id; }
Source:
public void customDisableMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=-1"); bind("server.tomcat.max-http-form-post-size=-1"); customizeAndRunServer((server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1)); }

Target:
public void customDisableMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=-1"); customizeAndRunServer((server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1)); }
Source:
public String getHostHeader() { return this.remoteIpValve.getHostHeader() == null ? this.hostHeader : this.remoteIpValve.getHostHeader(); }

Target:
public String getHostHeader() { return this.remoteIpValve.getHostHeader(); }
Source:
public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar( ObjectProvider<MBeanExporter> mbeanExporters, Environment environment) throws MalformedObjectNameException { String jmxName = environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME); if (mbeanExporters != null) { // Make sure to not register that MBean twice mbeanExporters.orderedStream().forEach(mbeanExporter -> { mbeanExporter.addExcludedBean(jmxName); }); } return new SpringApplicationAdminMXBeanRegistrar(jmxName); }

Target:
public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar( ObjectProvider<MBeanExporter> mbeanExporters, Environment environment) throws MalformedObjectNameException { String jmxName = environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME); if (mbeanExporters != null) { // Make sure to not register that MBean twice // ordering is not important for exporters, thus just iterate them for (MBeanExporter mbeanExporter : mbeanExporters) { mbeanExporter.addExcludedBean(jmxName); } } return new SpringApplicationAdminMXBeanRegistrar(jmxName); }
Source:
void bindDataSourcesToRegistry(Map<String, DataSource> dataSources, MeterRegistry registry, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) { List<DataSourcePoolMetadataProvider> metadataProvidersList = metadataProviders.orderedStream() .collect(Collectors.toList()); dataSources.forEach( (name, dataSource) -> bindDataSourceToRegistry(name, dataSource, metadataProvidersList, registry)); }

Target:
void bindDataSourcesToRegistry(Map<String, DataSource> dataSources, MeterRegistry registry, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) { // doesn't matter the ordering here since they are usually distinct and are // used as first match wins basis. List<DataSourcePoolMetadataProvider> metadataProvidersList = metadataProviders.stream() .collect(Collectors.toList()); dataSources.forEach( (name, dataSource) -> bindDataSourceToRegistry(name, dataSource, metadataProvidersList, registry)); }
Source:
void redisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate", "spring.session.redis.save-mode=on-get-attribute", "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.redis.port=" + redis.getFirstMappedPort()) .run(validateSpringSessionUsesRedis("foo:event:0:created:", FlushMode.IMMEDIATE, "0 0 12 * * *", SaveMode.ON_GET_ATTRIBUTE)); }

Target:
void redisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate", "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.session.redis.save-mode=on-get-attribute", "spring.redis.port=" + redis.getFirstMappedPort()) .run(validateSpringSessionUsesRedis("foo:event:0:created:", FlushMode.IMMEDIATE, "0 0 12 * * *", SaveMode.ON_GET_ATTRIBUTE)); }
Source:
public Cluster couchbaseCluster() { CouchbaseCluster couchbaseCluster = CouchbaseCluster .create(couchbaseEnvironment(), determineBootstrapHosts()); if (this.properties.getUsername() != null && this.properties.getPassword() != null) { return couchbaseCluster.authenticate(this.properties.getUsername(), this.properties.getPassword()); } return couchbaseCluster; }

Target:
public Cluster couchbaseCluster() { CouchbaseCluster couchbaseCluster = CouchbaseCluster .create(couchbaseEnvironment(), determineBootstrapHosts()); if (this.properties.getUsername().isEmpty() || this.properties.getPassword().isEmpty()) { return couchbaseCluster; } return couchbaseCluster.authenticate(this.properties.getUsername(), this.properties.getPassword()); }
Source:
public Bucket couchbaseClient() { if (this.properties.getUsername().isEmpty() || this.properties.getPassword().isEmpty()) { return couchbaseCluster().openBucket(this.properties.getBucket().getName()); } return couchbaseCluster().openBucket(this.properties.getBucket().getName(), this.properties.getBucket().getPassword()); }

Target:
public Bucket couchbaseClient() { if (this.properties.getUsername().isEmpty() || this.properties.getPassword().isEmpty()) { return couchbaseCluster().openBucket(this.properties.getBucket().getName(), this.properties.getBucket().getPassword()); } return couchbaseCluster().openBucket(this.properties.getBucket().getName()); }
Source:
void configure(MeterRegistry registry) { // Customizers must be applied before binders, as they may add custom // tags or alter timer or summary configuration. customize(registry); addFilters(registry); if (this.hasCompositeMeterRegistry) { if ((registry instanceof CompositeMeterRegistry)) { addBinders(registry); } } else { if (!(registry instanceof CompositeMeterRegistry)) { addBinders(registry); } } if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) { Metrics.addRegistry(registry); } }

Target:
void configure(MeterRegistry registry) { // Customizers must be applied before binders, as they may add custom // tags or alter timer or summary configuration. customize(registry); addFilters(registry); if (this.hasCompositeMeterRegistry) { if (registry instanceof CompositeMeterRegistry) { addBinders(registry); } } else { addBinders(registry); } if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) { Metrics.addRegistry(registry); } }
Source:
private PushGateway getPushGateway(String url) { try { return new PushGateway(new URL(Objects.toString(url, ""))); } catch (MalformedURLException ex) { return new PushGateway(url); } }

Target:
private PushGateway getPushGateway(String url) { try { return new PushGateway(new URL(url)); } catch (MalformedURLException ex) { return new PushGateway(url); } }
Source:
public TomcatConnectorCustomizer connectorCustomizer() { return (connector) -> connector.setPort(9001); }

Target:
public TomcatConnectorCustomizer connectorCustomizer() { return (connector) -> { }; }
Source:
public void tomcatContextCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations .of(ServletWebServerFactoryAutoConfiguration.class)) .withUserConfiguration( TomcatContextCustomizerConfiguration.class); runner.run((context) -> { TomcatServletWebServerFactory factory = context .getBean(TomcatServletWebServerFactory.class); assertThat(factory.getTomcatContextCustomizers()).hasSize(1); }); }

Target:
public void tomcatContextCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations .of(ServletWebServerFactoryAutoConfiguration.class)); runner.run((context) -> { TomcatServletWebServerFactory factory = context .getBean(TomcatServletWebServerFactory.class); assertThat(factory.getTomcatContextCustomizers()).hasSize(1); }); }
Source:
public HierarchicalNameMapper graphiteHierarchicalNameMapper(GraphiteConfig config) { return new GraphiteHierarchicalNameMapper(config.tagsAsPrefix()); }

Target:
public GraphiteHierarchicalNameMapper graphiteHierarchicalNameMapper( GraphiteConfig config) { return new GraphiteHierarchicalNameMapper(config.tagsAsPrefix()); }
Source:
void shutdown() { this.executorService.shutdown(); if (this.pushgatewayProperties.isPushOnShutdown()) { push(); } if (this.pushgatewayProperties.isDeleteOnShutdown()) { try { this.pushGateway.delete(job(), this.pushgatewayProperties.getGroupingKeys()); } catch (Throwable throwable) { this.logger.error( "Unable to delete metrics from Prometheus Pushgateway", throwable); } } }

Target:
void shutdown() { this.executorService.shutdown(); if (this.pushgatewayProperties.isPushOnShutdown()) { push(); } if (this.pushgatewayProperties.isDeleteOnShutdown()) { delete(); } }
Source:
protected List<String> getAndProcessPropertySourceProperties( MergedContextConfiguration mergedConfig) { List<String> propertySourceProperties = new ArrayList<>( Arrays.asList(mergedConfig.getPropertySourceProperties())); String differentiator = getDifferentiatorPropertySourceProperty(); if (differentiator != null) { propertySourceProperties.add(differentiator); } processPropertySourceProperties(mergedConfig, propertySourceProperties); return propertySourceProperties; }

Target:
private List<String> getAndProcessPropertySourceProperties( MergedContextConfiguration mergedConfig) { List<String> propertySourceProperties = new ArrayList<>( Arrays.asList(mergedConfig.getPropertySourceProperties())); String differentiator = getDifferentiatorPropertySourceProperty(); if (differentiator != null) { propertySourceProperties.add(differentiator); } processPropertySourceProperties(mergedConfig, propertySourceProperties); return propertySourceProperties; }
Source:
public SpringBootConfigurationFinder() { this.scanner = new ClassPathScanningCandidateComponentProvider(false); this.scanner.addIncludeFilter( new AnnotationTypeFilter(SpringBootConfiguration.class)); this.scanner.setResourcePattern("*.class"); }

Target:
public SpringBootConfigurationFinder() { this(SpringBootConfiguration.class); }
Source:
public void afterPropertiesSet() { this.embeddedDatabase = this.factory.getEmbeddedDatabase(); }

Target:
public void afterPropertiesSet() throws Exception { this.embeddedDatabase = this.factory.getEmbeddedDatabase(); }
Source:
public DataSource getObject() { return this.embeddedDatabase; }

Target:
public DataSource getObject() throws Exception { return this.embeddedDatabase; }
Source:
EmbeddedDatabase getEmbeddedDatabase() { EmbeddedDatabaseConnection connection = this.environment.getProperty( "spring.test.database.connection", EmbeddedDatabaseConnection.class, EmbeddedDatabaseConnection.NONE); if (EmbeddedDatabaseConnection.NONE.equals(connection)) { connection = EmbeddedDatabaseConnection.get(getClass().getClassLoader()); } Assert.state(connection != EmbeddedDatabaseConnection.NONE, "Failed to replace DataSource with an embedded database for tests. If " + "you want an embedded database please put a supported one " + "on the classpath or tune the replace attribute of " + "@AutoConfigureTestDatabase."); return new EmbeddedDatabaseBuilder().generateUniqueName(true) .setType(connection.getType()).build(); }

Target:
public EmbeddedDatabase getEmbeddedDatabase() { EmbeddedDatabaseConnection connection = this.environment.getProperty( "spring.test.database.connection", EmbeddedDatabaseConnection.class, EmbeddedDatabaseConnection.NONE); if (EmbeddedDatabaseConnection.NONE.equals(connection)) { connection = EmbeddedDatabaseConnection.get(getClass().getClassLoader()); } Assert.state(connection != EmbeddedDatabaseConnection.NONE, "Failed to replace DataSource with an embedded database for tests. If " + "you want an embedded database please put a supported one " + "on the classpath or tune the replace attribute of " + "@AutoConfigureTestDatabase."); return new EmbeddedDatabaseBuilder().generateUniqueName(true) .setType(connection.getType()).build(); }
Source:
private static synchronized void disableCaching() { if (!cacheDisabled) { cacheDisabled = true; doDisableCaching(); } }

Target:
private static void disableCaching() { if (!cacheDisabled) { cacheDisabled = true; doDisableCaching(); } }
Source:
public void setCurrentUrl( URL urlCurrent ) { oldFeedSource.setCurrentUrl( urlCurrent ); newFeedSource.setCurrentUrl( urlCurrent ); }

Target:
public void setCurrentUrl( URL urlCurrent ) { // No op - migration adapter isn't used on archive feeds }
Source:
private void logoutIfNeeded() throws InterruptedException { if (isViewDisplayed(getViewById(R.id.list_root)) == false) { return; } loadSettingsFromNotesList(); // Swipe to perform a scroll (because I couldn't get a reference to a scrollable view) // that will reveal the logout button. onView(withId(R.id.preferences_container)).perform(swipeUp()); // Logout selectSettingsOption(R.string.log_out, logoutPosition); // Give time to the logout to finish waitForViewMatching(withId(R.id.button_login), 1000); }

Target:
private void logoutIfNeeded() { if (!isViewDisplayed(getViewById(R.id.list_root))) { return; } loadSettingsFromNotesList(); // Swipe to perform a scroll (because I couldn't get a reference to a scrollable view) // that will reveal the logout button. onView(withId(R.id.preferences_container)).perform(swipeUp()); // Logout selectSettingsOption(R.string.log_out, logoutPosition); // Give time to the logout to finish waitForViewMatching(withId(R.id.button_login), 1000); }
Source:
public void sendMessageSync(String destAddress, String message, boolean command) throws InterruptedException, MessageException { Response response = getRequestBuilder().post(Entity.json(preparePayload(destAddress, message))); if (!response.getStatusInfo().equals(Response.Status.OK)) { String output = response.readEntity(String.class); throw new MessageException(new Exception(output)); } }

Target:
public void sendMessageSync(String destAddress, String message, boolean command) throws InterruptedException, MessageException { Response response = getRequestBuilder().post(Entity.json(preparePayload(destAddress, message))); if (!response.getStatusInfo().equals(Response.Status.OK)) { String output = response.readEntity(String.class); throw new MessageException(output); } }
Source:
public boolean truncateLog(long zxid) { try { // close the existing txnLog and snapLog close(); // truncate it FileTxnLog truncLog = new FileTxnLog(dataDir); boolean truncated = truncLog.truncate(zxid); truncLog.close(); // re-open the txnLog and snapLog // I'd rather just close/reopen this object itself, however that // would have a big impact outside ZKDatabase as there are other // objects holding a reference to this object. txnLog = new FileTxnLog(dataDir); snapLog = new FileSnap(snapDir); return truncated; } catch (IOException e) { LOG.error("Unable to truncate Txn log", e); return false; } }

Target:
public boolean truncateLog(long zxid) { try { // close the existing txnLog and snapLog close(); // truncate it try (FileTxnLog truncLog = new FileTxnLog(dataDir)) { boolean truncated = truncLog.truncate(zxid); // re-open the txnLog and snapLog // I'd rather just close/reopen this object itself, however that // would have a big impact outside ZKDatabase as there are other // objects holding a reference to this object. txnLog = new FileTxnLog(dataDir); snapLog = new FileSnap(snapDir); return truncated; } } catch (IOException e) { LOG.error("Unable to truncate Txn log", e); return false; } }
Source:
public void addEntry(FieldName fieldName, String value) { if (value != null) { logEntries.put(fieldName.name().toLowerCase(), value); } }

Target:
void addEntry(FieldName fieldName, String value) { if (value != null) { logEntries.put(fieldName.name().toLowerCase(), value); } }
Source:
public void start() { if (listenBacklog > 0) { bootstrap.option(ChannelOption.SO_BACKLOG, listenBacklog); } LOG.info("binding to port {}", localAddress); parentChannel = bootstrap.bind(localAddress).syncUninterruptibly().channel(); // Port changes after bind() if the original port was 0, update // localAddress to get the real port. localAddress = (InetSocketAddress) parentChannel.localAddress(); LOG.info("bound to port " + getLocalPort()); }

Target:
public void start() { if (listenBacklog != -1) { bootstrap.option(ChannelOption.SO_BACKLOG, listenBacklog); } LOG.info("binding to port {}", localAddress); parentChannel = bootstrap.bind(localAddress).syncUninterruptibly().channel(); // Port changes after bind() if the original port was 0, update // localAddress to get the real port. localAddress = (InetSocketAddress) parentChannel.localAddress(); LOG.info("bound to port " + getLocalPort()); }
Source:
public Boolean serializeZxidDigest(OutputArchive oa) throws IOException { if (!DigestCalculator.digestEnabled()) { return false; } ZxidDigest zxidDigest = lastProcessedZxidDigest; if (zxidDigest == null) { // write an empty digest zxidDigest = new ZxidDigest(); } zxidDigest.serialize(oa); return true; }

Target:
public boolean serializeZxidDigest(OutputArchive oa) throws IOException { if (!DigestCalculator.digestEnabled()) { return false; } ZxidDigest zxidDigest = lastProcessedZxidDigest; if (zxidDigest == null) { // write an empty digest zxidDigest = new ZxidDigest(); } zxidDigest.serialize(oa); return true; }
Source:
public void testOrderWithDifferentPrefixes() throws Exception { String[] names = { "r-3", "r-2", "r-1", "w-2", "w-1" }; // names with duplicated sequence numbers are not included in the result String[] expected = { "r-1", "r-2", "r-3" }; assertOrderedNodeNames(names, expected); }

Target:
public void testOrderWithDifferentPrefixes() throws Exception { String[] names = { "r-3", "r-2", "r-1", "w-2", "w-1" }; String[] expected = { "r-1", "w-1", "r-2", "w-2", "r-3" }; assertOrderedNodeNames(names, expected); }
Source:
private void configureSSLSocket(SSLSocket sslSocket) { if (cipherSuites != null) { SSLParameters sslParameters = sslSocket.getSSLParameters(); LOG.debug("Setup cipher suites for client socket: {}", Arrays.toString(cipherSuites)); sslParameters.setCipherSuites(cipherSuites); sslSocket.setSSLParameters(sslParameters); } }

Target:
private void configureSSLSocket(SSLSocket sslSocket) { SSLParameters sslParameters = sslSocket.getSSLParameters(); LOG.debug("Setup cipher suites for client socket: {}", Arrays.toString(cipherSuites)); sslParameters.setCipherSuites(cipherSuites); sslSocket.setSSLParameters(sslParameters); }
Source:
public void testFourLetterWordsAllDisabledByDefault() throws Exception { stopServer(); FourLetterCommands.resetWhiteList(); System.setProperty("zookeeper.4lw.commands.whitelist", "stat"); startServer(); // Default white list for 3.5.x is empty, so all command should fail. verifyAllCommandsFail(); TestableZooKeeper zk = createClient(); String sid = getHexSessionId(zk.getSessionId()); verifyAllCommandsFail(); zk.getData("/", true, null); verifyAllCommandsFail(); zk.close(); verifyFuzzyMatch("stat", "Outstanding"); verifyAllCommandsFail(); }

Target:
public void testFourLetterWordsAllDisabledByDefault() throws Exception { stopServer(); FourLetterCommands.resetWhiteList(); System.setProperty("zookeeper.4lw.commands.whitelist", "stat"); startServer(); // Default white list for 3.5.x is empty, so all command should fail. verifyAllCommandsFail(); TestableZooKeeper zk = createClient(); verifyAllCommandsFail(); zk.getData("/", true, null); verifyAllCommandsFail(); zk.close(); verifyFuzzyMatch("stat", "Outstanding"); verifyAllCommandsFail(); }
Source:
public void setup() throws InterruptedException, KeeperException.NoNodeException { System.setProperty(authProvider, superDigest); QuorumPeerConfig.setReconfigEnabled(false); // Get a three server quorum. qu = new QuorumUtil(1); qu.disableJMXTest = true; try { qu.startAll(); } catch (IOException e) { Assert.fail("Fail to start quorum servers."); } resetZKAdmin(); }

Target:
public void setup() throws InterruptedException { System.setProperty(authProvider, superDigest); QuorumPeerConfig.setReconfigEnabled(false); // Get a three server quorum. qu = new QuorumUtil(1); qu.disableJMXTest = true; try { qu.startAll(); } catch (IOException e) { Assert.fail("Fail to start quorum servers."); } resetZKAdmin(); }
Source:
public void tearDown() throws Exception { if (this.fileWatcher != null) { this.fileWatcher.close(); } // Cleanup directories final Path workDir = PATH.getParent(); if (Files.exists(workDir)) { Files.deleteIfExists(PATH); Files.delete(workDir); } }

Target:
public void tearDown() throws Exception { if (this.fileWatcher != null) { this.fileWatcher.close(); } }
Source:
private static FileSystem getCachedHttpFileSystem(final Configuration conf, final AzkabanCommonModuleConfig azConfig) { // Ensure the necessary props are not specified to enable CachedHttpFileSystem if (azConfig.getOriginDependencyRootUri() == null) return null; else validateURI(azConfig.getOriginDependencyRootUri(), CHTTP_SCHEME); try { return FileSystem.get(azConfig.getOriginDependencyRootUri(), conf); } catch (final IOException e) { log.error("Unable to initialize CachedHttpFileSystem.", e); throw new AzkabanException(e); } }

Target:
private static FileSystem getCachedHttpFileSystem(final Configuration conf, final AzkabanCommonModuleConfig azConfig) { // Ensure the necessary props are not specified to enable CachedHttpFileSystem if (azConfig.getOriginDependencyRootUri() == null) { return null; } // Ensure the origin URI has the correct scheme and has an authority. validateURI(azConfig.getOriginDependencyRootUri(), CHTTP_SCHEME, true); try { return FileSystem.get(azConfig.getOriginDependencyRootUri(), conf); } catch (final IOException e) { log.error("Unable to initialize CachedHttpFileSystem.", e); throw new AzkabanException(e); } }
Source:
private void setNeedsMoreUsersIfAppropriate(final Page page, final Project project, final Session session) { // See if the project has only one admin user with no admin groups. // If it does AND the forceMultipleUsers flag is set AND the current user has the ability to add // an admin, let's force the user to do so before allowing any execution or scheduling of flows. boolean hasEnoughUsersGroups = project.getUsersWithPermission(Type.ADMIN).size() > 1 || project.getGroupsWithPermission(Type.ADMIN).size() > 0 || !hasPermission(session.getUser(), Type.ADMIN) || !this.forceMultipleUsers; page.add("hasEnoughUsersGroups", hasEnoughUsersGroups); }

Target:
private void setNeedsMoreUsersIfAppropriate(final Page page, final Project project, final Session session) { // See if the project has only one admin user with no admin groups. // If it does AND the forceMultipleUsers flag is set AND the current user has the ability to add // an admin, let's force the user to do so before allowing any execution or scheduling of flows. boolean hasEnoughUsersGroups = !this.forceMultipleUsers || project.getUsersWithPermission(Type.ADMIN).size() > 1 || project.getGroupsWithPermission(Type.ADMIN).size() > 0 || !hasPermission(session.getUser(), Type.ADMIN); page.add("hasEnoughUsersGroups", hasEnoughUsersGroups); }