auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public StringResourceModel(final String resourceKey, final Component component) END { Args.notNull(resourceKey, "resource key"); this.resourceKey = resourceKey; this.component = component; } To make the migration easier I think it would be good to have one more constructor: `public StringResourceModel(final String resourceKey, final Component component, final IModel<?> model)`.

Target:
public StringResourceModel(final String resourceKey, final Component component) { this(resourceKey, component, null); }
Source:
public void before() { tester = new WicketTester(application); START WebApplication webApplication = tester.getApplication(); END webApplication.getWicketFilter().setFilterPath(""); } Why get it again? You already have a reference to it.

Target:
public void before() { tester = new WicketTester(application); application.getWicketFilter().setFilterPath(""); }
Source:
protected TextField<Integer> newHoursTextField(final String id, IModel<Integer> model, Class<Integer> type) { START TextField<Integer> hoursTextField = new TextField<Integer>(id, model, type); END hoursTextField.add(getMaximumHours() == 24 ? RangeValidator.range(0, 23) : RangeValidator .range(1, 12)); hoursTextField.setLabel(new Model<>(HOURS)); return hoursTextField; } Hi. Could you please use diamond operator? We try to use it wherever is possible. Thank you.

Target:
protected TextField<Integer> newHoursTextField(final String id, IModel<Integer> model, Class<Integer> type) { TextField<Integer> hoursTextField = new TextField<>(id, model, type); hoursTextField.add(getMaximumHours() == 24 ? RangeValidator.range(0, 23) : RangeValidator .range(1, 12)); hoursTextField.setLabel(new Model<>(HOURS)); return hoursTextField; }
Source:
public void add(final SampleResult sample) { synchronized (buffer) { buffer.add(sample); dataChanged = true; START CorrelationRecorder.setBuffer(buffer); END } } This does not look correct in terms of isolation of objects. Why is this call needed ?

Target:
public void add(final SampleResult sample) { synchronized (buffer) { buffer.add(sample); dataChanged = true; } }
Source:
public ResultData customizeResult(ResultData result) { START if (extraOptions == null) { END return new MapResultData(); } MapResultData customizedResult = new MapResultData(); customizedResult.setResult(DATA_CTX_RESULT, result); MapResultData extraResult = new MapResultData(); extraOptions.getProperties() .forEach((key, value) -> extraResult.setResult(key, new ValueResultData(value))); customizedResult.setResult(DATA_CTX_EXTRA_OPTIONS, extraResult); return customizedResult; } This is changing the behaviour. Previously it would add the `result` as `DATA_CTX_RESULT`.

Target:
public ResultData customizeResult(ResultData result) { MapResultData customizedResult = new MapResultData(); customizedResult.setResult(DATA_CTX_RESULT, result); if (extraOptions == null) { return customizedResult; } MapResultData extraResult = new MapResultData(); extraOptions.getProperties().forEach((key, value) -> extraResult.setResult(key, new ValueResultData(value))); customizedResult.setResult(DATA_CTX_EXTRA_OPTIONS, extraResult); return customizedResult; }
Source:
private boolean arrayMatched(JSONArray value) { if (value.isEmpty() && "[]".equals(getExpectedValue())) { return true; } START boolean foundMatch = Arrays.stream(value.toArray()) END .anyMatch(subj -> (subj == null && isExpectNull()) || isEquals(subj)); return foundMatch || isEquals(value); } Does this change incur a performance penalty during load testing phase?

Target:
private boolean arrayMatched(JSONArray value) { if (value.isEmpty() && "[]".equals(getExpectedValue())) { return true; } for (Object subj : value.toArray()) { if ((subj == null && isExpectNull()) || isEquals(subj)) { return true; } } return isEquals(value); }
Source:
private static String deleteLineBreak(String postdata) { START String repl = ""; END if (postdata != null) { Matcher m = deleteLinePattern.matcher(postdata); repl = m.replaceAll(""); } return repl; } I'd go for directly returning the results instead of using a variable and reassigning it.

Target:
private static String deleteLineBreak(String postdata) { Matcher m = deleteLinePattern.matcher(postdata); return m.replaceAll(""); }
Source:
public void addHeader(String name, String value) { START if (name != null && name.equalsIgnoreCase("COOKIE")) { END this.cookieInHeaders = value; } else if (name != null && !HEADERS_TO_IGNORE.contains(name)) { headers.put(name, value); } } Actually, my intention to place `"COOKIE"` in front, was to make the `null` check unnecessary here. `if ("COOKIE".equalsIgnoreCase(name)) { ... }` would be enough. If a `null` value is problematic for the set-contains check, we could return early from this method when `name` is `null`.

Target:
public void addHeader(String name, String value) { if ("COOKIE".equalsIgnoreCase(name)) { this.cookieInHeaders = value; } else if (!HEADERS_TO_IGNORE.contains(name)) { headers.put(name, value); } }
Source:
public boolean getEnabled(String actionCommand) { START if (ActionNames.ADD.equals(actionCommand)) END return guiComp.canBeAdded(); else return true; } Please use braces. Checkstyle should pick this up.

Target:
public boolean getEnabled(String actionCommand) { if (ActionNames.ADD.equals(actionCommand)) { return guiComp.canBeAdded(); } else { return true; } }
Source:
START private static String getYarnApiAddress(Configuration conf) { END Set<String> yarnApiAddresses = getYarnApiAddresses(conf); try { for (String yarnApiAddress : yarnApiAddresses) { if (successfulConnection(yarnApiAddress)) { return yarnApiAddress; } } } catch (IOException e) { LOG.error("Error getting yarn api address:", e); } return ""; } If you used an `Optional` here (which represents the notion that you may not get an RM), you could turn [these lines](https://github.com/LiveRamp/cascading_ext/pull/90/files#diff-5796ba38ae3b31ff5eab085bca3465e8R83-R89) into ``` getYarnApiAddress(conf).map(x -> getYarnAppInfo(x, appId)) ```

Target:
private static Optional<String> getYarnApiAddress(Configuration conf) { Set<String> yarnApiAddresses = getYarnApiAddresses(conf); try { for (String yarnApiAddress : yarnApiAddresses) { if (successfulConnection(yarnApiAddress)) { return Optional.of(yarnApiAddress); } } } catch (IOException e) { LOG.error("Error getting yarn api address:", e); } return Optional.empty(); }
Source:
public static MerlinsBeard from(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); AndroidVersion androidVersion = new AndroidVersion(); ResponseCodeValidator validator = new ResponseCodeValidator.DefaultEndpointResponseCodeValidator(); START EndpointPinger pinger = EndpointPinger.withCustomEndpointAndValidation(Endpoint.from(ENDPOINT), validator); END Ping ping = new Ping(Endpoint.defaultEndpoint(), new EndpointPinger.ResponseCodeFetcher(), validator); return new MerlinsBeard(connectivityManager, androidVersion, pinger, ping); } Maybe? ```suggestion EndpointPinger pinger = EndpointPinger.withCustomEndpointAndValidation(Endpoint.defaultEndpoint(), validator); ```

Target:
public static MerlinsBeard from(Context context) { return new MerlinsBeard.Builder() .build(context); }
Source:
public void reset() { START if (snackbar != null) { END snackbar.dismiss(); snackbar = null; } } `if (null) { return }` ?

Target:
public void reset() { if (snackbar == null) { return; } snackbar.dismiss(); snackbar = null; }
Source:
private static Observable<NetworkStatus.State> createObservable(Merlin merlin) { return Observable.create(new MerlinAction(merlin), Emitter.BackpressureMode.LATEST) START .distinctUntilChanged(); END } Did we also have `distinctUntilChanged` before? Although it kinda makes sense, I wonder if we should filter any event at all. Users can always use this themselves right?

Target:
private static Observable<NetworkStatus> createObservable(Merlin merlin) { return Observable.create(new MerlinAction(merlin), Emitter.BackpressureMode.LATEST); }
Source:
public void unbindWhenUnsubscribed() { Merlin merlin = mock(Merlin.class); Subscription subscription = MerlinObservable.from(merlin) .subscribe(); subscription.unsubscribe(); START verify(merlin, times(1)).unbind(); END } `times(1)` is not necessary.

Target:
public void unbindWhenUnsubscribed() { Subscription subscription = MerlinObservable.from(merlin) .subscribe(); subscription.unsubscribe(); verify(merlin).unbind(); }
Source:
public boolean isConnectedToMobileNetwork() { int simState = telephonyManager.getSimState(); START if (simState == TelephonyManager.SIM_STATE_READY) { END NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); return networkInfo != null && networkInfo.isConnected(); } return false; } Does this mean the following is possible if the sim is not ready? isConnected is true, isConnectedToWifi false and isConnectedToMobileNetwork false

Target:
public boolean isConnectedToMobileNetwork() { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); return networkInfo != null && networkInfo.isConnected(); }
Source:
public String getNameTokenUnitImport() { if (nameTokenPsiClass == null) { return ""; } START String importString = "import " + nameTokenPsiClass.getQualifiedName() + ";"; END return importString; } nl and return directly

Target:
public String getNameTokenUnitImport() { if (nameTokenPsiClass == null) { return ""; } return "import " + nameTokenPsiClass.getQualifiedName() + ";"; }
Source:
public void addComponentChangeListener(ComponentChangeListener l) { checkState(); START if( ! listenerList.contains(l)) { END listenerList.add(l); } log.trace("Added ComponentChangeListener " + l + ", current number of listeners is " + listenerList.size()); } Hmm, should we switch listenerList to a set?

Target:
public void addComponentChangeListener(ComponentChangeListener l) { checkState(); listenerList.add(l); log.trace("Added ComponentChangeListener " + l + ", current number of listeners is " + listenerList.size()); }
Source:
private void setDataBindingField() { START dataBindingField = holder.generatedClass.field(JMod.PRIVATE, getClasses().VIEW_DATA_BINDING, "viewDataBinding" + ModelConstants.generationSuffix()); END } not sure but iirc we use static import for `generationSuffix` in other classes

Target:
private void setDataBindingField() { dataBindingField = holder.generatedClass.field(JMod.PRIVATE, getClasses().VIEW_DATA_BINDING, "viewDataBinding" + generationSuffix()); }
Source:
private InjectMenuActivity.MockMenuInflater createMenuInflater() { final InjectMenuActivity.MockMenuInflater menuInflater = Mockito.mock(InjectMenuActivity.MockMenuInflater.class); doAnswer(new Answer<Void>() { START public Void answer(InvocationOnMock invocation) { END menuInflater.menuInflated = true; return null; } }).when(menuInflater).inflate(anyInt(), any(Menu.class)); return menuInflater; } OK, i realised you can just you Mockito verification, since you already using mocking. ```java Mockito.verify(menuInflater).inflate(R.menu.my_menu, menu); ``` This way you can get rid of the inner class and the boolean field as well. Another thing: most of the times, we static import methods like `mock` and `verify`.

Target:
private InjectMenuActivity.MockMenuInflater createMenuInflater() { final InjectMenuActivity.MockMenuInflater menuInflater = mock(InjectMenuActivity.MockMenuInflater.class); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { menuInflater.menuInflated = true; return null; } }).when(menuInflater).inflate(anyInt(), any(Menu.class)); return menuInflater; }
Source:
public void methodInjectionComesAfterInflation() { Menu menu = mock(Menu.class); assertThat(injectMenuActivity.menuIsInflated).isFalse(); injectMenuActivity.onCreateOptionsMenu(menu); assertThat(injectMenuActivity.menuIsInflated).isTrue(); START assertThat(injectMenuActivity.methodInjectedMenu).isSameAs(menu); END } I think this `assert` is not needed, it is already checked in other tests.

Target:
public void methodInjectionComesAfterInflation() { Menu menu = mock(Menu.class); assertThat(injectMenuActivity.menuIsInflated).isFalse(); injectMenuActivity.onCreateOptionsMenu(menu); assertThat(injectMenuActivity.menuIsInflated).isTrue(); }
Source:
public EViewHolder(AndroidAnnotationsEnvironment environment, TypeElement annotatedElement) throws Exception { super(environment, annotatedElement); START onFinishInflateCallBlock = new ArrayList<>(); END addSuppressWarning(); createConstructorAndBuilder(); } Let's move the initialisation to the declaration.

Target:
public EViewHolder(AndroidAnnotationsEnvironment environment, TypeElement annotatedElement) throws Exception { super(environment, annotatedElement); addSuppressWarning(); createConstructorAndBuilder(); }
Source:
public void testOnResultCalledInFragment() { FragmentStartedActivity_.intent(fragment).startForResult(AwaitingResultFragment.FIRST_REQUEST); START ShadowActivity a = (ShadowActivity) ShadowExtractor.extract(fragment.getActivity()); END a.receiveResult(FragmentStartedActivity_.intent(fragment).get(), Activity.RESULT_OK, new Intent()); assertThat(fragment.onResultCalled).isTrue(); } In other places you static import extract. I think we should be consistent?

Target:
public void testOnResultCalledInFragment() { FragmentStartedActivity_.intent(fragment).startForResult(AwaitingResultFragment.FIRST_REQUEST); ShadowActivity a = (ShadowActivity) extract(fragment.getActivity()); a.receiveResult(FragmentStartedActivity_.intent(fragment).get(), Activity.RESULT_OK, new Intent()); assertThat(fragment.onResultCalled).isTrue(); }
Source:
public void testPreferenceChangeCastedParameterPassed() { START Preference preference = activity.findPreference(activity.getString(R.string.checkBoxWithCastPrefKey)); END Boolean newValue = new Boolean(true); preference.getOnPreferenceChangeListener().onPreferenceChange(preference, newValue); assertThat(activity.preference).isSameAs(preference); assertThat(activity.newValue).isSameAs(newValue); } The value checking is not needed here, only the preference. We already check the value in the other test.

Target:
public void testPreferenceChangeCastedParameterPassed() { Preference preference = activity.findPreference(activity.getString(R.string.checkBoxWithCastPrefKey)); preference.getOnPreferenceChangeListener().onPreferenceChange(preference, true); assertThat(activity.preference).isSameAs(preference); }
Source:
public void activityCompilesWithRegularDrawable() { START addManifestProcessorParameter(ContextCompatDrawableTest.class, "AndroidManifestForDrawable.xml"); END CompileResult result = compileFiles(ActivityWithDrawable.class); File generatedFile = toGeneratedFile(ActivityWithDrawable.class); assertCompilationSuccessful(result); assertGeneratedClassMatches(generatedFile, DRAWABLE_SIGNATURE); } You can move this line to `setUp` from both test methods.

Target:
public void activityCompilesWithRegularDrawable() { CompileResult result = compileFiles(ActivityWithDrawable.class); File generatedFile = toGeneratedFile(ActivityWithDrawable.class); assertCompilationSuccessful(result); assertGeneratedClassMatches(generatedFile, DRAWABLE_SIGNATURE); }
Source:
private void createClass() throws JClassAlreadyExistsException { START builderClass = holder.getGeneratedClass()._class(PUBLIC | STATIC, "IntentBuilder" + ModelConstants.generationSuffix()); END builderClass._extends(getSuperClass()); holder.setIntentBuilderClass(builderClass); contextField = ref("context"); intentField = ref("intent"); } Here, I think we could name the inner class `IntentBuilder`. It's an inner class so there is no risk of conflict. Then, again, a `IntentBuilderImpl` would be weird.

Target:
private void createClass() throws JClassAlreadyExistsException { builderClass = holder.getGeneratedClass()._class(PUBLIC | STATIC, "IntentBuilder" + generationSuffix()); builderClass._extends(getSuperClass()); holder.setIntentBuilderClass(builderClass); contextField = ref("context"); intentField = ref("intent"); }
Source:
protected void setScopedObjectsField() { JClass keyWildCard = classes().KEY.narrow(codeModel().wildcard()); JClass scopedHashMap = classes().HASH_MAP.narrow(keyWildCard, classes().OBJECT); START getRoboGuiceHolder().scopedObjects = getGeneratedClass().field(JMod.PROTECTED, scopedHashMap, "scopedObjects" + ModelConstants.generationSuffix()); END getRoboGuiceHolder().scopedObjects.assign(JExpr._new(scopedHashMap)); } Same here. We should keep `scopedObjects_` since `scopeObjectsImpl` would be weird.

Target:
protected void setScopedObjectsField() { JClass keyWildCard = classes().KEY.narrow(codeModel().wildcard()); JClass scopedHashMap = classes().HASH_MAP.narrow(keyWildCard, classes().OBJECT); getRoboGuiceHolder().scopedObjects = getGeneratedClass().field(JMod.PROTECTED, scopedHashMap, "scopedObjects" + generationSuffix()); getRoboGuiceHolder().scopedObjects.assign(JExpr._new(scopedHashMap)); }
Source:
private String extractTag(Element element) { WakeLock annotation = element.getAnnotation(WakeLock.class); String tag = annotation.tag(); if (WakeLock.DEFAULT_TAG.equals(tag)) { tag = element.getEnclosingElement().getSimpleName().toString(); START tag += "." + element.getSimpleName().toString(); END } return tag; } just concat the whole thing, do not +=

Target:
private String extractTag(Element element) { WakeLock annotation = element.getAnnotation(WakeLock.class); String tag = annotation.tag(); if (WakeLock.DEFAULT_TAG.equals(tag)) { tag = element.getEnclosingElement().getSimpleName().toString() + "." + element.getSimpleName().toString(); } return tag; }
Source:
START private boolean logContains(String msg) { END List<LogItem> logs = ShadowLog.getLogs(); boolean found = false; for (LogItem logItem : logs) { if (logItem.msg.startsWith(msg)) found = true; } return found; } Make this static.

Target:
private static boolean logContains(String msg) { List<LogItem> logs = ShadowLog.getLogs(); boolean found = false; for (LogItem logItem : logs) { if (logItem.msg.startsWith(msg)) found = true; } return found; }
Source:
private String getExternalSSOProvider(){ try { return properties.getProperty(USERGRID_EXTERNAL_PROVIDER); } START catch(NullPointerException e ){ END throw new IllegalArgumentException("External SSO provider is enabled but the provider name is empty"); } } I don't think this will throw an NPE as much as it would return `null` to the caller of `getExternalSSOProvider()`

Target:
private String getExternalSSOProvider(){ return properties.getProperty(USERGRID_EXTERNAL_PROVIDER); }
Source:
public void setupStaticKeyspace() throws Exception { migrate(); // Need this legacy stuff for queues START if ( USE_VIRTUAL_KEYSPACES ) { END logger.info( "Creating static application keyspace " + getApplicationKeyspace() ); cass.createColumnFamily( getApplicationKeyspace(), createColumnFamilyDefinition( getApplicationKeyspace(), APPLICATIONS_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamilies( getApplicationKeyspace(), getCfDefs( ApplicationCF.class, getApplicationKeyspace() ) ); cass.createColumnFamilies( getApplicationKeyspace(), getCfDefs( QueuesCF.class, getApplicationKeyspace() ) ); } } This if isn't needed anymore, we don't always use virtual. Every row key is app prefixed, and we put all systems into the same keyspace. Eventually, we'll move to an org->keyspace lookup system.

Target:
public void setupStaticKeyspace() throws Exception { migrate(); // Need this legacy stuff for queues logger.info( "Creating static application keyspace " + getApplicationKeyspace() ); cass.createColumnFamily( getApplicationKeyspace(), createColumnFamilyDefinition( getApplicationKeyspace(), APPLICATIONS_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamilies( getApplicationKeyspace(), getCfDefs( ApplicationCF.class, getApplicationKeyspace() ) ); cass.createColumnFamilies( getApplicationKeyspace(), getCfDefs( QueuesCF.class, getApplicationKeyspace() ) ); }
Source:
public static String keyspaceForApplication( UUID applicationId ) { START if ( USE_VIRTUAL_KEYSPACES ) { END return getApplicationKeyspace(); } else { return "Application_" + applicationId.toString().replace( '-', '_' ); } } Just change this code, we always use virtual keyspaces, so the other scheme isn't valid any longer

Target:
public static String keyspaceForApplication( UUID applicationId ) { return getApplicationKeyspace(); }
Source:
public String getString( final Object key ) { //All values are strings , so doing the cast here saves doing the cast elsewhere START return String.valueOf(getDynamicProperties().get( key )); END } you should probably cast to a string or call toString also could be shortened to return (String) get( key );

Target:
public String getString( final Object key ) { //All values are strings , so doing the cast here saves doing the cast elsewhere return (String) getDynamicProperties().get( key ); }
Source:
public void addIndex(final UUID applicationId,final String indexSuffix,final int shards,final int replicas){ EntityIndex entityIndex = getManagerCache().getEntityIndex(CpNamingUtils.getApplicationScope(applicationId)); if(entityIndex instanceof AliasedEntityIndex) { ((AliasedEntityIndex)entityIndex).addIndex(indexSuffix, shards, replicas); START } END } What if it's not the right instance? Shouldn't we throw an UnsupportedOperationException? Or, is there a way to just create it from the factory, so we know it's always the right instance type? Since this happens very rarely, I don't think we'll need to worry about getting it from the cache for efficiency.

Target:
public void addIndex(final UUID applicationId,final String indexSuffix,final int shards,final int replicas){ EntityIndex entityIndex = getManagerCache().getEntityIndex(CpNamingUtils.getApplicationScope(applicationId)); entityIndex.addIndex(indexSuffix, shards, replicas); }
Source:
public <T> boolean register(T destroyableInstance, Binding<T> binding, Iterable<LifecycleAction> action) { try { return (running.get()) ? binding.acceptScopingVisitor(new ManagedInstanceScopingVisitor(destroyableInstance, binding.getSource(), action)) : false; } catch (Exception e) { LOGGER.warn("failed to register lifecycle actions for {}", destroyableInstance, e); START return false; END } } Shouldn't we be throwing here? Under what conditions would this throw an exception that we are fine with ignoring?

Target:
public <T> boolean register(T destroyableInstance, Binding<T> binding, Iterable<LifecycleAction> action) { return (running.get()) ? binding.acceptScopingVisitor(new ManagedInstanceScopingVisitor(destroyableInstance, binding.getSource(), action)) : false; }
Source:
START private LifecycleInjector createInjector(List<Module> modules, List<Module> overrides) { END return InjectorBuilder.fromModules(modules).overrideWith(overrides).createInjector(); } Is this method necessary? This code is only called from one place.

Target:
protected LifecycleInjector createInjector(List<Module> modules, List<Module> overrides) { return InjectorBuilder.fromModules(modules).overrideWith(overrides).createInjector(); }
Source:
public void call(Object obj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { START LOG.info("invoking lifecycle action {}", description); END method.invoke(obj); } info might be too noisy. Let's make this debug.

Target:
public void call(Object obj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { LOG.debug("invoking lifecycle action {}", description); method.invoke(obj); }
Source:
public List<Module> transform(List<Module> modules) { START BindingTracingVisitor visitor = new BindingTracingVisitor(); END for (Element binding : Elements.getElements(modules)) { LOG.debug("Binding : {}", binding); } return modules; } This doesn't seem to be used?

Target:
public List<Module> transform(List<Module> modules) { for (Element binding : Elements.getElements(modules)) { LOG.debug("Binding : {}", binding); } return modules; }
Source:
protected String visitOther(Element element) { Object source = element.getSource(); ElementSource elementSource = null; START while (source != null && source instanceof ElementSource) { END elementSource = (ElementSource)source; source = elementSource.getOriginalElementSource(); } if (elementSource != null) { return elementSource.getModuleClassNames().toString(); } return null; } I think you should be able to call instanceof on a null (which will fail the instanceof)

Target:
protected String visitOther(Element element) { Object source = element.getSource(); ElementSource elementSource = null; while (source instanceof ElementSource) { elementSource = (ElementSource)source; source = elementSource.getOriginalElementSource(); } if (elementSource != null) { return elementSource.getModuleClassNames().toString(); } return null; }
Source:
private Class<?> classFromInternalName(String name) { try { START return Class.forName(name.replace('/', '.'), true, classLoader); END } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } Shouldn't the 2nd parameter be false so we don't force static initialization?

Target:
private Class<?> classFromInternalName(String name) { try { return Class.forName(name.replace('/', '.'), false, classLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } }
Source:
public void toFile(File file) throws Exception { PrintWriter out = new PrintWriter(file, "UTF-8"); try { out.write(graph()); } finally { START Closeables.close(out, false); END } } why we don't swallow exception here for close?

Target:
public void toFile(File file) throws Exception { PrintWriter out = new PrintWriter(file, "UTF-8"); try { out.write(graph()); } finally { Closeables.close(out, true); } }
Source:
protected AbstractObjectConfigurationProvider(ObjectMapper mapper) { this.mapper = mapper; START this.logger = LoggerFactory.getLogger(getClass()); END } Can we make logger a private static final

Target:
protected AbstractObjectConfigurationProvider(ObjectMapper mapper) { if (mapper == null) { this.mapper = new ObjectMapper(); } else { this.mapper = mapper; } this.logger = LoggerFactory.getLogger(getClass()); }
Source:
public ArchaiusConfigurationProvider(Map<String, String> variableValues) { START super(new ObjectMapper()); END this.variableValues = Maps.newHashMap(variableValues); this.configurationManager = ConfigurationManager.getConfigInstance(); this.propertyFactory = DynamicPropertyFactory.getInstance(); this.ownershipPolicy = new ConfigurationOwnershipPolicy() { @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return configurationManager.containsKey(key.getKey(variables)); } }; } set to 'null' and create a default in AbstractObjectConfigurationProvider

Target:
public ArchaiusConfigurationProvider(Map<String, String> variableValues) { this.variableValues = Maps.newHashMap(variableValues); this.configurationManager = ConfigurationManager.getConfigInstance(); this.propertyFactory = DynamicPropertyFactory.getInstance(); this.ownershipPolicy = new ConfigurationOwnershipPolicy() { @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return configurationManager.containsKey(key.getKey(variables)); } }; }
Source:
public PropertiesConfigurationProvider(Properties properties, Map<String, String> variableValues) { START this(properties, variableValues, new ObjectMapper()); END } Pass 'null' for ObjectMapper and create a default in AbstractObjectConfigurationProvider

Target:
public PropertiesConfigurationProvider(Properties properties, Map<String, String> variableValues) { this(properties, variableValues, null); }
Source:
public SystemConfigurationProvider(Map<String, String> variableValues) { START this(variableValues, new ObjectMapper()); END } pass 'null' for ObjectMapper and create a default in AbstractObjectConfigurationProvider

Target:
public SystemConfigurationProvider(Map<String, String> variableValues) { this(variableValues, null); }
Source:
public void addKerberosAuthentication(UserEntity userEntity, String principalName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.KERBEROS, principalName, new Validator() { START @Override END public void validate(UserEntity userEntity, String key) throws AmbariException { // Ensure no other authentication entries exist for the same principal... if (!CollectionUtils.isEmpty(userAuthenticationDAO.findByTypeAndKey(UserAuthenticationType.KERBEROS, key))) { throw new AmbariException("The authentication type already exists for this principal"); } } }, persist); } let's do it using lambda approach

Target:
public void addKerberosAuthentication(UserEntity userEntity, String principalName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.KERBEROS, principalName, (user, key) -> { // Ensure no other authentication entries exist for the same principal... if (!CollectionUtils.isEmpty(userAuthenticationDAO.findByTypeAndKey(UserAuthenticationType.KERBEROS, key))) { throw new AmbariException("The authentication type already exists for this principal"); } }, persist); }
Source:
public Map<String, String> toMap(Optional<ObjectMapper> mapper) { Map<String, String> map = START mapper.orElseGet(() -> new ObjectMapper()).convertValue(this, new TypeReference<Map<String, String>>(){}); END if ( !Boolean.parseBoolean(map.get("keyStore")) ) { // keyStore is declared as a primitive value instead of Boolean -> treat false as unset map.remove("keyStore"); } return map; } ```suggestion mapper.orElseGet(ObjectMapper::new).convertValue(this, new TypeReference<Map<String, String>>(){}); ```

Target:
public Map<String, String> toMap(Optional<ObjectMapper> mapper) { Map<String, String> map = mapper.orElseGet(ObjectMapper::new).convertValue(this, new TypeReference<Map<String, String>>(){}); if ( !Boolean.parseBoolean(map.get("keyStore")) ) { // keyStore is declared as a primitive value instead of Boolean -> treat false as unset map.remove("keyStore"); } return map; }
Source:
public static ValueAttributesInfo fromMap(Map<String, String> attributes, Optional<ObjectMapper> mapper) { START return mapper.orElseGet(() -> new ObjectMapper()).convertValue(attributes, ValueAttributesInfo.class); END } ```suggestion return mapper.orElseGet(ObjectMapper::new).convertValue(attributes, ValueAttributesInfo.class); ```

Target:
public static ValueAttributesInfo fromMap(Map<String, String> attributes, Optional<ObjectMapper> mapper) { return mapper.orElseGet(ObjectMapper::new).convertValue(attributes, ValueAttributesInfo.class); }
Source:
START public java.util.Optional<String> getUrlOverride(@Nonnull String service, @Nonnull Link quickLink) { END return Optional.ofNullable( urlOverrides.get(Pair.of(service, quickLink.getName())) ); } ```suggestion public Optional<String> getUrlOverride(@Nonnull String service, @Nonnull Link quickLink) { ```

Target:
public Optional<String> getUrlOverride(@Nonnull String service, @Nonnull Link quickLink) { return Optional.ofNullable( urlOverrides.get(Pair.of(service, quickLink.getName())) ); }
Source:
public boolean include(String value, String defaultValue) { return value != null && ( defaultValue == null || START !Objects.equals(StringUtils.trim(defaultValue), StringUtils.trim(value)) END ); } This trimming strategy is not always applicable, e.g. it is not for password. See https://github.com/apache/ambari/blob/4839a6f6df8bf741d3acc77ebadbe0300c4e3270/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/BlueprintConfigurationProcessor.java#L783 for more. (Unless passwords are already substituted in this phase)

Target:
public boolean include(String value, String defaultValue) { return true; }
Source:
private boolean isBuiltInCheckRequired(UpgradeCheck upgradeCheck, UpgradeType upgradeType) { if (upgradeType == null) { return true; } UpgradeCheckInfo annotation = upgradeCheck.getClass().getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return false; } UpgradeType[] upgradeTypes = annotation.required(); if (ArrayUtils.contains(upgradeTypes, upgradeType)) { START return true; END } return false; } simplify: `return ArrayUtils.contains(...)`

Target:
private boolean isBuiltInCheckRequired(UpgradeCheck upgradeCheck, UpgradeType upgradeType) { if (upgradeType == null) { return true; } UpgradeCheckInfo annotation = upgradeCheck.getClass().getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return false; } UpgradeType[] upgradeTypes = annotation.required(); return ArrayUtils.contains(upgradeTypes, upgradeType); }
Source:
public boolean haveAllRepoUrlsBeenResolved() { START if(stackContext == null) { END return true; } return stackContext.haveAllRepoTasksCompleted(); } Should never be null. How is that happening? Even if there's no directory for a stack (how?) the context should be available.

Target:
public boolean haveAllRepoUrlsBeenResolved() { return stackContext.haveAllRepoTasksCompleted(); }
Source:
public Set<String> getHosts(String serviceName, String componentName) { Set<String> hosts = m_topology.get(serviceName + "/" + componentName); if (null == hosts) { START hosts = Sets.newHashSet(); END } return hosts; } Wouldn't `new HashSet<>()` or even `Collections.emptySet()` be better here since there is not need to have Google collections as a dependency?

Target:
public Set<String> getHosts(String serviceName, String componentName) { Set<String> hosts = m_topology.get(serviceName + "/" + componentName); if (null == hosts) { hosts = new HashSet<>(); } return hosts; }
Source:
public BlueprintProvisioningState getBlueprintProvisioningState() { BlueprintProvisioningState blueprintProvisioningState = null; ClusterEntity clusterEntity = getClusterEntity(); START blueprintProvisioningState = clusterEntity.getBlueprintProvisioningState(); END return blueprintProvisioningState; } Code: I think the local variable `blueprintProvisioningState` is unnecessary, value can be returned directly. At the least the variable shouldn't be pre-declared with `null` value.

Target:
public BlueprintProvisioningState getBlueprintProvisioningState() { ClusterEntity clusterEntity = getClusterEntity(); return clusterEntity.getBlueprintProvisioningState(); }
Source:
public boolean isSsoIntegrationEnabled() { try { START final Predicate ssoEnabledPredicate = ssoEnabledConfiguration == null ? null : PredicateUtils.fromJSON(ssoEnabledConfiguration); END return ssoIntegrationSupported && ssoEnabledPredicate != null && ssoEnabledPredicate.evaluate(configHelper.calculateExistingConfigurations(ambariManagementController, cluster)); } catch (AmbariException e) { throw new AmbariRuntimeException("Error while evaulating if SSO integration is enabled", e); } } This does not seem to be backwards compatible with the existing implementation. If it is not, there may be issues with existing mpacks that support this feature. I suggest using a different property for the predicate declaration so that old way can be deprecated and write a message to the log if encountered.

Target:
public boolean isSsoIntegrationEnabled() { try { return ssoIntegrationSupported && ssoEnabledConfiguration != null && ssoEnabledConfiguration.evaluate(configHelper.calculateExistingConfigurations(ambariManagementController, cluster)); } catch (AmbariException e) { throw new AmbariRuntimeException("Error while evaulating if SSO integration is enabled", e); } }
Source:
public JSONObject getSlaveAttributeForLabel(String labelName) { for (MesosSlaveInfo slaveInfo : slaveInfos) { START if(labelName != null) { END if (labelName.equals(slaveInfo.getLabelString())) { return slaveInfo.getSlaveAttributes(); } } else { if (slaveInfo.getLabelString() == null) { return slaveInfo.getSlaveAttributes(); } } } return null; } :ant: I'd use StringUtils.equals for clarity.

Target:
public JSONObject getSlaveAttributeForLabel(String labelName) { for (MesosSlaveInfo slaveInfo : slaveInfos) { if (StringUtils.equals(labelName, slaveInfo.getLabelString())) { return slaveInfo.getSlaveAttributes(); } } return null; }
Source:
public Boolean getDockerPrivilegedMode() { START return dockerPrivilegedMode != null ? dockerPrivilegedMode : false; END } why not just return dockerPrivilegedMode directly?

Target:
public Boolean getDockerPrivilegedMode() { return dockerPrivilegedMode; }
Source:
private FormValidation doCheckCpus(@QueryParameter String value) { boolean valid = true; String errorMessage = "Invalid CPUs value, it should be a positive decimal."; if (StringUtils.isBlank(value)) { valid = false; } else { try { START if (Double.parseDouble(value.trim()) < 0) { END valid = false; } } catch (NumberFormatException e) { valid = false; } } return valid ? FormValidation.ok() : FormValidation.error(errorMessage); } So you trim here when you validate but you don't trim when assigning the variables above. Either you should do trim there too or just not trim here.

Target:
private FormValidation doCheckCpus(@QueryParameter String value) { boolean valid = true; String errorMessage = "Invalid CPUs value, it should be a positive decimal."; if (StringUtils.isBlank(value)) { valid = false; } else { try { if (Double.parseDouble(value) < 0) { valid = false; } } catch (NumberFormatException e) { valid = false; } } return valid ? FormValidation.ok() : FormValidation.error(errorMessage); }
Source:
public void testFilterBuilderUri() { Warp .execute(clientAction) START .filter(request().uri().endsWith(".jsf").build()) END .verify(serverAssertion); } The `build()` method is not necessary as I can see from `BasicWarpTest`m right?

Target:
public void testFilterBuilderUri() { Warp .execute(clientAction) .filter(request().uri().endsWith(".jsf")) .verify(serverAssertion); }
Source:
public JacksonSerializerHelper() { numberTypes = new HashSet<>(); numberTypes.add(Long.class.getCanonicalName()); numberTypes.add(Float.class.getCanonicalName()); START numberTypes.add(Double.class.getCanonicalName()); END } Could this not be a static list?

Target:
public JacksonSerializerHelper() { }
Source:
public void should_canUserSeeProcessInstance_call_engine_api() throws Exception { START final boolean expected = true; END checkCanUserSeeProcessInstanceWhenApiReturn(expected); } can be inlined

Target:
public void should_canUserSeeProcessInstance_call_engine_api() throws Exception { checkCanUserSeeProcessInstanceWhenApiReturn(true); }
Source:
public void should_canUserSeeProcessInstance_call_engine_api_false() throws Exception { START final boolean expected = false; END checkCanUserSeeProcessInstanceWhenApiReturn(expected); } can be inlined

Target:
public void should_canUserSeeProcessInstance_call_engine_api_false() throws Exception { checkCanUserSeeProcessInstanceWhenApiReturn(false); }
Source:
START protected File getFolder(final String folderPath) { END return getFolder(new File(folderPath)); } Is there a reason to be protected ?

Target:
private File getFolder(final String folderPath) { return getFolder(new File(folderPath)); }
Source:
public void should_use_infopath_if_location_param_is_not_defined() throws Exception { START when(req.getMethod()).thenReturn("GET"); END when(req.getParameter("location")).thenReturn(null); when(req.getPathInfo()).thenReturn("/bonita.css"); final String resourceLocation = resourceLocationReader.getResourceLocationFromRequest(req); verify(req, times(1)).getPathInfo(); assertThat(resourceLocation).isEqualTo("bonita.css"); } I don't think you need to stub that

Target:
public void should_use_infopath_if_location_param_is_not_defined() throws Exception { when(req.getParameter("location")).thenReturn(null); when(req.getPathInfo()).thenReturn("/bonita.css"); final String resourceLocation = resourceLocationReader.getResourceLocationFromRequest(req); verify(req, times(1)).getPathInfo(); assertThat(resourceLocation).isEqualTo("bonita.css"); }
Source:
private Clickable newTaskListLink() { final TreeIndexed<String> tree = new TreeIndexed<String>(); START return new Link(_("New List"), _("Check the new task list"), END new CheckValidSessionBeforeAction(new ActionShowView(AngularIFrameView.TASK_LISTING_TOKEN, tree))); } I think we should remove the _() so that it doesn't show up in crowdin

Target:
private Clickable newTaskListLink() { final TreeIndexed<String> tree = new TreeIndexed<String>(); return new Link("New List", "Check the new task list", new CheckValidSessionBeforeAction(new ActionShowView(AngularIFrameView.TASK_LISTING_TOKEN, tree))); }
Source:
public ApplicationPageDataStore create(final APISession session) { ApplicationAPI applicationAPI; START PageAPI pageAPI; END try { applicationAPI = TenantAPIAccessor.getLivingApplicationAPI(session); pageAPI = TenantAPIAccessor.getCustomPageAPI(session); return new ApplicationPageDataStore(session, applicationAPI, pageAPI, new ApplicationPageItemConverter()); } catch (final Exception e) { throw new APIException(e); } } why declaring data out of try block?

Target:
public ApplicationPageDataStore create(final APISession session) { try { final ApplicationAPI applicationAPI = TenantAPIAccessor.getLivingApplicationAPI(session); final PageAPI pageAPI = TenantAPIAccessor.getCustomPageAPI(session); return new ApplicationPageDataStore(session, applicationAPI, pageAPI, new ApplicationPageItemConverter()); } catch (final Exception e) { throw new APIException(e); } }
Source:
public void onSuccess(final int httpStatusCode, final String response, final Map<String, String> headers) { final PageItem page = JSonItemReader.parseItem(response, PageDefinition.get()); addBody(new DeletePageFormProblemsCallout(formMappings, page.getDisplayName())); pagesLeft--; START if (pagesLeft==0) { END addBody(new CalloutWarning(_("If you delete a page that is used by a process, the process becomes unresolved.\nBefore deleting a page, you should also check whether it is used in a custom profile navigation."))); addBody(new Paragraph(_("Do you still want to delete the selected pages?"))); } } may be inline : if (--pagesLeft==0)

Target:
public void onSuccess(final int httpStatusCode, final String response, final Map<String, String> headers) { final PageItem page = JSonItemReader.parseItem(response, PageDefinition.get()); addBody(new DeletePageFormProblemsCallout(formMappings, page.getDisplayName())); if (--pagesLeft==0) { addBody(new CalloutWarning(_("If you delete a page that is used by a process, the process becomes unresolved.\nBefore deleting a page, you should also check whether it is used in a custom profile navigation."))); addBody(new Paragraph(_("Do you still want to delete the selected pages?"))); } }
Source:
public ContentHighlighter getHighlighter() { ContentHighlighter t = null; try { t = (ContentHighlighter) Class.forName(getBolderClass()) .getConstructor(new Class[] { GenericConfiguration.class }).newInstance(config); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) { // TODO Auto-generated catch block START e.printStackTrace(); END } return t; } Use logger here!

Target:
public ContentHighlighter getHighlighter() { ContentHighlighter t = null; try { t = (ContentHighlighter) Class.forName(getBolderClass()) .getConstructor(new Class[] { GenericConfiguration.class }).newInstance(config); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) { LOGGER.error(e); } return t; }
Source:
private void testString(final String language, final String str) throws CRException { bean.set("content", str); t.processBean(bean); String s = (String) bean.get("lang"); START Assert.assertEquals("The found Language (" + s + ") should be (" + language + "). String: '" + str + "'", language, s); END } Please use static imports for Assert methods.

Target:
private void testString(final String language, final String str) throws CRException { bean.set("content", str); t.processBean(bean); String s = (String) bean.get("lang"); assertEquals("The found Language (" + s + ") should be (" + language + "). String: '" + str + "'", language, s); }
Source:
public JSONArray(Collection<?> collection) { START this.myArrayList = new ArrayList<Object>(collection == null ? 0 : collection.size()); END if (collection != null) { for (Object o: collection){ this.myArrayList.add(JSONObject.wrap(o)); } } } Better to use an if/else statement here instead of 0 as initial capacity

Target:
public JSONArray(Collection<?> collection) { if (collection == null) { this.myArrayList = new ArrayList<Object>(); } else { this.myArrayList = new ArrayList<Object>(collection.size()); for (Object o: collection){ this.myArrayList.add(JSONObject.wrap(o)); } } }
Source:
public String getString(String key) throws JSONException { Object object = this.get(key); START return object.toString(); END } Just a note for other reviewers, the get(key) will throw an exception if the key or the value is null, so no null check is needed here. I'm not sure if you want to make this more succinct though as ``` java return this.get(key).toString(); ``` I'm personally not a fan of local variables that are only used once.

Target:
public String getString(String key) throws JSONException { return this.get(key).toString(); }
Source:
public void setEnvironmentFlags(Map<String, String> flags) { try { metadata.update(metadata.new Updater() { @Override public void updateCopy(HostMetadata currentCopy) { currentCopy.set_environment_flags(flags); } }); START } catch (InterruptedException e) { END throw new RuntimeException(e); } catch (KeeperException e) { throw new RuntimeException(e); } } can consolidate this to `catch (InterruptedException | KeeperException e)`

Target:
public void setEnvironmentFlags(Map<String, String> flags) { try { metadata.update(metadata.new Updater() { @Override public void updateCopy(HostMetadata currentCopy) { currentCopy.set_environment_flags(flags); } }); } catch (InterruptedException | KeeperException e) { throw new RuntimeException(e); } }
Source:
START public void run() { END if (IGNORE_PATHS.contains(partition.getPath().getName())) { return; } if (!partition.isDir()) { return; } try { copyPartitionContents(); } catch (IOException e) { this.exception = e; } } Instead of those two break off points, I would rather see the core of the method wrapped in an if statement that combines both checks. Much easier to read.

Target:
public void run() { try { copyPartitionContents(); } catch (IOException e) { this.exception = e; } }
Source:
public final @Nullable TileMultiBlock getMasterBlock() { if (masterBlock != null && !isStructureValid()) { START masterBlock.isMaster = false; END masterBlock = null; sendUpdateToClient(); } return masterBlock; } Don't like this. Its not the slaves job to determine whether a master is a master.

Target:
public final @Nullable TileMultiBlock getMasterBlock() { if (masterBlock != null && !isStructureValid()) { masterBlock = null; sendUpdateToClient(); } return masterBlock; }
Source:
public boolean needsFuel() { ItemStack fuel = getStackInSlot(SLOT_INPUT); START return InvTools.isEmpty(fuel) || sizeOf(fuel) < 8; END } In the Blast Furnace you removed the isEmpty() check, but here you kept it.

Target:
public boolean needsFuel() { ItemStack fuel = getStackInSlot(SLOT_INPUT); return sizeOf(fuel) < 8; }
Source:
public void readFromNBT(NBTTagCompound data) { super.readFromNBT(data); START if (needsFuel()) { END fuel = data.getLong("fuel"); } powered = data.getBoolean("powered"); pointPos = NBTPlugin.readBlockPos(data, "point"); prevX = data.getInteger("prevX"); prevY = data.getInteger("prevY"); prevZ = data.getInteger("prevZ"); } Don't commit these style changes.

Target:
public void readFromNBT(NBTTagCompound data) { super.readFromNBT(data); if (needsFuel()) fuel = data.getLong("fuel"); powered = data.getBoolean("powered"); pointPos = NBTPlugin.readBlockPos(data, "point"); prevX = data.getInteger("prevX"); prevY = data.getInteger("prevY"); prevZ = data.getInteger("prevZ"); }
Source:
public float getRailMaxSpeed(World world, EntityMinecart cart, BlockPos pos) { TileEntity tile = WorldPlugin.getBlockTile(world, pos); if (tile instanceof TileTrackOutfitted) START return ((TileTrackOutfitted) tile).getTrackKitInstance().getRailMaxSpeed(world, cart, pos, ((TileTrackOutfitted) tile).getTrackType()); END return 0.4f; } TrackType parameter not needed.

Target:
public float getRailMaxSpeed(World world, EntityMinecart cart, BlockPos pos) { TileEntity tile = WorldPlugin.getBlockTile(world, pos); if (tile instanceof TileTrackOutfitted) return ((TileTrackOutfitted) tile).getTrackKitInstance().getRailMaxSpeed(world, cart, pos); return 0.4f; }