auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected String getTokenFromSession(final WebContext context) { START return ((Optional<String>) context.getSessionStore().get(context, Pac4jConstants.CSRF_TOKEN)).orElse(null); END } this cast seems dangerous: why is an optional stored in there?

Target:
protected String getTokenFromSession(final WebContext context) { return (String) context.getSessionStore().get(context, Pac4jConstants.CSRF_TOKEN).orElse(null); }
Source:
public final Optional<RedirectAction> getLogoutAction(final WebContext context, final U currentProfile, final String targetUrl) { init(); START return Optional.of(logoutActionBuilder.getLogoutAction(context, currentProfile, targetUrl)); END } ofNullable?

Target:
public final Optional<RedirectAction> getLogoutAction(final WebContext context, final U currentProfile, final String targetUrl) { init(); return logoutActionBuilder.getLogoutAction(context, currentProfile, targetUrl); }
Source:
public SessionStore<J2EContext> buildFromTrackableSession(final J2EContext context, final Object trackableSession) { if (trackableSession != null) { return new J2EProvidedSessionStore((HttpSession) trackableSession); } else { START return (SessionStore<J2EContext>) SessionStore.EMPTY; END } } I have no opinion on this, but is it really what we would want? to throw exception while before we would be returning `null`? (I haven't finished reading, so maybe I will get an answer in the rest of the diff : )

Target:
public Optional<SessionStore<J2EContext>> buildFromTrackableSession(final J2EContext context, final Object trackableSession) { return trackableSession != null ? Optional.of(new J2EProvidedSessionStore((HttpSession) trackableSession)) : Optional.empty(); }
Source:
protected HttpAction redirectToIdentityProvider(final C context, final List<Client> currentClients) { final IndirectClient currentClient = (IndirectClient) currentClients.get(0); START return (HttpAction) currentClient.redirect(context).get(); END } I don't think it makes sense to have an optional `HttpAction` here. The signature of the `redirect` method should not have an `Optional`. As we are working on the API, I'm wondering if this `redirect` should belong to the `IndirectClient` class instead of the `Client` interface.

Target:
protected HttpAction redirectToIdentityProvider(final C context, final List<Client> currentClients) { final IndirectClient currentClient = (IndirectClient) currentClients.get(0); return currentClient.redirect(context); }
Source:
public FromAttributesAuthorizationGenerator() { START this.roleAttributes = Arrays.asList(new String[] {}); END this.permissionAttributes = Arrays.asList(new String[] {}); } Can you use `new ArrayList<String>();`?

Target:
public FromAttributesAuthorizationGenerator() { this.roleAttributes = new ArrayList(); this.permissionAttributes = new ArrayList(); }
Source:
protected void internalInit(WebContext context) { CommonHelper.assertNotNull("ticketValidator", this.ticketValidator); if (this.ticketValidator instanceof InitializableObject) { START ((InitializableObject) this.ticketValidator).init(); END } } This is the way I used to initialize objects, but I tend to do things differently right now: initialization must be handled by the component which is initializable, not by another one using it; otherwise, initialization may be forgotten.

Target:
protected void internalInit(WebContext context) { CommonHelper.assertNotNull("ticketValidator", this.ticketValidator); }
Source:
public void setLinkedId(final String linkedId) { START if (this.linkedId != null) { END // Don't allow unsetting of already set linked id CommonHelper.assertNotNull("linkedId", linkedId); } this.linkedId = linkedId; } If we want to remove a link to an account, we should allow to set `null`. We should just remove the `CommonHelper.assertNotNull` test.

Target:
public void setLinkedId(final String linkedId) { this.linkedId = linkedId; }
Source:
public Object getCustomParam(String name) { START return (customParams!=null)?customParams.get(name):null; END } Don't check the `customParams` if it has already been checked in the `setCustomParams` method.

Target:
public Object getCustomParam(String name) { return customParams.get(name); }
Source:
public String getCustomParam(String name) { START if (customParams != null) { END return customParams.get(name); } else { return null; } } This check is useless as the `customParams` can never be `null`.

Target:
public String getCustomParam(String name) { return customParams.get(name); }
Source:
public boolean isProfileAuthorized(final WebContext context, final U profile) throws RequiresHttpAction { if (profile != null && !(profile instanceof AnonymousProfile)) { return true; } else { if (this.redirectionUrl != null) { throw RequiresHttpAction.redirect("user should be authenticated", context, this.redirectionUrl); } else { return false; START } END } } Looks like the above block is repeated. Could we extract this bit out?

Target:
public boolean isProfileAuthorized(final WebContext context, final U profile) throws RequiresHttpAction { return profile != null && !(profile instanceof AnonymousProfile); }
Source:
public static boolean isNotEmpty(final Collection coll) { START return coll != null && !coll.isEmpty(); END } You could simply turn this into !isEmpty()

Target:
public static boolean isNotEmpty(final Collection coll) { return !isEmpty(coll); }
Source:
public Client findClient(final WebContext context) { final String name = context.getRequestParameter(this.clientNameParameter); START if (name == null && defaultClient != null) { END return defaultClient; } CommonHelper.assertNotBlank("name", name); return findClient(name); } What is this `defaultClient` for? It doesn't seem related to the resource changes...

Target:
public Client findClient(final WebContext context) { final String name = context.getRequestParameter(this.clientNameParameter); CommonHelper.assertNotBlank("name", name); return findClient(name); }
Source:
protected MetadataResolver initServiceProviderMetadataResolver(final WebContext context) { String finalCallbackUrl = computeFinalCallbackUrl(context); this.spMetadataResolver = new SAML2ServiceProviderMetadataResolver(this.configuration.getServiceProviderMetadataPath(), this.configuration.getServiceProviderMetadataResource(), finalCallbackUrl, START (this.configuration.getServiceProviderEntityId().equals("CALLBACK_URL") ? finalCallbackUrl END : this.configuration.getServiceProviderEntityId()), this.configuration.isForceServiceProviderMetadataGeneration(), this.credentialProvider); return this.spMetadataResolver.resolve(); } I get the idea, but can you remove this for now? Let's try to keep one change at a time, there are already many things to account for.

Target:
protected MetadataResolver initServiceProviderMetadataResolver(final WebContext context) { this.spMetadataResolver = new SAML2ServiceProviderMetadataResolver(this.configuration, computeFinalCallbackUrl(context), this.credentialProvider); return this.spMetadataResolver.resolve(); }
Source:
protected MetadataResolver initServiceProviderMetadataResolver(final WebContext context) { START this.spMetadataResolver = new SAML2ServiceProviderMetadataResolver(this.configuration.getServiceProviderMetadataPath(), END computeFinalCallbackUrl(context), this.configuration.getServiceProviderEntityId(), this.configuration.isForceServiceProviderMetadataGeneration(), this.credentialProvider); return this.spMetadataResolver.resolve(); } I think that passing the `configuration` could be sufficient, couldn't it? To mirror what's done for the identity provider...

Target:
protected MetadataResolver initServiceProviderMetadataResolver(final WebContext context) { this.spMetadataResolver = new SAML2ServiceProviderMetadataResolver(this.configuration, computeFinalCallbackUrl(context), this.credentialProvider); return this.spMetadataResolver.resolve(); }
Source:
protected void initializeClientConfiguration() { if (this.casPrefixUrl != null && !this.casPrefixUrl.endsWith("/")) { this.casPrefixUrl += "/"; } if (CommonHelper.isBlank(this.casPrefixUrl)) { START this.casPrefixUrl = this.casLoginUrl.replaceFirst("/login$", "/$"); END } else if (CommonHelper.isBlank(this.casLoginUrl)) { this.casLoginUrl = this.casPrefixUrl + "login"; } } The `$` is not a required convention, it's part of the regexp which is the first parameter of the `replaceFirst` method. ``` String url1 = "http://localhost:8080/cas/login"; System.out.println(url1.replaceFirst("/login$", "/end")); ``` Will output: `http://localhost:8080/cas/end`. And it works for: `String url1 = "http://loginserver/cas/login";` which is the needed fix. Though, the proposed fix: `this.casPrefixUrl = this.casLoginUrl.replaceFirst("/login$", "/$");` doesn't work and generates: `Illegal group reference: group index is missing`.

Target:
protected void initializeClientConfiguration() { if (this.casPrefixUrl != null && !this.casPrefixUrl.endsWith("/")) { this.casPrefixUrl += "/"; } if (CommonHelper.isBlank(this.casPrefixUrl)) { this.casPrefixUrl = this.casLoginUrl.replaceFirst("/login$", "/"); } else if (CommonHelper.isBlank(this.casLoginUrl)) { this.casLoginUrl = this.casPrefixUrl + "login"; } }
Source:
public List<Client> getClients() { START init(); END if (this.clients == null) { return Collections.emptyList(); } else { return this.clients; } } While `getClients` should have no initialization.

Target:
public List<Client> getClients() { return this.clients; }
Source:
public Google2AttributesDefinition() { addAttribute(GENDER, Converters.genderConverter); START addAttribute(GENDER, Converters.stringConverter); END addAttribute(DISPLAY_NAME, Converters.stringConverter); addAttribute(GIVEN_NAME, Converters.stringConverter); addAttribute(FAMILY_NAME, Converters.stringConverter); addAttribute(URL, Converters.stringConverter); addAttribute(PICTURE, Converters.stringConverter); addAttribute(LANGUAGE, Converters.localeConverter); addAttribute(BIRTHDAY, Google2Converters.dateConverter); addAttribute(EMAILS, Google2Converters.listEmailConverter); } `GENDER` again?

Target:
public Google2AttributesDefinition() { addAttribute(GENDER, Converters.genderConverter); addAttribute(DISPLAY_NAME, Converters.stringConverter); addAttribute(GIVEN_NAME, Converters.stringConverter); addAttribute(FAMILY_NAME, Converters.stringConverter); addAttribute(URL, Converters.stringConverter); addAttribute(PICTURE, Converters.stringConverter); addAttribute(LANGUAGE, Converters.localeConverter); addAttribute(BIRTHDAY, Google2Converters.dateConverter); addAttribute(EMAILS, Google2Converters.listEmailConverter); }
Source:
public String getEmail() { final List<Google2Email> list = getEmails(); START if (list != null && list.size() > 0) END return list.get(0).getEmail(); else return null; } You get it right. Per code conventions, I like to see brackets around `if` and `else` clauses.

Target:
public String getEmail() { final List<Google2Email> list = getEmails(); if (list != null && list.size() > 0) { return list.get(0).getEmail(); } else { return null; } }
Source:
protected abstract C retrieveCredentials(final WebContext context) throws RequiresHttpAction; public final U getUserProfile(final C credentials, final WebContext context) { init(); logger.debug("credentials : {}", credentials); if (credentials == null) { return null; START } END final U profile = retrieveUserProfile(credentials, context); for (AuthorizationGenerator<U> authorizationGenerator : this.authorizationGenerators) { authorizationGenerator.generate(profile); } return profile; } I would keep the condition on `!= null` as the list can be set to `null`...

Target:
protected abstract C retrieveCredentials(final WebContext context) throws RequiresHttpAction; public final U getUserProfile(final C credentials, final WebContext context) { init(); logger.debug("credentials : {}", credentials); if (credentials == null) { return null; } final U profile = retrieveUserProfile(credentials, context); if (this.authorizationGenerators != null) { for (AuthorizationGenerator<U> authorizationGenerator : this.authorizationGenerators) { authorizationGenerator.generate(profile); } } return profile; }
Source:
public MemcachedClient create() { if (useSharedClient && clients.size() == 1) { logger.info("Using a shared client"); return clients.get(0); } logger.info("Creating a new client"); MemcachedClient client = null; START try { END client = new MemcachedClient(this.addresses); } catch (IOException ex) { throw new IllegalStateException("Error starting Memcached client.", ex); } clients.add(client); return client; } this can lead to more than 1 client being created because create is probably called concurrently. Keep things simple and just make the method synchronized

Target:
public synchronized MemcachedClient create() { if (useSharedClient && clients.size() == 1) { logger.info("Using a shared client"); return clients.get(0); } logger.info("Creating a new client"); MemcachedClient client = null; try { client = new MemcachedClient(this.addresses); } catch (IOException ex) { throw new IllegalStateException("Error starting Memcached client.", ex); } clients.add(client); return client; }
Source:
public void setup() { this.map = targetInstance.getMap(name); START generatedIds = generateStrings(keyCount, idLength); END } This could lead to a huge amount of data being kept in memory; even though it is just readonly.

Target:
public void setup() { this.map = targetInstance.getMap(name); }
Source:
public static File getConfigurationFile(String filename) { File file = new File(filename).getAbsoluteFile(); if (file.exists()) { START return file.getAbsoluteFile(); END } else { return newFile(getSimulatorHome(), "conf", filename).getAbsoluteFile(); } } Duplicate `getAbsoluteFile()`

Target:
public static File getConfigurationFile(String filename) { File file = new File(filename).getAbsoluteFile(); if (file.exists()) { return file; } else { return newFile(getSimulatorHome(), "conf", filename).getAbsoluteFile(); } }
Source:
public MetronomeBuilder withRatePerSecond(double ratePerSecond) { if (ratePerSecond <= 0) { START throw new IllegalArgumentException("ratePerSecond can't smaller than 0"); END } long intervalMicros = round(SECONDS.toMicros(1) / ratePerSecond); return withIntervalMicros(intervalMicros); } `smaller than 1`

Target:
public MetronomeBuilder withRatePerSecond(double ratePerSecond) { long intervalMicros = round(SECONDS.toMicros(1) / ratePerSecond); return withIntervalMicros(intervalMicros); }
Source:
START private static boolean setValue(Object object, String value, Field field) throws IllegalAccessException { END if (setIntegralValue(object, value, field)) { return true; } if (setFloatingPointValue(object, value, field)) { return true; } if (setNonNumericValue(object, value, field)) { return true; } return isProbeField(field); } overall the commit is very good, but this method might be misleading - it doesn't set anything if the field belongs to a probe.

Target:
private static boolean setValue(Object object, String value, Field field) throws IllegalAccessException { if (setIntegralValue(object, value, field)) { return true; } if (setFloatingPointValue(object, value, field)) { return true; } return setNonNumericValue(object, value, field); }
Source:
public long getOperationCount() { try { Long count = invokeMethod((operationCountWorkerInstance != null) ? operationCountWorkerInstance : testClassInstance, operationCountMethod); return (count == null ? -1 : count); } catch (Exception e) { START LOGGER.warn("Exception while retrieving operation count from " + testCase.getId() + ": " + e.getMessage()); END return -1; } } won't this produce awful lot of warnings when the method is not available? I thought you would log it to `finest` - disabled by default, but with an option to enable it if needed.

Target:
public long getOperationCount() { try { Long count = invokeMethod((operationCountWorkerInstance != null) ? operationCountWorkerInstance : testClassInstance, operationCountMethod); return (count == null ? -1 : count); } catch (Exception e) { LOGGER.debug("Exception while retrieving operation count from " + testCase.getId() + ": " + e.getMessage()); return -1; } }
Source:
START public void terminate() throws IllegalStateException{ END terminate(Integer.MAX_VALUE); } no need to declare unchecked exception.

Target:
public void terminate() { terminate(Integer.MAX_VALUE); }
Source:
public void run() { long iteration = 0; while (!testContext.isStopped()) { START for (int i = 0; i < keyCount; i++) { END String key = keys[random.nextInt(keys.length)]; map.put(key, createValue(key,random)); iteration++; if (iteration % logFrequency == 0) { LOGGER.info(Thread.currentThread().getName() + " At iteration: " + iteration); } } } } Do we need this inner for loop?

Target:
public void run() { long iteration = 0; while (!testContext.isStopped()) { String key = keys[random.nextInt(keys.length)]; map.put(key, createValue(key,random)); iteration++; if (iteration % logFrequency == 0) { LOGGER.info(Thread.currentThread().getName() + " At iteration: " + iteration); } } }
Source:
public T select() { int chance = random.nextInt(100); START for (Map.Entry<T, Integer> entry : operations.entrySet()) { END Integer probability = entry.getValue(); if ((chance -= probability) < 0) { return entry.getKey(); } } return defaultOperation; } So for discussion sake, lets assume we have 10 instead of 100 chances, and you will have 80% read and 20% put, then the array would look like: ``` [put, put, read, read, read, read, read, read, read, read] ``` To find your operration, you can do a: ``` int index = random.nextInt(array.length); return array[index] ```

Target:
public T select() { int chance = random.nextInt(operations.length); return (T) operations[chance]; }
Source:
OperationSelector(Object[] operations) { START this.random = new Random(); END this.operations = operations; } Personal flavour; do whatever you like. If an object can be initialized in the class constructor, I do that. It keeps the normal constructor cleaner and shorter. Especially when you have some initialization logic in the normal constructor, this can be a good way to get rid of things that don't to be there.

Target:
OperationSelector(Object[] operations) { this.operations = operations; }
Source:
public void onResponse(Object response) { START operations.addAndGet(performanceUpdateFrequency); END } aren't you introducing the calculation bug again?

Target:
public void onResponse(Object response) { operations.addAndGet(1); }
Source:
List<MetricFamilySamples> fromCounter(String dropwizardName, Counter counter) { String name = sanitizeMetricName(dropwizardName); MetricFamilySamples.Sample sample = sampleBuilder.createSample(dropwizardName, "", new ArrayList<String>(), new ArrayList<String>(), new Long(counter.getCount()).doubleValue()); START return Arrays.asList(new MetricFamilySamples(name, Type.GAUGE, getHelpMessage(dropwizardName, counter), Arrays.asList(sample))); END } Is the metric name going to match the timeseries name?

Target:
MetricFamilySamples fromCounter(String dropwizardName, Counter counter) { MetricFamilySamples.Sample sample = sampleBuilder.createSample(dropwizardName, "", new ArrayList<String>(), new ArrayList<String>(), new Long(counter.getCount()).doubleValue()); return new MetricFamilySamples(sample.name, Type.GAUGE, getHelpMessage(dropwizardName, counter), Arrays.asList(sample)); }
Source:
START protected Child getNoLabelsChild() throws IllegalArgumentException { END if (noLabelsChild == null) { throw new IllegalArgumentException("For a labelled metric you must specify the labels"); } return noLabelsChild; } IllegalArgumentException is a runtime exception, no need to declare it.

Target:
protected Child getNoLabelsChild() { if (noLabelsChild == null) { throw new IllegalArgumentException("For a labelled metric you must specify the labels"); } return noLabelsChild; }
Source:
START List<MetricFamilySamples> familySamplesList(Collector.Type type, List<MetricFamilySamples.Sample> samples) { END MetricFamilySamples mfs = new MetricFamilySamples(fullname, type, help, samples); List<MetricFamilySamples> mfsList = new ArrayList<MetricFamilySamples>(1); mfsList.add(mfs); return mfsList; } This should be protected

Target:
protected List<MetricFamilySamples> familySamplesList(Collector.Type type, List<MetricFamilySamples.Sample> samples) { MetricFamilySamples mfs = new MetricFamilySamples(fullname, type, help, samples); List<MetricFamilySamples> mfsList = new ArrayList<MetricFamilySamples>(1); mfsList.add(mfs); return mfsList; }
Source:
START private double nullSafeArrayLength(long[] array) { END return null == array ? 0 : array.length; } This should be static technically.

Target:
private static double nullSafeArrayLength(long[] array) { return null == array ? 0 : array.length; }
Source:
public static void main(String[] args) throws Exception { START PushGateway pg = new PushGateway(args[0], args[1]); END g.set(42); pg.push(pushRegistry, "job"); } This will throw an exception if there's only one arg.

Target:
public static void main(String[] args) throws Exception { PushGateway pg = new PushGateway(args[0]); g.set(42); pg.push(pushRegistry, "job"); }
Source:
public void pushAdd(CollectorRegistry registry, String job, Map<String, String> groupingKey) throws IOException { HttpPost request = new HttpPost(); START request.setEntity(createOutputEntity(registry)); END doRequest(registry, job, groupingKey, request); } I think this code and function would be better inlined in doRequest

Target:
public void pushAdd(CollectorRegistry registry, String job, Map<String, String> groupingKey) throws IOException { HttpPost request = new HttpPost(); request.setEntity(createOutputEntity(registry)); doRequest(job, groupingKey, request); }
Source:
StandardExports(StatusReader statusReader, OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean) { this.statusReader = statusReader; this.osBean = osBean; this.runtimeBean = runtimeBean; this.unix = osBean instanceof UnixOperatingSystemMXBean; START this.linux = osBean.getName().indexOf("Linux") == 0; END } this is getting a little towards the magic side, I'd put the RHS in parens

Target:
StandardExports(StatusReader statusReader, OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean) { this.statusReader = statusReader; this.osBean = osBean; this.runtimeBean = runtimeBean; this.unix = (osBean instanceof UnixOperatingSystemMXBean); this.linux = (osBean.getName().indexOf("Linux") == 0); }
Source:
START public void start() { END this.counter = Counter.build().name(COUNTER_NAME) .help("Log4j log statements at various log levels") .labelNames("level") .register(registry); trace = counter.labels("trace"); debug = counter.labels("debug"); info = counter.labels("info"); warn = counter.labels("warn"); error = counter.labels("error"); super.start(); } > in this case that should thrown an exception as we would double count otherwise seeing as we only ever have a single registry. No exception would be thrown currently, prometheus scrapes of the target will fail though due to duplicate metrics. I think double counting is preferable to failing scrapes for the entire target.

Target:
public void start() { super.start(); }
Source:
public void onLogin(User user) { mIconsHidden = false; supportInvalidateOptionsMenu(); START Log.e("LOGGED IN", "EFCEF"); END ((LoginListener)mMediaView).onLogin(user); if (((MainApplication)getApplication()).isFirstTimeGalleryUser()) { MediaFragment.createHelpDialog(this).show(); ((MainApplication)getApplication()).setFirstTimeGalleryUser(false); } } This log can't go live.

Target:
public void onLogin(User user) { mIconsHidden = false; supportInvalidateOptionsMenu(); ((LoginListener)mMediaView).onLogin(user); if (((MainApplication)getApplication()).isFirstTimeGalleryUser()) { MediaFragment.createHelpDialog(this).show(); ((MainApplication)getApplication()).setFirstTimeGalleryUser(false); } }
Source:
public VCardBuilder addAdr(final Map parameters, final List values) { START properties.add(new VCardProperty("adr", parameters, "text", (List) getAdrTextOrDefault(values))); END return this; } (List) cast is redundant?

Target:
public VCardBuilder addAdr(final Map parameters, final List values) { properties.add(new VCardProperty("adr", parameters, "text", getAdrTextOrDefault(values))); return this; }
Source:
private RpslObject convertToRpslObject(final WhoisResources whoisResources, final ObjectType objectType) { START for (WhoisObject whoisObject : whoisResources.getWhoisObjects()) { END if (objectType == ObjectType.getByName(whoisObject.getType())) { return whoisObjectMapper.map(whoisObject, FormattedServerAttributeMapper.class); } } setErrorMessage(whoisResources, "Unable to find " + objectType + " in WhoisResources"); throw new ReferenceUpdateFailedException(Response.Status.BAD_REQUEST, whoisResources); } final?

Target:
private RpslObject convertToRpslObject(final WhoisResources whoisResources, final ObjectType objectType) { for (final WhoisObject whoisObject : whoisResources.getWhoisObjects()) { if (objectType == ObjectType.getByName(whoisObject.getType())) { return whoisObjectMapper.map(whoisObject, FormattedServerAttributeMapper.class); } } setErrorMessage(whoisResources, "Unable to find " + objectType + " in WhoisResources"); throw new ReferenceUpdateFailedException(Response.Status.BAD_REQUEST, whoisResources); }
Source:
public static boolean isIanaResource(final RpslObject resource) { final RpslAttribute netname = resource.findAttribute(AttributeType.NETNAME); final boolean status = (netname != null && IANA_NETNAME.equals(netname.getValue().trim())); START LOGGER.debug("Is inetnum with netname iana? {}", resource.getKey(), netname != null ? netname.getValue() : null, status); END return status; } this appears to be a useless check - null is still used

Target:
public static boolean isIanaResource(final RpslObject resource) { final RpslAttribute netname = resource.findAttribute(AttributeType.NETNAME); //status return (netname != null && IANA_NETNAME.equals(netname.getValue().trim())); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; State state = (State) o; START if (id != state.id) return false; END if (count != state.count) return false; return source != null ? source.equals(state.source) : state.source == null; } these three statements can be folded into one: return (id == state.id) && (count == state.count) && ...

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; State state = (State) o; return id == state.id && count == state.count && (source != null ? source.equals(state.source) : state.source == null); }
Source:
public synchronized void init() { // there should be only one LoggingDriver initialized per JVM (or we won't know which applicationContext's loggerContext to log to) try { Driver driver = DriverManager.getDriver(URL_PREFIX); LOGGER.error("LoggingDriver already installed; removing"); try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { throw new IllegalStateException("Unable to de-register logging JDBC driver", e); } } catch (SQLException expected) { START LOGGER.error("SQLException ", expected); END } try { DriverManager.registerDriver(this); } catch (SQLException e) { throw new IllegalStateException("Unable to register logging JDBC driver", e); } } log @ debug for expected exception, or ignore

Target:
public synchronized void init() { // there should be only one LoggingDriver initialized per JVM (or we won't know which applicationContext's loggerContext to log to) try { Driver driver = DriverManager.getDriver(URL_PREFIX); LOGGER.error("LoggingDriver already installed; removing"); try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { throw new IllegalStateException("Unable to de-register logging JDBC driver", e); } } catch (SQLException expected) { LOGGER.debug(expected.getMessage(), expected); } try { DriverManager.registerDriver(this); } catch (SQLException e) { throw new IllegalStateException("Unable to register logging JDBC driver", e); } }
Source:
private void loadRemoteEntries() { START if (swipeRefresh != null && !swipeRefresh.isRefreshing()) { END swipeRefresh.setRefreshing(true); } state.setLoadRemoteEntries(new LoadRemoteEntries(this)); Utils.execute(state.loadRemoteEntries); } Use tabs

Target:
private void loadRemoteEntries() { state.setLoadRemoteEntries(new LoadRemoteEntries(this)); Utils.execute(state.loadRemoteEntries); }
Source:
public List<Pipeline> getPipelines() { if (pagingEnabled) { START if (!isFullScreenView()) { END int startIndex = ((this.getCurrentPage() - 1) * noOfPipelines); int retrieveSize = Math.min(pipelines.size() - ((this.getCurrentPage() - 1) * noOfPipelines), noOfPipelines); return pipelines.subList(startIndex, startIndex + retrieveSize); } } return pipelines; } Just collapse these two if statements if (pagingEnabled && !isFullScreenView()) { ...

Target:
public List<Pipeline> getPipelines() { if (pagingEnabled && !isFullScreenView()) { int startIndex = ((this.getCurrentPage() - 1) * noOfPipelines); int retrieveSize = Math.min(pipelines.size() - ((this.getCurrentPage() - 1) * noOfPipelines), noOfPipelines); return pipelines.subList(startIndex, startIndex + retrieveSize); } return pipelines; }
Source:
START public void calculatePipelineRoutes(Task task, final Route route, List<Route> allRoutes) { END if (task.getDownstreamTasks() != null && task.getDownstreamTasks().size() > 0) { for (String downstreamTaskName: task.getDownstreamTasks()) { // assume each task only appears once in the pipeline Route currentRoute = createRouteAndCopyTasks(route, task); calculatePipelineRoutes(getTaskFromName(downstreamTaskName), currentRoute, allRoutes); } } else { Route currentRoute = createRouteAndCopyTasks(route, task); allRoutes.add(currentRoute); } } Should this method really be public?

Target:
void calculatePipelineRoutes(Task task, final Route route, List<Route> allRoutes) { if (task.getDownstreamTasks() != null && task.getDownstreamTasks().size() > 0) { for (String downstreamTaskName: task.getDownstreamTasks()) { // assume each task only appears once in the pipeline Route currentRoute = createRouteAndCopyTasks(route, task); calculatePipelineRoutes(getTaskFromName(downstreamTaskName), currentRoute, allRoutes); } } else { Route currentRoute = createRouteAndCopyTasks(route, task); allRoutes.add(currentRoute); } }
Source:
public int getGenre() { START if (id3v2Tag != null && id3v2Tag.getGenre() != -1) { END return id3v2Tag.getGenre(); } else if (id3v1Tag != null) { return id3v1Tag.getGenre(); } else { return -1; } } This changes the default behaviour and would lead to different results when a consumer updates mp3agic. We could do that in the future but should keep the decision to prefer id3v2 over id3v1 consistent in the whole library. This should go to another pull request and signed off by @mpatric before.

Target:
public int getGenre() { if (id3v1Tag != null && id3v1Tag.getGenre() != -1) { return id3v1Tag.getGenre(); } else if (id3v2Tag != null) { return id3v2Tag.getGenre(); } else { return -1; } }
Source:
START public static AddonArchive getDeployment() END { AddonArchive archive = ShrinkWrap .create(AddonArchive.class) .addBeansXML() .addAsAddonDependencies( AddonDependencyEntry.create("org.jboss.forge.addon:ui"), AddonDependencyEntry.create("org.jboss.forge.addon:shell-test-harness"), AddonDependencyEntry.create("org.jboss.forge.addon:resources"), AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi") ); return archive; } Remove all @AddonDeployment annotations and leave only @AddonDeployments. Also, remove the addAsAddonDependencies below.

Target:
public static AddonArchive getDeployment() { return ShrinkWrap .create(AddonArchive.class) .addBeansXML(); }
Source:
public File move(File source, File target) throws IOException { if (target.isDirectory()) { START Path path = Files.move(source.toPath(), Paths.get(target.getAbsolutePath(), source.getName()), END ATOMIC_MOVE); return path.toFile(); } this.renameFile(source, target); return target; } Can't we use this method regardless of the target type?

Target:
public File move(File source, File target) throws IOException { if (target.isDirectory()) { Path path = Files.move(source.toPath(), Paths.get(target.getAbsolutePath(), source.getName()), ATOMIC_MOVE); return path.toFile(); } Path path = Files.move(source.toPath(), target.toPath(), ATOMIC_MOVE); return path.toFile(); }
Source:
public void move(FileResource<?> target) { try { getFileOperations().move(file, target.getUnderlyingResourceObject()); START this.file = target.getUnderlyingResourceObject(); END } catch (IOException e) { throw new ResourceException("Error while moving Resource " + this, e); } } This won't work if the target is a DirectoryResource. Return the File object from getFileOperation().move() (Change the signature)

Target:
public void move(FileResource<?> target) { try { this.file = getFileOperations().move(file, target.getUnderlyingResourceObject()); } catch (IOException e) { throw new ResourceException("Error while moving Resource " + this, e); } }
Source:
public Metadata getMetadata(UIContext context) { return Metadata.from(super.getMetadata(context), getClass()) .name("Constraint: New Annotation") .description("Create a Bean Validation constraint annotation") START .category(super.getMetadata(context).getCategory()); END } You can remove this line. Metadata.from already reuses the category from super.getMetadata

Target:
public Metadata getMetadata(UIContext context) { return Metadata.from(super.getMetadata(context), getClass()) .name("Constraint: New Annotation") .description("Create a Bean Validation constraint annotation"); }
Source:
public void testFileSize() throws Exception { File file = File.createTempFile("forge", "testFileSize"); file.deleteOnExit(); try (FileWriter write = new FileWriter(file)) { write.append("Test"); FileResource<?> fileResource = factory.create(file).reify(FileResource.class); Assert.assertEquals(file.length(), fileResource.getSize()); START file.delete(); END } } file.delete() should be called outside the try block, otherwise the FileWriter associated with it won´t release the lock

Target:
public void testFileSize() throws Exception { File file = File.createTempFile("forge", "testFileSize"); file.deleteOnExit(); try (FileWriter write = new FileWriter(file)) { write.append("Test"); FileResource<?> fileResource = factory.create(file).reify(FileResource.class); Assert.assertEquals(file.length(), fileResource.getSize()); } file.delete(); }
Source:
public boolean isCorrectMutator(MethodSource<JavaClassSource> method, PropertySource<JavaClassSource> property) { String returnType = method.getReturnType().getName(); String className = property.getOrigin().getName(); START return returnType.equals(className); END } Can returnType be null? Perhaps it's better to invert this (className.equals(returnType))

Target:
public boolean isCorrectMutator(MethodSource<JavaClassSource> method, PropertySource<JavaClassSource> property) { String returnType = method.getReturnType().getName(); String className = property.getOrigin().getName(); return className.equals(returnType); }
Source:
START public Resource<T> getChild(final String name) END { throw new RuntimeException("not implemented"); } Not backwards compatible.

Target:
public Resource<?> getChild(final String name) { throw new RuntimeException("not implemented"); }
Source:
public static WebArchive createWebApplication() { return ShrinkWrap.create(WebArchive.class, "spring-test.war") .addClasses(Employee.class, EmployeeService.class, DefaultEmployeeService.class, EmployeeRepository.class, DefaultEmployeeRepository.class, NullEmployeeRepository.class, START EmployeeController.class, ClassPathResourceLocationsProcessor.class) END .addAsLibraries(springDependencies()) .addAsLibraries(mockitoDependencies()); } The extension internal class quite likely should not be here. Good you have added it into the archive appender, but it should be removed from here.

Target:
public static WebArchive createWebApplication() { return ShrinkWrap.create(WebArchive.class, "spring-test.war") .addClasses(Employee.class, EmployeeService.class, DefaultEmployeeService.class, EmployeeRepository.class, DefaultEmployeeRepository.class, NullEmployeeRepository.class, EmployeeController.class) .addAsLibraries(springDependencies()) .addAsLibraries(mockitoDependencies()); }
Source:
public void addCatalogVersion(final String catalogResource) throws Exception { final StandaloneCatalog inputCatalogVersion = XMLLoader.getObjectFromString(Resources.getResource(catalogResource).toExternalForm(), StandaloneCatalog.class); final StandaloneCatalogWithPriceOverride inputCatalogVersionWithOverride = new StandaloneCatalogWithPriceOverride(inputCatalogVersion, priceOverride, internalTenantContext.getTenantRecordId(), internalCallContextFactory); if (versionedCatalog == null) { START versionedCatalog = new DefaultVersionedCatalog(new ArrayList<>()); END } versionedCatalog.add(inputCatalogVersionWithOverride); } You could use the no-arg constructor instead.

Target:
public void addCatalogVersion(final String catalogResource) throws Exception { final StandaloneCatalog inputCatalogVersion = XMLLoader.getObjectFromString(Resources.getResource(catalogResource).toExternalForm(), StandaloneCatalog.class); final StandaloneCatalogWithPriceOverride inputCatalogVersionWithOverride = new StandaloneCatalogWithPriceOverride(inputCatalogVersion, priceOverride, internalTenantContext.getTenantRecordId(), internalCallContextFactory); if (versionedCatalog == null) { versionedCatalog = new DefaultVersionedCatalog(); } versionedCatalog.add(inputCatalogVersionWithOverride); }
Source:
public boolean addTrackingIds(final Collection<String> trackingIds) { START this.trackingIds.addAll(trackingIds); END return true; } You could have returned the result of `addAll` to make the returned value a bit more meaningful. This (historic) boolean API is a bit weird though.

Target:
public boolean addTrackingIds(final Collection<String> trackingIds) { return this.trackingIds.addAll(trackingIds); }
Source:
public String toString() { return "DefaultSubscriptionBillingEvent{" + "type=" + type + START ", plan='" + plan + '\'' + END ", planPhase='" + planPhase + '\'' + ", effectiveDate=" + effectiveDate + ", totalOrdering=" + totalOrdering + ", bcdLocal=" + bcdLocal + '}'; } Unclear if there are circular dependencies with the objects' `toString` methods (we had the problem in the past). Might be safer to just print the names.

Target:
public String toString() { return "DefaultSubscriptionBillingEvent{" + "type=" + type + ", plan='" + plan.getName() + '\'' + ", planPhase='" + planPhase.getName() + '\'' + ", effectiveDate=" + effectiveDate + ", totalOrdering=" + totalOrdering + ", bcdLocal=" + bcdLocal + '}'; }
Source:
public T call() throws Exception { try { Request.setPerThreadRequestData(requestData); UUIDs.setRandom(random); ThreadContext.bind(securityManager); ThreadContext.bind(subject); MDC.setContextMap(mdcContextMap); return delegate.call(); } finally { Request.resetPerThreadRequestData(); START UUIDs.setRandom(null); END ThreadContext.unbindSecurityManager(); ThreadContext.unbindSubject(); // Reset the MDC as before the call, in case the plugin fiddle'd with it MDC.setContextMap(mdcContextMap); } } Unrelated to your change but this whole `finally` block is a crazy amount of thread reset state!

Target:
public T call() throws Exception { try { Request.setPerThreadRequestData(requestData); UUIDs.setRandom(random); ThreadContext.bind(securityManager); ThreadContext.bind(subject); MDC.setContextMap(mdcContextMap); return delegate.call(); } finally { Request.resetPerThreadRequestData(); UUIDs.setRandom(null); ThreadContext.unbindSecurityManager(); ThreadContext.unbindSubject(); MDC.clear(); } }
Source:
public List<AuditLogWithHistory> getEmailAuditLogsWithHistoryForId(final UUID accountEmailId, final AuditLevel auditLevel, final InternalTenantContext context) throws AccountApiException { START return transactionalSqlDao.execute(true, AccountApiException.class, new EntitySqlDaoTransactionWrapper<List<AuditLogWithHistory>>() { END @Override public List<AuditLogWithHistory> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) { final AccountEmailSqlDao transactional = entitySqlDaoWrapperFactory.become(AccountEmailSqlDao.class); return auditDao.getAuditLogsWithHistoryForId(transactional, TableName.ACCOUNT_EMAIL, accountEmailId, auditLevel, context); } }); } Can you use the other signature (without the exception)? It doesn't look like `AccountApiException` is thrown here (same remark below).

Target:
public List<AuditLogWithHistory> getEmailAuditLogsWithHistoryForId(final UUID accountEmailId, final AuditLevel auditLevel, final InternalTenantContext context) { return transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper<List<AuditLogWithHistory>>() { @Override public List<AuditLogWithHistory> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) { final AccountEmailSqlDao transactional = entitySqlDaoWrapperFactory.become(AccountEmailSqlDao.class); return auditDao.getAuditLogsWithHistoryForId(transactional, TableName.ACCOUNT_EMAIL, accountEmailId, auditLevel, context); } }); }
Source:
public List<AuditLog> getAuditLogs() { START return ImmutableList.<AuditLog>copyOf(accountAuditLogs); END } It seems like we could change for free the definition of `accountAuditLogs` to be `private final List<AuditLog> accountAuditLogs;` and avoid that copy.

Target:
public List<AuditLog> getAuditLogs() { return accountAuditLogs; }
Source:
private static BigDecimal computeAmount(final BigDecimal targetTierPrice, final Integer targetQuantity) { START return targetTierPrice.multiply(new BigDecimal(targetQuantity)); END } Nit: `BigDecimal.valueOf()`

Target:
private static BigDecimal computeAmount(final BigDecimal targetTierPrice, final Integer targetQuantity) { return targetTierPrice.multiply(BigDecimal.valueOf(targetQuantity)); }
Source:
public UsageDetailMode getItemResultBehaviorMode() { final UsageDetailMode mode = staticConfig.getItemResultBehaviorMode(); START if (mode.compareTo(UsageDetailMode.AGGREGATE) != 0 || mode.compareTo(UsageDetailMode.DETAIL) != 0) { END return UsageDetailMode.AGGREGATE; } return mode; } You could simplify it (use `==`).

Target:
public UsageDetailMode getItemResultBehaviorMode() { final UsageDetailMode mode = staticConfig.getItemResultBehaviorMode(); if (mode == UsageDetailMode.AGGREGATE || mode == UsageDetailMode.DETAIL) { return mode; } return UsageDetailMode.AGGREGATE; }
Source:
private boolean isUsageOverrideListHasOnlyNull(List<UsagePriceOverride> usagePriceOverrides) { for (UsagePriceOverride override : usagePriceOverrides) START if (override != null) return false; END return true; } Nit: Add brackets: ``` if (override != null) { return false; } ```

Target:
private boolean isUsageOverrideListHasOnlyNull(List<UsagePriceOverride> usagePriceOverrides) { for (UsagePriceOverride override : usagePriceOverrides) { if (override != null) { return false; } } return true; }
Source:
public PaymentPluginApi getPaymentPluginApi() throws PaymentApiException { final String pluginName = getPaymentProviderPluginName(true); START return getPaymentPluginApi(pluginName); END } I would have expected the opposite: Since this is called when [running payment operations](https://github.com/killbill/killbill/blob/work-for-release-0.17.x/payment/src/main/java/org/killbill/billing/payment/core/sm/payments/PaymentOperation.java#L74), and that we _only_ want to fetch deleted payment method for `GET` operations, then shouldn't this be `false`?

Target:
public PaymentPluginApi getPaymentPluginApi() throws PaymentApiException { final String pluginName = getPaymentProviderPluginName(false); return getPaymentPluginApi(pluginName); }
Source:
public Pagination<Payment> getPayments(final Long offset, final Long limit, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) { START return paymentProcessor.getPayments(offset, limit, withPluginInfo, properties, context, internalCallContextFactory.createInternalTenantContext(context)); END } Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`

Target:
public Pagination<Payment> getPayments(final Long offset, final Long limit, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) { return paymentProcessor.getPayments(offset, limit, withPluginInfo, withAttempts, properties, context, internalCallContextFactory.createInternalTenantContext(context)); }
Source:
public Payment getPaymentByExternalKey(final String paymentExternalKey, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) START throws PaymentApiException { END final Payment payment = paymentProcessor.getPaymentByExternalKey(paymentExternalKey, withPluginInfo, properties, tenantContext, internalCallContextFactory.createInternalTenantContext(tenantContext)); if (payment == null) { throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT, paymentExternalKey); } return payment; } Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`

Target:
public Payment getPaymentByExternalKey(final String paymentExternalKey, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { final Payment payment = paymentProcessor.getPaymentByExternalKey(paymentExternalKey, withPluginInfo, withAttempts, properties, tenantContext, internalCallContextFactory.createInternalTenantContext(tenantContext)); if (payment == null) { throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT, paymentExternalKey); } return payment; }
Source:
public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) { START return paymentProcessor.searchPayments(searchKey, offset, limit, withPluginInfo, properties, context, internalCallContextFactory.createInternalTenantContext(context)); END } Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`

Target:
public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) { return paymentProcessor.searchPayments(searchKey, offset, limit, withPluginInfo, withAttempts, properties, context, internalCallContextFactory.createInternalTenantContext(context)); }
Source:
public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) throws PaymentApiException { START return paymentProcessor.searchPayments(searchKey, offset, limit, pluginName, withPluginInfo, properties, context, internalCallContextFactory.createInternalTenantContext(context)); END } Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`

Target:
public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) throws PaymentApiException { return paymentProcessor.searchPayments(searchKey, offset, limit, pluginName, withPluginInfo, withAttempts, properties, context, internalCallContextFactory.createInternalTenantContext(context)); }