auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void onDestroy() { super.onDestroy(); conversionManager.shutdown(); conversionManager.removeGlobalDownloadCallback(getSlidingUpFragment()); conversionManager.removeBaseInfoViewListener(getSlidingUpFragment()); conversionManager.removeGlobalJobViewListener(getSlidingUpFragment()); START client = null; END } is this really necessary? you destroy the activity anyway.

Target:
protected void onDestroy() { super.onDestroy(); conversionManager.shutdown(); conversionManager.removeGlobalDownloadCallback(getSlidingUpFragment()); conversionManager.removeBaseInfoViewListener(getSlidingUpFragment()); conversionManager.removeGlobalJobViewListener(getSlidingUpFragment()); }
Source:
public void setUp() throws Exception { Script startScript = BrickTestUtils.createProjectAndGetStartScript("newDataDialogTest"); variableBrickPosition = 1; listBrickPosition = 2; // "when program starts" brick is the first START startScript.addBrick(variableBrickPosition - 1, new SetVariableBrick()); END startScript.addBrick(listBrickPosition - 1, new AddItemToUserListBrick()); baseActivityTestRule.launchActivity(); } position is not necessary, just add them in the order you want to have them there: startScript.addBrick(new SetVariableBrick()); startScript.addBrick(new AddItemToUserListBrick());

Target:
public void setUp() throws Exception { Script startScript = BrickTestUtils.createProjectAndGetStartScript("newDataDialogTest"); variableBrickPosition = 1; listBrickPosition = 2; startScript.addBrick(new SetVariableBrick()); startScript.addBrick(new AddItemToUserListBrick()); baseActivityTestRule.launchActivity(); }
Source:
private String cutTrailingZerosofString(String number) { BigDecimal decimal = new BigDecimal(number); if (decimal.compareTo(BigDecimal.ZERO) == 0) { START decimal = BigDecimal.ZERO; END } else { decimal = decimal.stripTrailingZeros(); } return decimal.toPlainString(); } Please explain. If it's because of negative zero, please provide a code snippet where the result is `-0` without this code.

Target:
private String cutTrailingZerosofString(String number) { return new BigDecimal(number).stripTrailingZeros().toPlainString(); }
Source:
public void onResume() { START BottomBar.hideBottomBar(getActivity()); END super.onResume(); adapter.notifyDataSetChanged(); } Nice catch, but instead of hiding the bottom bar we should remove it altogether, it is never used in the backpack anyway.

Target:
public void onResume() { super.onResume(); adapter.notifyDataSetChanged(); }
Source:
public void testCreateUserListInSpinner() { onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) START .performNewVariableInitial(newList); END onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .checkShowsText(newList); } no need to address the element twice, you can perform multiple checks operations on it in series: onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .performNewVariableInitial(newList); .checkShowsText(newList);

Target:
public void testCreateUserListInSpinner() { onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .performNewVariableInitial(newList) .checkShowsText(newList); }
Source:
public void setUp() throws Exception { Script script = BrickTestUtils.createProjectAndGetStartScript("PhiroSeekBarColorBrickTest"); script.addBrick(new PhiroRGBLightBrick(PhiroRGBLightBrick.Eye.BOTH, INIT_COLOR_VALUE, INIT_COLOR_VALUE, INIT_COLOR_VALUE)); START baseActivityTestRule.launchActivity(null); END } please call baseActivityTestRule.launchActivity() if you give it null, it ignores the fragment position given in the rules constructor.

Target:
public void setUp() throws Exception { Script script = BrickTestUtils.createProjectAndGetStartScript("PhiroSeekBarColorBrickTest"); script.addBrick(new PhiroRGBLightBrick(PhiroRGBLightBrick.Eye.BOTH, INIT_COLOR_VALUE, INIT_COLOR_VALUE, INIT_COLOR_VALUE)); baseActivityTestRule.launchActivity(); }
Source:
public void uncaughtException(Thread thread, Throwable exception) { CrashReporter.storeUnhandledException(exception); preferences.edit().putBoolean(RECOVERED_FROM_CRASH, true).commit(); START Log.e(TAG, "uncaughtException: ", exception); END exit(); } Exactly! Thanks! Oh, please move this line up to the top of the method. Logging the error should be the first statement imo.

Target:
public void uncaughtException(Thread thread, Throwable exception) { Log.e(TAG, "uncaughtException: ", exception); CrashReporter.storeUnhandledException(exception); preferences.edit().putBoolean(RECOVERED_FROM_CRASH, true).commit(); exit(); }
Source:
public void onLoadProjectSuccess(boolean startProjectActivity) { if (getActivity() == null) { START Log.e(TAG, "Null Value of getActivity() at onLoadProjectSuccess"); END return; } Intent intent = new Intent(getActivity(), ProjectActivity.class); intent.putExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST, true); getActivity().startActivity(intent); } You don't need to check for `null` because the Task which triggers this callback should have been canceled anyway. If the problem still exists, Crashlytics will tell us.

Target:
public void onLoadProjectSuccess(boolean startProjectActivity) { Intent intent = new Intent(getActivity(), ProjectActivity.class); intent.putExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST, true); getActivity().startActivity(intent); }
Source:
private void disposeTextures() { for (Scene scene : project.getSceneList()) { for (Sprite sprite : scene.getSpriteList()) { START for (int j = 0; j < sprite.getLookDataList().size(); j++) { END LookData lookData = sprite.getLookDataList().get(j); lookData.getPixmap().dispose(); lookData.getTextureRegion().getTexture().dispose(); } } } } `for (LookData lookData : sprite.getLookDataList()) {` I'll take a look at the test asap

Target:
private void disposeTextures() { for (Scene scene : project.getSceneList()) { for (Sprite sprite : scene.getSpriteList()) { for (LookData lookData : sprite.getLookDataList()) { lookData.getPixmap().dispose(); lookData.getTextureRegion().getTexture().dispose(); } } } }
Source:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled); editor.commit(); if (isEnabled) { CloudMessaging.initialize(context); START } END } Disabling notifications will not unsubscribe from FCM (immediately) if `CloudMessaging.initialize` is not called. However, see https://github.com/Catrobat/Catroid/pull/2430#issuecomment-318926128

Target:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled).commit(); CloudMessaging.initialize(context); }
Source:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); START editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled); END editor.commit(); CloudMessaging.initialize(context); } you can directly put `.commit()` at the end of this. Editor calls always return the Editor again ;)

Target:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled).commit(); CloudMessaging.initialize(context); }
Source:
protected void doLookUpdate() { updateLookFromFormula(); if (wait) { START BackgroundWaitHandler.addObserver(look, this); END } if (look != null && sprite != null && sprite.getLookDataList().contains(look)) { sprite.look.setLookData(look); setLookDone = true; } } should this really be done before the check below? what happens if the observer gets added, but the `setLookData()` never gets called?

Target:
protected void doLookUpdate() { updateLookFromFormula(); if (look != null && sprite != null && sprite.getLookDataList().contains(look)) { if (wait) { BackgroundWaitHandler.addObserver(look, this); } sprite.look.setLookData(look); setLookDone = true; } }
Source:
public List<BackPackedListData> getBackPackedListData() { START return backPackedListData != null ? backPackedListData : new ArrayList<BackPackedListData>(); END } It would be better to initialise the member variable at the point of declaration (i.e. ``` List<BackpackedListData> backPackedListData = new ArrayList<>(); ``` instead of checking here. you can still overwrite the list at other points and you save yourself this (unnecessary) check.

Target:
public List<BackPackedListData> getBackPackedListData() { return backPackedListData; }
Source:
public static int getUniqueNotificationId() { if (uniqueNotificationIdCounter == null) { uniqueNotificationIdCounter = new AtomicInteger(0); START } END return uniqueNotificationIdCounter.incrementAndGet(); } since it's not a static method anymore with the latest changes, it might be removed again, am i right?

Target:
public int getUniqueNotificationId() { return uniqueNotificationIdCounter.incrementAndGet(); }
Source:
START public void buttonContinueOpensProjectActivity() throws ClassNotFoundException, END NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IllegalAccessException { onView(withId(R.id.main_menu_button_continue)) .perform(click()); onView(withId(R.id.fragment_sprites_list)) .check(matches(isDisplayed())); } why the list of exceptions?

Target:
public void buttonContinueOpensProjectActivity() { onView(withId(R.id.main_menu_button_continue)) .perform(click()); onView(withId(R.id.fragment_sprites_list)) .check(matches(isDisplayed())); }
Source:
public static void setAutoCrashReportingEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CRASH_REPORTS, isEnabled); editor.commit(); START CrashReporter.IS_CRASH_REPORTER_INITIALIZED = CrashReporter.initialize(context); END } Instead of assigning the variable here, update the variable in the `CrashReporter.initialize` method itself.

Target:
public static void setAutoCrashReportingEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CRASH_REPORTS, isEnabled); editor.commit(); if (isEnabled) { CrashReporter.initialize(context); } }
Source:
public static void setAutoCrashReportingEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CRASH_REPORTS, isEnabled); editor.commit(); START CrashReporter.initialize(context); END } Please undo as was. Calling initialize even if you don't want to initialize the CrashReporter is really really odd.

Target:
public static void setAutoCrashReportingEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CRASH_REPORTS, isEnabled); editor.commit(); if (isEnabled) { CrashReporter.initialize(context); } }
Source:
public static boolean initialize(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); START if (CrashReporter.isReportingEnabled()) { END reporter.initialize(context); Log.d(TAG, "INITIALIZED!"); return true; } Log.d(TAG, "INITIALIZATION FAILED! [ Report : " + isReportingEnabled() + "]"); return false; } ~`CrashReporter.`~`isReportingEnabled()`

Target:
public static boolean initialize(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); if (isReportingEnabled()) { reporter.initialize(context); Log.d(TAG, "INITIALIZED!"); return true; } Log.d(TAG, "INITIALIZATION FAILED! [ Report : " + isReportingEnabled() + "]"); return false; }
Source:
public void testAutoCrashReportEnabling() { Context context = InstrumentationRegistry.getTargetContext(); SettingsActivity.setAutoCrashReportingEnabled(context, false); verify(CrashReporter.reporter, Mockito.times(0)).initialize(context); SettingsActivity.setAutoCrashReportingEnabled(context, true); START verify(CrashReporter.reporter, Mockito.times(1)).initialize(context); END } `verify(`~`CrashReporter.`~`reporter, `~`Mockito.`~`times(1)).initialize(context);`

Target:
public void testAutoCrashReportEnabling() { Context context = InstrumentationRegistry.getTargetContext(); SettingsActivity.setAutoCrashReportingEnabled(context, false); verify(reporter, times(0)).initialize(context); SettingsActivity.setAutoCrashReportingEnabled(context, true); verify(reporter, times(1)).initialize(context); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); START sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); END } Inline occurrences

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); }
Source:
public boolean isRecoveredFromCrash() { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(RECOVERED_FROM_CRASH, false); START } END Please make private and put it after the `checkIfCrashRecoveryAndFinishActivity` method. > We like to put the private utilities called by a public function right after the public function itself. This follows the stepdown rule and helps the program read like a newspaper article. -Clean Code|Chapter 10: Classes

Target:
private boolean isRecoveredFromCrash() { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(RECOVERED_FROM_CRASH, false); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler(this)); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); START CrashReporter.sendUnhandledCaughtException(); END } this is really obvuscating whats going on here, it says sendUnhandledCaughtException and is called EVERY time on create of the activity. why not move the whole thing to checkIfCrashRecovery or into exceptionHandler or somewhere else...

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); }
Source:
public static void sendUnhandledCaughtException() { String json = preferences.getString(EXCEPTION_FOR_REPORT, ""); if (isReportingEnabled() && !json.isEmpty()) { Log.d(TAG, "AFTER_EXCEPTION : sendCaughtException()"); Gson gson = new Gson(); Throwable exception = gson.fromJson(json, Throwable.class); START if (logException(exception)) { END preferences.edit().remove(EXCEPTION_FOR_REPORT).commit(); } } } please make logException return void. - the boolean return value is only utilized here. - its always going to be true, since in line 93 you made sure that its only reached when isReportingEnabled() is true

Target:
public static void sendUnhandledCaughtException() { String json = preferences.getString(EXCEPTION_FOR_REPORT, ""); if (isReportingEnabled() && !json.isEmpty()) { Log.d(TAG, "AFTER_EXCEPTION : sendCaughtException()"); Gson gson = new Gson(); Throwable exception = gson.fromJson(json, Throwable.class); logException(exception); preferences.edit().remove(EXCEPTION_FOR_REPORT).commit(); } }
Source:
public void uncaughtException(Thread thread, Throwable exception) { Log.e(TAG, "unhandled exception", exception); CrashReporter.storeUnhandledException(exception); START if (!BuildConfig.DEBUG) { END System.exit(EXIT_CODE); android.os.Process.killProcess(android.os.Process.myPid()); } } Please remove the if condition (keep the content (exit, kill)). We are handling this in https://github.com/Catrobat/Catroid/pull/2365#discussion_r123898209 There seems to be a problem if we don't exit, kill the process. More details on https://github.com/Catrobat/Catroid/pull/2365#discussion_r124620967

Target:
public void uncaughtException(Thread thread, Throwable exception) { Log.e(TAG, "unhandled exception", exception); CrashReporter.storeUnhandledException(exception); System.exit(EXIT_CODE); android.os.Process.killProcess(android.os.Process.myPid()); }
Source:
public void createProject() { START Script script; END brickPosition = 1; ifBrick = new PhiroIfLogicBeginBrick(); IfLogicElseBrick ifLogicElseBrick = new IfLogicElseBrick(ifBrick); IfLogicEndBrick ifLogicEndBrick = new IfLogicEndBrick(ifLogicElseBrick, ifBrick); ifBrick.setIfElseBrick(ifLogicElseBrick); ifBrick.setIfEndBrick(ifLogicEndBrick); script = BrickTestUtils.createProjectAndGetStartScript("PhiroIfBrickTest"); script.addBrick(ifBrick); script.addBrick(ifLogicElseBrick); script.addBrick(ifLogicEndBrick); } why initialization separate from assignment? (line120)

Target:
public void createProject() { brickPosition = 1; ifBrick = new PhiroIfLogicBeginBrick(); IfLogicElseBrick ifLogicElseBrick = new IfLogicElseBrick(ifBrick); IfLogicEndBrick ifLogicEndBrick = new IfLogicEndBrick(ifLogicElseBrick, ifBrick); ifBrick.setIfElseBrick(ifLogicElseBrick); ifBrick.setIfEndBrick(ifLogicEndBrick); Script script = BrickTestUtils.createProjectAndGetStartScript("PhiroIfBrickTest"); script.addBrick(ifBrick); script.addBrick(ifLogicElseBrick); script.addBrick(ifLogicEndBrick); }
Source:
public void setUp() throws Exception { createProjectAndGetStartScriptWithImages("BroadcastBrickTest"); baseActivityTestRule.launchActivity(null); START onView(withId(R.id.brick_when_condition_edit_text)).perform(click()); END onView(withId(R.id.formula_editor_keyboard_sensors)).perform(click()); onView(withText(getResourcesString(R.string.formula_editor_function_touched))).perform(click()); onView(withId(R.id.formula_editor_keyboard_ok)).perform(click()); } why is this necessary? why onTouch? please do not use espresso onView or onData operations in setUp.

Target:
public void setUp() throws Exception { createProjectAndGetStartScriptWithImages("BroadcastBrickTest"); baseActivityTestRule.launchActivity(null); }
Source:
public void clear(String sceneName) { START if (!broadcastSequenceMap.containsKey(sceneName)) { END return; } broadcastSequenceMap.get(sceneName).clear(); } please change to: if (broadcastSequenceMap.containsKey(sceneName)) { broadcastSequenceMap.get(sceneName).clear(); } its a lot easier to read...

Target:
public void clear(String sceneName) { if (broadcastSequenceMap.containsKey(sceneName)) { broadcastSequenceMap.get(sceneName).clear(); } }
Source:
public void setUp() throws Exception { brickPosition = 1; START valToChange = 30.5f; END BrickTestUtils.createProjectAndGetStartScript("changeTransparencyByNBricktest1") .addBrick(new ChangeTransparencyByNBrick()); baseActivityTestRule.launchActivity(null); } same as above, please make this a local variable instead of a member

Target:
public void setUp() throws Exception { brickPosition = 1; BrickTestUtils.createProjectAndGetStartScript("changeTransparencyByNBricktest1") .addBrick(new ChangeTransparencyByNBrick()); baseActivityTestRule.launchActivity(null); }
Source:
public static void enlargeButtonText(Button button) { if (modifier == 1.0f) { return; } START if (!enlargedButtons.contains(button)) { END button.setTextSize(TypedValue.COMPLEX_UNIT_PX, button.getTextSize() * getModifier()); enlargedButtons.add(button); } } is this keeping of already modified buttons necessary?

Target:
public static void enlargeButtonText(Button button) { if (modifier == 1.0f) { return; } button.setTextSize(TypedValue.COMPLEX_UNIT_PX, button.getTextSize() * getModifier()); }
Source:
private Object interpretDistanceToSpritePosition(Sprite currentSprite, String secondSpriteName) { Sprite secondSprite; try { secondSprite = ProjectManager.getInstance().getSceneToPlay().getSpriteBySpriteName(secondSpriteName); } catch (Resources.NotFoundException exception) { return 0d; START } END float secondSpriteXPosition = secondSprite.look.getXInUserInterfaceDimensionUnit(); float secondSpriteYPosition = secondSprite.look.getYInUserInterfaceDimensionUnit(); return currentSprite.look.getDistanceToInUserInterfaceDimensions(secondSpriteXPosition, secondSpriteYPosition); } None of the methods in the try block throw a `NotFoundException`.

Target:
private Object interpretDistanceToSpritePosition(Sprite currentSprite, String secondSpriteName) { Sprite secondSprite; secondSprite = ProjectManager.getInstance().getSceneToPlay().getSpriteBySpriteName(secondSpriteName); float secondSpriteXPosition = secondSprite.look.getXInUserInterfaceDimensionUnit(); float secondSpriteYPosition = secondSprite.look.getYInUserInterfaceDimensionUnit(); return currentSprite.look.getDistanceToInUserInterfaceDimensions(secondSpriteXPosition, secondSpriteYPosition); }
Source:
private void askQuestion() { ArrayList<Object> params = new ArrayList<>(); params.add(this); START if (StageActivity.messageHandler == null) { END return; } // Check to see if a recognition activity is present Message message = StageActivity.messageHandler.obtainMessage(StageActivity.REGISTER_INTENT, params); message.sendToTarget(); questionAsked = true; } This can be done before creating the ArrayList (also in AskAction)

Target:
private void askQuestion() { if (StageActivity.messageHandler == null) { return; } ArrayList<Object> params = new ArrayList<>(); params.add(this); Message message = StageActivity.messageHandler.obtainMessage(StageActivity.REGISTER_INTENT, params); message.sendToTarget(); questionAsked = true; }
Source:
public static <T extends Object> List<T> distinctListByClassOfObjects(List<T> listToDistinct) { List<T> distinctList = new ArrayList<>(); HashMap<Class, T> uniqueMap = new HashMap<>(); for (T objectInstance : listToDistinct) { uniqueMap.put(objectInstance.getClass(), objectInstance); } distinctList.addAll(uniqueMap.values()); START return distinctList; END } Perfect! :+1: Just a few things. I'm a little picky here :grimacing: No need to `extends Object`. Please use `Map` as declaration type. ```java return new ArrayList<>(uniqueMap.values()); ``` The method is a perfect text-book example for tests. :wink:

Target:
public static <T> List<T> distinctListByClassOfObjects(List<T> listToDistinct) { Map<Class, T> uniqueMap = new HashMap<>(); for (T objectInstance : listToDistinct) { uniqueMap.put(objectInstance.getClass(), objectInstance); } return new ArrayList<>(uniqueMap.values()); }
Source:
public Scene getCurrentScene() { if (currentScene == null && project != null) { currentScene = project.getDefaultScene(); } START return currentScene; END } can it happen here that null is returned when current scene = null and project = null? can this be a problem?

Target:
public Scene getCurrentScene() { if (currentScene == null) { currentScene = project.getDefaultScene(); } return currentScene; }
Source:
public void onClick(View view) { if (adapter == null) { return; } if (adapter.getActionMode() != BrickAdapter.ActionModeEnum.NO_ACTION) { return; } START if (((BrickAdapter) adapter).isDragging) { END return; } showFormulaEditorToEditFormula(view); } possible cause of ClassCastException, instanceof check required before casting

Target:
public void onClick(View view) { if (adapter == null) { return; } if (adapter.getActionMode() != BrickAdapter.ActionModeEnum.NO_ACTION) { return; } if (adapter instanceof BrickAdapter && ((BrickAdapter) adapter).isDragging) { return; } showFormulaEditorToEditFormula(view); }
Source:
public boolean checkSpriteReplaceInBackpack(List<Sprite> currentSpriteList) { START boolean spritesAlreadyInBackpack; END for (Sprite sprite : currentSpriteList) { spritesAlreadyInBackpack = checkSpriteReplaceInBackpack(sprite); if (spritesAlreadyInBackpack) { return true; } } return false; } Please inline and remove

Target:
public boolean checkSpriteReplaceInBackpack(List<Sprite> currentSpriteList) { for (Sprite sprite : currentSpriteList) { if (checkSpriteReplaceInBackpack(sprite)) { return true; } } return false; }
Source:
private void addAttribute(XMLExtendedStreamReader reader, ModelNode operation, SimpleAttributeDefinition attributeDefinition) throws XMLStreamException { START String value = rawAttributeText(reader, attributeDefinition.getXmlName(), attributeDefinition.getDefaultValue().asString()); END if (value != null) { attributeDefinition.parseAndSetParameter(value, operation, reader); } else { throw missingRequired(reader, attributeDefinition.getXmlName()); } } @ochaloup The parser can't do this. It needs to preserve what it read from the xml, not introduce default values into the management model that were not what the user put in the xml. The subsystem can use a default value from the AttributeDefinition to configure the runtime services, but what's stored in the management model should reflect the user provided configuration. It appears this method is only called by the parseCM method, so I think just eliminating the 'else' block that throws missingRequired would be fine.

Target:
private void addAttribute(XMLExtendedStreamReader reader, ModelNode operation, SimpleAttributeDefinition attributeDefinition) throws XMLStreamException { String value = rawAttributeText(reader, attributeDefinition.getXmlName(), null); if (value != null) { attributeDefinition.parseAndSetParameter(value, operation, reader); } }
Source:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); } catch (Throwable e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway EeLogger.ROOT_LOGGER.debugf(e,"Ignoring failure to handle interceptor annotations for %s", description.getComponentClassName()); START return; END } } LGTM. Some minor points: we can now remove `throws DeploymentUnitProcessingException` since the method already catches all exceptions. `return;` is now also redundant. `final <class> componentClass` can be combined with assignment.

Target:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) { try { final Class<?> componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); } catch (Throwable e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway EeLogger.ROOT_LOGGER.debugf(e,"Ignoring failure to handle interceptor annotations for %s", description.getComponentClassName()); } }
Source:
protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { super.recordCapabilitiesAndRequirements(context, operation, resource); START ModelNode defaultTracer = DEFAULT_TRACER.resolveModelAttribute(context, operation); END if (defaultTracer.isDefined()) { context.registerCapability(RuntimeCapability.Builder.of(DEFAULT_TRACER_CAPABILITY.getDynamicName(defaultTracer.asString()), false).build()); } } I don't think you want to call the super implementation, as you are handling capability registration conditionally.

Target:
protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { ModelNode defaultTracer = DEFAULT_TRACER.resolveModelAttribute(context, operation); if (defaultTracer.isDefined()) { context.registerCapability(DEFAULT_TRACER_CAPABILITY); } }
Source:
static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) { START String[] prefixes = new String[keyPrefix.length + 1]; prefixes[0] = SUBSYSTEM_NAME; System.arraycopy(keyPrefix, 0, prefixes, 1, keyPrefix.length); END return getResourceDescriptionResolver(false, prefixes); } This seems a bit unnecessary. Any way to avoid it?

Target:
static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) { return getResourceDescriptionResolver(false, keyPrefix); }
Source:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { START super.registerAttributes(resourceRegistration); END resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION_NAME, null); resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION, null); } The super implementation is a no-op by design.

Target:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION_NAME, null); resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION, null); }
Source:
public void testStatefulTimeout0() throws Exception { Annotated0TimeoutBean timeout0 = lookup(Annotated0TimeoutBean.class); timeout0.doStuff(); START Thread.sleep(2000); END try { timeout0.doStuff(); throw new RuntimeException("Expecting NoSuchEJBException"); } catch (NoSuchEJBException expected) { } Assert.assertTrue(Annotated0TimeoutBean.preDestroy); } This sleep should not be necessary.

Target:
public void testStatefulTimeout0() throws Exception { Annotated0TimeoutBean timeout0 = lookup(Annotated0TimeoutBean.class); timeout0.doStuff(); try { timeout0.doStuff(); throw new RuntimeException("Expecting NoSuchEJBException"); } catch (NoSuchEJBException expected) { } Assert.assertTrue(Annotated0TimeoutBean.preDestroy); }
Source:
public void accept(T value) { Lock lock = this.lock.writeLock(); lock.lock(); try { START this.value = value; END } finally { lock.unlock(); } } If you'll eliminate the lock, accept method will contain just "this.value = value;" statement

Target:
public synchronized void accept(T value) { this.value = value; }
Source:
public <R, E extends Exception> R execute(ExceptionFunction<T, R, E> function) throws E { Lock lock = this.lock.readLock(); lock.lock(); try { T value = this.value; START return (value != null) ? function.apply(value) : null; END } finally { lock.unlock(); } } And above two lines will do perfect job for you. Yes, you could miss some statistics, but this is the case anyway because there's a race condition between retrieving the executor and invoking it.

Target:
public synchronized <R, E extends Exception> R execute(ExceptionFunction<T, R, E> function) throws E { return (this.value != null) ? function.apply(this.value) : null; }
Source:
private static AttributeDefinition getAttributeDefinition(String name, ModelType modelType, ModelNode defaultValue) { if (NO_DEFAULT.equals(defaultValue.asString())) { return new SimpleAttributeDefinitionBuilder(name, modelType) .setRequired(false) START .setAllowExpression(false) END .build(); } else { return new SimpleAttributeDefinitionBuilder(name, modelType) .setRequired(false) .setAllowExpression(false) .setDefaultValue(defaultValue) .build(); } } Attribute should allow expressions.

Target:
private static AttributeDefinition getAttributeDefinition(String name, ModelType modelType, ModelNode defaultValue) { if (NO_DEFAULT.equals(defaultValue.asString())) { return new SimpleAttributeDefinitionBuilder(name, modelType) .setRequired(false) .setAllowExpression(true) .build(); } else { return new SimpleAttributeDefinitionBuilder(name, modelType) .setRequired(false) .setAllowExpression(true) .setDefaultValue(defaultValue) .build(); } }
Source:
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException{ Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); ModelNode model = resource.getModel(); START attributeDefinition.validateAndSet(operation, model); END JaxrsContextParamHandler.setContextParam(attributeName, valueToRestore); } Doesn't belong in this method.

Target:
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException{ JaxrsContextParamHandler.setContextParam(attributeName, valueToRestore); }
Source:
private static AttributeDefinition getListAttributeDefinition(String name, ModelType modelType) { return new StringListAttributeDefinition.Builder(name) .setRequired(false) .setAllowExpression(false) .setValidator(JavaIdListValidator.INSTANCE) .build(); START } END Well, maybe that doesn't apply as this isn't really a map. It's a list of strings with the strings presumably being an opaque key/value pair. That's not how the WF management API typically handles maps.

Target:
private static AttributeDefinition getListAttributeDefinition(String name, ModelType modelType) { return new StringListAttributeDefinition.Builder(name) .setRequired(false) .setAllowExpression(true) .setValidator(JavaIdListValidator.INSTANCE) .build(); }
Source:
public boolean isCallerInRole(String role) { String caller = ctx.getCallerPrincipal().getName(); if (!USER.equals(caller)) { START log.severe("Caller name is not " + USER + ", but " + caller); END } return ctx.isCallerInRole(role); } Should this fail instead of just logging?

Target:
public boolean isCallerInRole(String role) throws Exception { String caller = ctx.getCallerPrincipal().getName(); if (!USER.equals(caller)) { throw new Exception("Caller name is not " + USER + ", but " + caller); } return ctx.isCallerInRole(role); }
Source:
public void close() { this.bean.close(); if (!this.bean.isValid()) { InfinispanBeanManager.this.cancel(this.bean); } else { InfinispanBeanManager.this.schedule(this.bean); } START } END I don't think it makes sense to schedule expiration/passivation on release. The last access time isn't updated until close(), and we already schedule for expiration/passivation then.

Target:
public void close() { this.bean.close(); if (!this.bean.isValid()) { InfinispanBeanManager.this.cancel(this.getId()); } else { InfinispanBeanManager.this.schedule(this.getId(), this.entry); } }
Source:
public void reset() { latch = new CountDownLatch(1); latch2 = new CountDownLatch(1); START System.out.println("RESET " + latch); END } This should probably be removed

Target:
public void reset() { latch = new CountDownLatch(1); latch2 = new CountDownLatch(1); }
Source:
public SmallRyeHealth getHealth() { START String emptyChecksStatus = emptyLivenessChecksStatus.equals(DOWN) || emptyReadinessChecksStatus.equals(DOWN) ? DOWN : UP; END return getHealth(emptyChecksStatus, healthChecks, livenessChecks, readinessChecks); } Just a proposal - changing this to ``` DOWN.equals(emptyLivenessChecksStatus) || DOWN.equals(emptyReadinessChecksStatus) ? DOWN : UP; ``` may prevent some possible NPEs.

Target:
public SmallRyeHealth getHealth() { String emptyChecksStatus = DOWN.equals(emptyLivenessChecksStatus) || DOWN.equals(emptyReadinessChecksStatus) ? DOWN : UP; return getHealth(emptyChecksStatus, healthChecks, livenessChecks, readinessChecks); }
Source:
public static boolean hasLogMessage(String logFileName, String logMessage) throws Exception { BufferedReader fileReader = null; boolean found = false; Path logPath = LoggingUtil.getInServerLogPath(logFileName); START fileReader = Files.newBufferedReader(logPath); END String line = ""; while ((line = fileReader.readLine()) != null) { if(line.contains(logMessage)) { found = true; break; } } fileReader.close(); return found; } We should probably just use a try with resources here. At a minimum we'd need the close in a finally block. Something like ``` public static boolean hasLogMessage(String logFileName, String logMessage) throws Exception { boolean found = false; Path logPath = LoggingUtil.getInServerLogPath(logFileName); try (BufferedReader fileReader = Files.newBufferedReader(logPath)) { String line = ""; while ((line = fileReader.readLine()) != null) { if (line.contains(logMessage)) { found = true; break; } } } return found; } ```

Target:
public static boolean hasLogMessage(String logFileName, String logMessage) throws Exception { boolean found = false; Path logPath = LoggingUtil.getInServerLogPath(logFileName); try (BufferedReader fileReader = Files.newBufferedReader(logPath)) { String line = ""; while ((line = fileReader.readLine()) != null) { if (line.contains(logMessage)) { found = true; break; } } } return found; }
Source:
public ResourceDescriptor addAttributes(Collection<AttributeDefinition> attributes) { for (AttributeDefinition attribute : attributes) { START this.addAttributes(new Attribute() { END @Override public AttributeDefinition getDefinition() { return attribute; } }); } return this; } There's no reason to wrap the AttributeDefinition. Add directly to the this.attributes collection.

Target:
public ResourceDescriptor addAttributes(Collection<AttributeDefinition> attributes) { this.attributes.addAll(attributes); return this; }
Source:
START public void destroy() { // add a breakpoint here to check if this method is invoked END LOG.info("===================="); LOG.info("Destroyed CountBean"); LOG.info("===================="); TestResultsBean.setPreDestroySessionScoped(true); } In order that the test runs successfully is a debugger required or is this some artifact of the test development?

Target:
public void destroy() { LOG.info("Destroyed CountBean"); TestResultsBean.setPreDestroySessionScoped(true); }
Source:
private void setPreservePathOnForward(Boolean preservePathOnForward) throws Exception { String opName = preservePathOnForward == null ? UNDEFINE_ATTRIBUTE_OPERATION : WRITE_ATTRIBUTE_OPERATION; START ModelNode setPreservePathOp = createOpNode("subsystem=undertow/servlet-container=default", WRITE_ATTRIBUTE_OPERATION); END setPreservePathOp.get("name").set("preserve-path-on-forward"); if (preservePathOnForward != null) { setPreservePathOp.get("value").set(preservePathOnForward); } CoreUtils.applyUpdate(setPreservePathOp, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); } Instead of `WRITE_ATTRIBUTE_OPERATION`, should not be used `opName` here?

Target:
private void setPreservePathOnForward(Boolean preservePathOnForward) throws Exception { String opName = preservePathOnForward == null ? UNDEFINE_ATTRIBUTE_OPERATION : WRITE_ATTRIBUTE_OPERATION; ModelNode setPreservePathOp = createOpNode("subsystem=undertow/servlet-container=default", opName); setPreservePathOp.get("name").set("preserve-path-on-forward"); if (preservePathOnForward != null) { setPreservePathOp.get("value").set(preservePathOnForward); } CoreUtils.applyUpdate(setPreservePathOp, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); }
Source:
public ElytronManagedThreadFactory(String name, ContextServiceImpl contextService, int priority) { super(name, contextService, priority); START fccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); END } It probably makes sense to just use the `org.jboss.as.ee` module class loader here instead of hoping we get the right one.

Target:
public ElytronManagedThreadFactory(String name, ContextServiceImpl contextService, int priority) { super(name, contextService, priority); }
Source:
private void activate() { ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); START NamespaceContextSelector.pushCurrentSelector(this.getNamespaceContextSelector()); END this.endpoint.activate(endpointFactory, activationSpec); NamespaceContextSelector.popCurrentSelector(); } catch (Exception e) { throw EjbLogger.ROOT_LOGGER.failedToActivateMdb(getComponentName(), e); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl); } } The code between push and pop should be wrapped in a "try" block, and pop invoked on "finally".

Target:
private void activate() { ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); NamespaceContextSelector.pushCurrentSelector(this.getNamespaceContextSelector()); try { this.endpoint.activate(endpointFactory, activationSpec); } finally { NamespaceContextSelector.popCurrentSelector(); } } catch (Exception e) { throw EjbLogger.ROOT_LOGGER.failedToActivateMdb(getComponentName(), e); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl); } }
Source:
START public DeploymentRepository getValue() throws IllegalStateException, IllegalArgumentException { END return this; } You can drop these from the throws clause. Not only are they not thrown, but they are RuntimeExceptions.

Target:
public DeploymentRepository getValue() { return this; }
Source:
public void stopContainer() throws Exception { deployer.undeploy(APP_CONTEXT); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); final ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); START LOGGER.info("*** reseting test configuration"); END serverTearDown(managementClient); LOGGER.trace("*** stopping container"); containerController.stop(CONTAINER); } Was there a reason to change this to info instead of trace?

Target:
public void stopContainer() throws Exception { deployer.undeploy(APP_CONTEXT); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); final ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); LOGGER.trace("*** reseting test configuration"); serverTearDown(managementClient); LOGGER.trace("*** stopping container"); containerController.stop(CONTAINER); }
Source:
public void run() { final ExecutorService executor = executorServiceInjectedValue.getOptionalValue(); START if (executor != null) { END executor.submit(this::persistTimer); } } This will never be null, as this is not an optional dependency. Functionally it makes no difference but it could be confusing to someone reading the code.

Target:
public void run() { executorServiceInjectedValue.getValue().submit(this::persistTimer); }
Source:
private Indexer indexStream(InputStream stream) { try { Indexer indexer = new Indexer(); indexer.index(stream); return indexer; START } catch (IOException e) { END throw new IllegalStateException(e); } } This stream is not closed

Target:
private Indexer indexStream(InputStream stream) { try { Indexer indexer = new Indexer(); indexer.index(stream); stream.close(); return indexer; } catch (IOException e) { throw new IllegalStateException(e); } }
Source:
START public String invoke(String id) { END String interceptorInvocationCounterKey = id + "-COUNT"; log.info("Test Invoked"); String clientInterceptor = wasClientInterceptorInvoked(); log.info(String.format("clientInterceptorInvoked: %b %s", (clientInterceptor!=null), clientInterceptor)); context.getContextData().put("ClientInterceptorInvoked", clientInterceptor); return "" + context.getContextData().get(interceptorInvocationCounterKey); } What is the purpose of this? you just pulled it out of the same map key?

Target:
public int invoke(String id) { String interceptorInvocationCounterKey = id + "-COUNT"; String clientInterceptor = wasClientInterceptorInvoked(); context.getContextData().put("ClientInterceptorInvoked", clientInterceptor); return (Integer) context.getContextData().get(interceptorInvocationCounterKey); }
Source:
LegacyProtocolResourceDefinition(String name, String targetName, JGroupsModel deprecation, Consumer<ResourceDescriptor> descriptorConfigurator, ResourceServiceBuilderFactory<ChannelFactory> parentBuilderFactory) { START super(pathElement(name), descriptorConfigurator.andThen(descriptor -> descriptor.setAddOperationTransformation(new OperationTransformation(targetName)).setOperationTransformation(new OperationTransformation(targetName))), null, parentBuilderFactory); END this.setDeprecated(deprecation.getVersion()); } lambda

Target:
LegacyProtocolResourceDefinition(String name, String targetName, JGroupsModel deprecation, Consumer<ResourceDescriptor> descriptorConfigurator, ResourceServiceBuilderFactory<ChannelFactory> parentBuilderFactory) { super(pathElement(name), descriptorConfigurator.andThen(new OperationTransformation(targetName)), null, parentBuilderFactory); this.setDeprecated(deprecation.getVersion()); }
Source:
public static JavaArchive createDeployment() { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar"); jar.addPackage(UserTransactionAccessTestCase.class.getPackage()); START jar.as(ZipExporter.class).exportTo(new File(TestSuiteEnvironment.getTmpDir(), jar.getName()), true); END return jar; } I think this like should have just been deleted, there is no reason to export the archive

Target:
public static JavaArchive createDeployment() { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar"); jar.addPackage(UserTransactionAccessTestCase.class.getPackage()); return jar; }
Source:
public ServiceBuilder<SecurityConfiguration> build(ServiceTarget target) { ServiceBuilder<SecurityConfiguration> builder = target.addService(this.getServiceName(), new ValueService<>(this)).setInitialMode(ServiceController.Mode.ON_DEMAND); START if (sslContextDependency != null) { END this.sslContextDependency.register(builder); } return builder; } return (this.sslContextDependency != null) ? this.sslContextDependency.register(builder) : builder; :)

Target:
public ServiceBuilder<SecurityConfiguration> build(ServiceTarget target) { ServiceBuilder<SecurityConfiguration> builder = target.addService(this.getServiceName(), new ValueService<>(this)).setInitialMode(ServiceController.Mode.ON_DEMAND); return (this.sslContextDependency != null) ? this.sslContextDependency.register(builder) : builder; }
Source:
public ResourceDescriptor addRequiredChildren(Set<? extends ResourceDefinition> set) { START set.forEach(definition -> this.requiredChildren.add(definition.getPathElement())); END return this; } Use normal for-each loop instead of lambda.

Target:
public ResourceDescriptor addRequiredChildren(Set<? extends ResourceDefinition> set) { for (ResourceDefinition definition : set) { this.requiredChildren.add(definition.getPathElement()); } return this; }
Source:
public ServiceBuilder<PersistenceConfiguration> build(ServiceTarget target) { ServiceBuilder<PersistenceConfiguration> builder = super.build(target); START this.remoteCacheContainer.register(builder); END return builder; } return this.remoteCacheContainer.register(super.build(target));

Target:
public ServiceBuilder<PersistenceConfiguration> build(ServiceTarget target) { return this.remoteCacheContainer.register(super.build(target)); }
Source:
public void setSocketAddresses(List<InetSocketAddress> addresses) { START List<PhysicalAddress> list = new ArrayList<>(); END for (InetSocketAddress address : addresses) { IpAddress ipAddress = new IpAddress(address.getAddress(), address.getPort()); list.add(ipAddress); } this.setInitialHosts(list); } ArrayList should be constructed with fixed capacity.

Target:
public void setSocketAddresses(List<InetSocketAddress> addresses) { List<PhysicalAddress> list = new ArrayList<>(addresses.size()); for (InetSocketAddress address : addresses) { IpAddress ipAddress = new IpAddress(address.getAddress(), address.getPort()); list.add(ipAddress); } this.setInitialHosts(list); }