auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ServerTemplate loadServerTemplate(String serverTemplateId) { START ServerTemplate template = getTemplateStorage().load(serverTemplateId); END if (template == null) { throw new RuntimeException("No server template found for id " + serverTemplateId); } return template; } (`final`)

Target:
private ServerTemplate loadServerTemplate(String serverTemplateId) { final ServerTemplate template = getTemplateStorage().load(serverTemplateId); if (template == null) { throw new RuntimeException("No server template found for id " + serverTemplateId); } return template; }
Source:
private void onSaveError(final ClientRuntimeError error) { START showError(error.getThrowable() instanceof DefinitionNotFoundException ? "somps" : error.getMessage()); END } "somps"? What's this?

Target:
private void onSaveError(final ClientRuntimeError error) { showError(error); }
Source:
public static Optional<ClassLoader> loadDependenciesClassloaderFromProject(String prjPath, String localRepo) { List<String> poms = new ArrayList<>(); MavenUtils.searchPoms(Paths.get(URI.create(FILE_URI + prjPath)), START poms); END List<URL> urls = getDependenciesURL(poms, localRepo); return buildResult(urls); } Personal preference here, but I would rather return the poms list with searchPoms than append them into the argument. Just that I usually don't expect the passed values to change (in Java).

Target:
public static Optional<ClassLoader> loadDependenciesClassloaderFromProject(String prjPath, String localRepo) { List<String> poms = MavenUtils.searchPoms(Paths.get(URI.create(FILE_URI + prjPath))); List<URL> urls = getDependenciesURL(poms, localRepo); return buildResult(urls); }
Source:
START public void isInternalImportExternalImportType() { END final Imports imports = new Imports(); final Import importType = new Import("External1"); imports.addImport(importType); presenter.setContent(dmo, imports, false); assertFalse(presenter.isInternalImport(mock(Import.class))); } This method contains assertion: ``` assertFalse(presenter.isInternalImport(mock(Import.class))); ``` Shouldn't be this? ``` assertFalse(presenter.isInternalImport(importType)); ```

Target:
public void isInternalImportExternalImportType() { final Imports imports = new Imports(); final Import importType = new Import("External1"); imports.addImport(importType); presenter.setContent(dmo, imports, false); assertFalse(presenter.isInternalImport(importType)); }
Source:
public T setFillGradient(final Type type, final String startColor, final String endColor) { this.fillGradientType = type; this.fillGradientStartColor = startColor; this.fillGradientEndColor = endColor; if (null != getShape()) { final BoundingBox bb = getShape().getBoundingBox(); START textViewDecorator.setTextBoundaries(bb); END final double width = bb.getWidth(); final double height = bb.getHeight(); updateFillGradient(width, height); } return cast(); } Why the need to set text bounds when setting the fill gradient? And.. if this is for good reason, then why not do it [here](https://github.com/Christopher-Chianelli/kie-wb-common/blob/23c7dfd45dfff9d7840b2f9e3f08d26228dbfe5c/kie-wb-common-stunner/kie-wb-common-stunner-client/kie-wb-common-stunner-lienzo/src/main/java/org/kie/workbench/common/stunner/client/lienzo/shape/view/wires/ext/WiresShapeViewExt.java#L189) so that potential use of either public methods sets the text bounds?

Target:
public T setFillGradient(final Type type, final String startColor, final String endColor) { this.fillGradientType = type; this.fillGradientStartColor = startColor; this.fillGradientEndColor = endColor; if (null != getShape()) { final BoundingBox bb = getShape().getBoundingBox(); final double width = bb.getWidth(); final double height = bb.getHeight(); updateFillGradient(width, height); } return cast(); }
Source:
private void onSafeRename() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to rename a .java file that could be parsed without errors, and we can calculate the //className we can check for class usages prior to renaming and we can also suggest to perform an automatic // class renaming. final String className = context.getEditorModelContent().getOriginalClassName(); START showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_renaming_of_used_class(className), END versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> rename(), () -> { }); } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file renaming procedure. rename(); } } @pefernan A test that checks the showAssetUsagesDisplayer is invocked will be appreciated please.

Target:
public void onSafeRename() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to rename a .java file that could be parsed without errors, and we can calculate the //className we can check for class usages prior to renaming and we can also suggest to perform an automatic // class renaming. final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_renaming_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> rename(), () -> { }); } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file renaming procedure. rename(); } }
Source:
START public Map getMap() { END return map; } Let's avoid raw types, please.

Target:
public Map<String, Object> getMap() { return map; }
Source:
public BoundingBox getBoundingBox() { if (getPathPartList().size() < 1) { START if (!parse(getAttributes())) { END return new BoundingBox(0, 0, 0, 0); } } return getPathPartList().getBoundingBox(); } Both `if` statements could be erased, `parse` returns always true. WDYT?

Target:
public BoundingBox getBoundingBox() { if (getPathPartList().size() < 1) { return new BoundingBox(0, 0, 0, 0); } return getPathPartList().getBoundingBox(); }
Source:
public static NIOKieMavenCompiler getCompiler(KieDecorator decorator) { START NIOKieMavenCompiler compiler = compilers.get(decorator); END if (compiler == null) { compiler = createAndAddNewCompiler(decorator); } return compiler; } decorator is of type KieDecorator, while the map is from Strings. perhaps you missed the `decorator.name()`?

Target:
public static NIOKieMavenCompiler getCompiler(KieDecorator decorator) { NIOKieMavenCompiler compiler = compilers.get(decorator.name()); if (compiler == null) { compiler = createAndAddNewCompiler(decorator); } return compiler; }
Source:
public void render(FormRenderingContext context) { layoutGenerator.clear(); formContent.clear(); if (context != null) { START Panel panel = layoutGenerator.buildLayout(context); END formContent.add(panel); } } @Christopher-Chianelli that's not a problem but maybe I'm forgetting something about this change, is there any reason for splitting this lines of code?

Target:
public void render(FormRenderingContext context) { layoutGenerator.clear(); formContent.clear(); if (context != null) { formContent.add(layoutGenerator.buildLayout(context)); } }
Source:
public void addVariable(String variable, String type) { if (variables.containsKey(variable)) { String existingType = variables.get(variable); if (!existingType.equals(type)) { valid = false; START errors.add("Wrong type for variable task variable '" + variable + "': expected type was '" + existingType + "' but received '" + type + "'."); END } } else { variables.put(variable, type); } } I see a problem with this error - user doesn't know where the expected type comes from (it is already added from other task).

Target:
public void addVariable(String variable, String type) { addVariable(Optional.empty(), variable, type); }
Source:
START void onCanvasElementSelectedEvent(@Observes CanvasElementSelectedEvent event) { END checkNotNull("event", event); final String uuid = event.getElementUUID(); if (isSameCanvas(event) && isRegistered(uuid)) { final HasControlPoints<?> hasControlPoints = getControlPointsInstance(uuid); if (!hasControlPoints.areControlsVisible()) { showCPs(hasControlPoints); } else { hideCPs(hasControlPoints); } } } Is it package private intentionally? Also this method has no test and, probably, not used.

Target:
private void onCanvasElementSelectedEvent(@Observes CanvasElementSelectedEvent event) { checkNotNull("event", event); final String uuid = event.getElementUUID(); if (isSameCanvas(event) && isRegistered(uuid)) { final HasControlPoints<?> hasControlPoints = getControlPointsInstance(uuid); if (!hasControlPoints.areControlsVisible()) { showCPs(hasControlPoints); } else { hideCPs(hasControlPoints); } } }
Source:
START public String getFormId() { END FormDefinition def = renderingContext.getRootForm(); return renderingContext.getRootForm().getId(); } I think this line should be `def.getId();` or the code on line 112 is useless.

Target:
public String getFormId() { return renderingContext.getRootForm().getId(); }
Source:
private void buildTestedInstance() { START ; END this.tested = new ClientFullSessionImpl(factory, canvasCommandManager, sessionCommandManager, requestCommandManager, registryFactory); } Floating semicolon

Target:
private void buildTestedInstance() { this.tested = new ClientFullSessionImpl(factory, canvasCommandManager, sessionCommandManager, requestCommandManager, registryFactory); }
Source:
public ListBoxBaseDefinition getDefaultField() { StringListBoxFieldDefinition result = new StringListBoxFieldDefinition(); START result.setStandaloneClassName(String.class.getName()); END return result; } same here, and so on, in case it could make sense

Target:
public ListBoxBaseDefinition getDefaultField() { return new StringListBoxFieldDefinition(); }
Source:
public String getDescription() { final String description = translationService.getTranslation(FormEditorConstants.NewFormDefinitionlHandlerForm); START return description != null && !description.isEmpty() ? description : "Form (Preview)"; END } I don't know the internals, so likely the case were "Form (Preview)" is returned is never reached. But i18n is appreciable in other case.

Target:
public String getDescription() { return translationService.getTranslation(FormEditorConstants.NewFormDefinitionlHandlerForm); }
Source:
private void formFieldsShouldNotBeGeneratedForPersistenceId(List<FieldDefinition> formModelFields) { START assertTrue(dataObject.getProperty("id") != null); END int EXPECTED_FORM_FIELD_COUNT = finderService.getDataObjectProperties(formModel.getClassName(), path).size() - 1; assertEquals("Form field should be generated for every data field except of persistence id", EXPECTED_FORM_FIELD_COUNT, formModelFields.size()); } Hi @jsoltes you can use Assert#assertNotNull(java.lang.Object) method here.

Target:
private void formFieldsShouldNotBeGeneratedForPersistenceId(List<FieldDefinition> formModelFields) { assertNotNull(dataObject.getProperty("id")); int EXPECTED_FORM_FIELD_COUNT = finderService.getDataObjectProperties(formModel.getClassName(), path).size() - 1; assertEquals("Form field should be generated for every data field except of persistence id", EXPECTED_FORM_FIELD_COUNT, formModelFields.size()); }
Source:
public CanvasHighlight invalid(final Iterable<? extends RuleViolation> violations) { violations.forEach(v -> { final String uuid = v.getUUID(); START if (null != uuid) { END applyStateToShape(uuid, ShapeState.INVALID); } }); getCanvas().draw(); return this; } Consider use of ```Optional```

Target:
public CanvasHighlight invalid(final Iterable<? extends RuleViolation> violations) { violations.forEach(v -> { final String uuid = v.getUUID(); applyStateToShape(uuid, ShapeState.INVALID); }); getCanvas().draw(); return this; }
Source:
START protected Optional<CommandResult<CanvasViolation>> doDragEnd(final Element element) { END final AbstractCanvas<?> canvas = canvasHandler.getAbstractCanvas(); final Shape<?> shape = canvas.getShape(element.getUUID()); final double x = shape.getShapeView().getShapeX(); final double y = shape.getShapeView().getShapeY(); return Optional.of(move(element, x, y)); } Heh, perhaps I'm being picky here.. but on this occasion is use of ```Optional``` required? Execution of a command should **always** result in a non-```null``` result?

Target:
private CommandResult<CanvasViolation> doDragEnd(final Element element) { final AbstractCanvas<?> canvas = canvasHandler.getAbstractCanvas(); final Shape<?> shape = canvas.getShape(element.getUUID()); final double x = shape.getShapeView().getShapeX(); final double y = shape.getShapeView().getShapeY(); return move(element, x, y); }
Source:
public CanvasViolationImpl build() { final CanvasViolationImpl result = new CanvasViolationImpl(ruleViolation.getMessage(), ruleViolation.getViolationType()); if (ruleViolation instanceof AbstractRuleViolation) { final String uuid = ((AbstractRuleViolation) ruleViolation).getUuid(); if (null != uuid) { result.setUuid(uuid); START ; END } } return result; } Floating ```;```

Target:
public CanvasViolationImpl build() { final CanvasViolationImpl result = new CanvasViolationImpl(ruleViolation.getMessage(), ruleViolation.getViolationType()); if (ruleViolation instanceof AbstractRuleViolation) { final String uuid = ((AbstractRuleViolation) ruleViolation).getUuid(); if (null != uuid) { result.setUuid(uuid); } } return result; }
Source:
protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { START final org.kie.workbench.common.stunner.core.graph.Graph graph = getGraph(context); END final Collection<RuleViolation> cardinalityRuleViolations = doEvaluate(context, RuleContextBuilder.GraphContexts.cardinality(graph, getCandidate(), CardinalityContext.Operation.ADD)); return new GraphCommandResultBuilder(cardinalityRuleViolations).build(); } Do we need FQCN?

Target:
protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { final Graph graph = getGraph(context); final Collection<RuleViolation> cardinalityRuleViolations = doEvaluate(context, RuleContextBuilder.GraphContexts.cardinality(graph, getCandidate(), CardinalityContext.Operation.ADD)); return new GraphCommandResultBuilder(cardinalityRuleViolations).build(); }
Source:
START private RuleExtensionHandler getExtensionHandler(final RuleExtension rule, END final RuleEvaluationContext context) { final RuleExtensionHandler handler = registry.getExtensionHandler(rule.getHandlerType()); return null != handler && accepts(handler, rule, context) ? handler : null; } Since you've used ```Optional``` elsewhere in this class; perhaps use of ```Optional``` here too would be nice?

Target:
private Optional<RuleExtensionHandler> getExtensionHandler(final RuleExtension rule, final RuleEvaluationContext context) { final RuleExtensionHandler handler = registry.getExtensionHandler(rule.getHandlerType()); return null != handler && accepts(handler, rule, context) ? Optional.of(handler) : Optional.empty(); }
Source:
public static RuleViolation addViolationSourceUUID(final String uuid, final RuleViolation violation) { try { ((AbstractRuleViolation) violation).setUuid(uuid); START } catch (final ClassCastException ignored) { END } return violation; } Why would we expect a CCE? To me this smells of a hack to fix a problem you had.

Target:
public static RuleViolation addViolationSourceUUID(final String uuid, final RuleViolation violation) { if (violation instanceof AbstractRuleViolation) { ((AbstractRuleViolation) violation).setUuid(uuid); } return violation; }
Source:
public <T> Collection<ValidationMessage> validateForSave( final Path path, final T content ) { START return (Collection<ValidationMessage>) saveValidators.stream().filter( v -> v.accept( path ) ).flatMap( c -> c.validate( path, END content ).stream().filter( r -> r != null ) ).collect( Collectors.toList() ); } Can we really have ```null``` ```ValidationMessage```? (it looks like you filter the list from validation for nulls)

Target:
public <T> Collection<ValidationMessage> validateForSave( final Path path, final T content ) { return (Collection<ValidationMessage>) saveValidators.stream().filter( v -> v.accept( path ) ).flatMap( c -> c.validate( path, content ).stream() ).collect( Collectors.toList() ); }
Source:
public void applyTitle(final String title, final W element, final MutationContext mutationContext) { START if (title.trim().length() > 0) { END // Apply title's value. viewHandler.applyTitle(title, mutationContext); // Apply title's font styles. applyFont(element, mutationContext); } } This condition is not covered by tests, but anyway I don't sure we are need this condition here.

Target:
public void applyTitle(final String title, final W element, final MutationContext mutationContext) { // Apply title's value. viewHandler.applyTitle(title, mutationContext); // Apply title's font styles. applyFont(element, mutationContext); }
Source:
void updateSelectedOrganizationalUnit() { START libraryService.call( new RemoteCallback<OrganizationalUnitRepositoryInfo>() { END @Override public void callback( final OrganizationalUnitRepositoryInfo newInfo ) { refreshLibrary( newInfo ); } } ).getOrganizationalUnitRepositoryInfo( getViewSelectedOrganizationalUnit() ); } Lamda?

Target:
void updateSelectedOrganizationalUnit() { libraryService.call( ( OrganizationalUnitRepositoryInfo newInfo ) -> refreshLibrary( newInfo ) ) .getOrganizationalUnitRepositoryInfo( getViewSelectedOrganizationalUnit() ); }
Source:
public void destroy() { this.canvasHandler = null; this.canvasHighlight = null; this.sourceNode = null; this.palette.destroy(); this.nodeDragProxyFactory.destroy(); this.nodeBuilderControl.setCommandManagerProvider(null); this.nodeBuilderControl.disable(); this.graphBoundsIndexer.destroy(); START this.canvasHighlight.destroy(); END } This method lead to NullPointerException: ```java this.canvasHighlight = null; [...] this.canvasHighlight.destroy(); ```

Target:
public void destroy() { this.palette.destroy(); this.nodeDragProxyFactory.destroy(); this.nodeBuilderControl.setCommandManagerProvider(null); this.nodeBuilderControl.disable(); this.graphBoundsIndexer.destroy(); this.canvasHighlight.destroy(); this.canvasHandler = null; this.canvasHighlight = null; this.sourceNode = null; }
Source:
public void destroy() { destroyToolbar(); destroyPalette(); START sessionManager.dispose(); END getDisplayer().destroy(); getView().destroy(); diagram = null; } It might be nicer to keep these terms the same "dispose" and "destroy". Does "dispose" do anything different to what I'd expect "destroy" to do?

Target:
public void destroy() { destroyToolbar(); destroyPalette(); sessionManager.destroy(); getDisplayer().destroy(); getView().destroy(); diagram = null; }
Source:
START public void initializeWithProjectsTest() { END doReturn( true ).when( libraryService ).thereIsAProjectInTheWorkbench(); libraryMonitor.initialize(); assertTrue( libraryMonitor.thereIsAtLeastOneProjectAccessible() ); verify( workbench ).addStartupBlocker( LibraryMonitor.class ); verify( workbench ).removeStartupBlocker( LibraryMonitor.class ); } As an aside (optional, if feel like changing) this test and ```initializeWithoutProjectsTest()``` are remarkably similar and perhaps removal of the duplicated code to a shared method with single ```isAProjectInTheWorkbench``` ```boolean``` parameter could remove the duplication.

Target:
public void initializeWithProjectsTest() { thereIsAProjectInTheWorkbench( true ); }
Source:
public void testAddPackagesToWhiteList() throws Exception { final WhiteList whiteList = new WhiteList(); grid.setDependencies( new POM(), whiteList ); final HashSet<String> packages = new HashSet<String>(); packages.add( "org.drools" ); packages.add( "org.guvnor" ); assertEquals( 0, whiteList.size() ); START grid.onAddAll( packages ); END } There's a missing assert here?

Target:
public void testAddPackagesToWhiteList() throws Exception { final WhiteList whiteList = new WhiteList(); grid.setDependencies( new POM(), whiteList ); final HashSet<String> packages = new HashSet<String>(); packages.add( "org.drools" ); packages.add( "org.guvnor" ); assertEquals( 0, whiteList.size() ); grid.onAddAll( packages ); assertEquals( 2, whiteList.size() ); }
Source:
public void init() { // Initialize caches. super.initialize(); // Initialize the application's VFS. initFileSystem(); // Register packaged diagrams into VFS. registerAppDefinitions(); // Load vfs diagrams and put into the parent registry. final Collection<Diagram> diagrams = getAllDiagrams(); if ( null != diagrams && !diagrams.isEmpty() ) { START for ( Diagram diagram : diagrams ) { END getRegistry().register( diagram ); } } } start using Java8. diagrams.forEach...

Target:
public void init() { // Initialize caches. super.initialize(); // Initialize the application's VFS. initFileSystem(); // Register packaged diagrams into VFS. registerAppDefinitions(); // Load vfs diagrams and put into the parent registry. final Collection<Diagram> diagrams = getAllDiagrams(); if ( null != diagrams ) { diagrams.forEach( diagram -> getRegistry().register( diagram ) ); } }
Source:
private Button button( final String text, final Command command, final ButtonType type ) { START Button button = new Button( text, new ClickHandler() { END @Override public void onClick( ClickEvent event ) { command.execute(); } } ); button.setType( type ); return button; } And here... re: @karreiro mention of lamdas :-)

Target:
Button button( final String text, final Command command, final ButtonType type ) { Button button = new Button( text, event -> command.execute() ); button.setType( type ); return button; }
Source:
void hideLoadingPopup() { START @SuppressWarnings("GwtToHtmlReferences") END final Element e = RootPanel.get( "loading" ).getElement(); new Animation() { @Override protected void onUpdate( double progress ) { e.getStyle().setOpacity( 1.0 - progress ); } @Override protected void onComplete() { e.getStyle().setVisibility( Style.Visibility.HIDDEN ); } }.run( 500 ); } @paulovmr in the future we should move this to uberfire.

Target:
public void hideLoadingPopup() { @SuppressWarnings("GwtToHtmlReferences") final Element e = RootPanel.get( "loading" ).getElement(); new Animation() { @Override protected void onUpdate( double progress ) { e.getStyle().setOpacity( 1.0 - progress ); } @Override protected void onComplete() { e.getStyle().setVisibility( Style.Visibility.HIDDEN ); } }.run( 500 ); }
Source:
public DataObjectCreatedEvent( Project currentProject, DataObject currentDataObject ) { START super( null, currentProject, currentDataObject ); END } I'm not a lover of passing nulls to methods or constructors.. would another constructor without the contextId be better?

Target:
public DataObjectCreatedEvent( Project currentProject, DataObject currentDataObject ) { super( currentProject, currentDataObject ); }
Source:
public DataObjectDeletedEvent(String source, DataModel currentModel, DataObject currentDataObject) { START super(null, source, currentModel, currentDataObject); END } I'm not a lover of passing nulls to methods or constructors.. would another constructor without the contextId be better?

Target:
public DataObjectDeletedEvent(String source, DataModel currentModel, DataObject currentDataObject) { super(source, currentModel, currentDataObject); }
Source:
public static OkHttpClient getInstance() { START if (sOkHttpClient == null) { END sOkHttpClient = new OkHttpClient(); sOkHttpClient.setConnectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setReadTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setWriteTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.networkInterceptors().add(new UserAgentInterceptor(getUserAgentString())); } return sOkHttpClient; } このメソッドをsynchronizedにするかsynchronizedブロックでThread safeにした方がよさそうです

Target:
public static synchronized OkHttpClient getInstance() { if (sOkHttpClient == null) { sOkHttpClient = new OkHttpClient(); sOkHttpClient.setConnectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setReadTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setWriteTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.networkInterceptors().add(new UserAgentInterceptor(getUserAgentString())); } return sOkHttpClient; }
Source:
protected boolean hasVideoAvailable() { if ( isTokenEvent ) { return tokenAd != null; } else { START return incentivizedInterstitial.isAdReadyToDisplay(); END } } what happens when this is called before incentivizedInterstitial is assigned?

Target:
protected boolean hasVideoAvailable() { if ( isTokenEvent ) { return tokenAd != null; } else { return ( incentivizedInterstitial != null && incentivizedInterstitial.isAdReadyToDisplay() ); } }
Source:
public void handleClick(@NonNull final View view) { super.handleClick( view ); parentNativeAd.launchClickTarget( view.getContext() ); START notifyAdClicked(); END } Can we keep the order we have previously? That is 1. notify ad click, 2. launch click target.

Target:
public void handleClick(@NonNull final View view) { super.handleClick( view ); notifyAdClicked(); parentNativeAd.launchClickTarget( view.getContext() ); }
Source:
private static void mkdirsOrThrow(File dir) throws IOException { START if (!dir.exists()) { END if (!dir.mkdirs()) { throw new IOException("Failed to create directory " + dir); } } } It's not an issue but I think that it's better to put the both checks on a single line (`if (!dir.exists() && !dir.mkdirs())`)

Target:
private static void mkdirsOrThrow(File dir) throws IOException { if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Failed to create directory " + dir); } }
Source:
private boolean pluginNotStarted(String pluginId) { if (pluginId != null) { PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId); if (PluginState.STARTED != pluginWrapper.getPluginState()) { return true; } START log.trace("Checking extensions from plugin '{}'", pluginId); END } else { log.trace("Checking extensions from classpath"); } return false; } I think that the log messages related to extensions cannot be part of "pluginNotStarted"

Target:
private boolean pluginNotStarted(String pluginId) { if (pluginId != null) { PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId); return PluginState.STARTED != pluginWrapper.getPluginState(); } return false; }
Source:
public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { START tryStartPlugin(pluginWrapper, pluginWrapper.getDescriptor(), pluginState); END } } } this is a mechanic extraction. it's enough to pass only the pluginWrapper

Target:
public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { tryStartPlugin(pluginWrapper); } } }
Source:
public void testCreateFailNotFound() { START PluginDescriptor pluginDescriptor = mock(DefaultPluginDescriptor.class); END when(pluginDescriptor.getPluginClass()).thenReturn("org.pf4j.plugin.NotFoundTestPlugin"); PluginWrapper pluginWrapper = mock(PluginWrapper.class); when(pluginWrapper.getDescriptor()).thenReturn(pluginDescriptor); when(pluginWrapper.getPluginClassLoader()).thenReturn(getClass().getClassLoader()); DefaultPluginFactory instance = new DefaultPluginFactory(); Plugin result = instance.create(pluginWrapper); assertNull(result); } No need to change. I feel that it's from the refactoring action

Target:
public void testCreateFailNotFound() { PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); when(pluginDescriptor.getPluginClass()).thenReturn("org.pf4j.plugin.NotFoundTestPlugin"); PluginWrapper pluginWrapper = mock(PluginWrapper.class); when(pluginWrapper.getDescriptor()).thenReturn(pluginDescriptor); when(pluginWrapper.getPluginClassLoader()).thenReturn(getClass().getClassLoader()); DefaultPluginFactory instance = new DefaultPluginFactory(); Plugin result = instance.create(pluginWrapper); assertNull(result); }
Source:
public void accumulate(long cx) { START N += cx; END M += (cx == 0 ? 0 : cx * Math.log(cx)); } simpler to wrap both lines in an if: ``` if (cx > 0) { .. } ```

Target:
public void accumulate(long cx) { if(cx > 0) { N += cx; M += cx * Math.log(cx); } }
Source:
public void cleanup() { START if(this.streamEstimator != null) { END this.streamEstimator.reset(); } } streamEstimator should never be null right?

Target:
public void cleanup() { this.streamEstimator.reset(); }
Source:
public Object exec(Tuple input) throws IOException { START if (input.size() == 0) END { throw new RuntimeException("Expected at least one parameter"); } for (Object o : input) { if (o != null) { return o; } } return null; } I think it should be: ``` java if (input == null || input.size() == 0) return null; ```

Target:
public Object exec(Tuple input) throws IOException { if (input == null || input.size() == 0) { return null; } for (Object o : input) { if (o != null) { return o; } } return null; }
Source:
public void shouldReturnNullForEmptyFilename() { S3FileMapper s3FileMapper = new S3FileMapper(mockFileBrowser, mockFileHelper); START S3File file = s3FileMapper.transform(null); END assertNull(file); } Since the test is for an empty filename I was expecting this to be `transform("")`?

Target:
public void shouldReturnNullForEmptyFilename() { S3FileMapper s3FileMapper = new S3FileMapper(mockFileBrowser, mockFileHelper); S3File file = s3FileMapper.transform(""); assertNull(file); }
Source:
public void helpBuildingEvent(EventBuilder eventBuilder) { eventBuilder.withSdkName(RavenEnvironment.SDK_NAME + ":android"); START String release = tags.get(VERSION_NAME_TAG_KEY); END if (!TextUtils.isEmpty(release)) { eventBuilder.withRelease(release); } for (String key : tags.keySet()) { eventBuilder.withTag(key, tags.get(key)); } } I was just wondering if perhaps it makes sense to include this in the `for` loop below instead i.e. `if (VERSION_NAME_TAG_KEY.equals()) {...}` One other issue is whether you want the version name to be included both in the release property and as a tag.

Target:
public void helpBuildingEvent(EventBuilder eventBuilder) { eventBuilder.withSdkName(RavenEnvironment.SDK_NAME + ":android"); for (String key : tags.keySet()) { String value = tags.get(key); if (VERSION_NAME_TAG_KEY.equals(key)) { eventBuilder.withRelease(value); } eventBuilder.withTag(key, value); } }
Source:
private boolean isRequestFiltered(@Nullable Integer orderBy) { return orderBy != null && (orderBy == Constants.ORDER_BY_DISTANCE || orderBy == Constants.ORDER_BY_DATE || orderBy == Constants.ORDER_BY_STATUS || orderBy == Constants.ORDER_BY_NAME); START return false; END } I guess this is never reached, right?

Target:
private boolean isRequestFiltered(@Nullable Integer orderBy) { return orderBy != null && (orderBy == Constants.ORDER_BY_DISTANCE || orderBy == Constants.ORDER_BY_DATE || orderBy == Constants.ORDER_BY_STATUS || orderBy == Constants.ORDER_BY_NAME); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiDataPoint that = (ApiDataPoint) o; START return id.equals(that.id); END } ha! this is a new construct for me. I thought `that.id` is a private field ...?

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiDataPoint that = (ApiDataPoint) o; return id.equals(that.getId()); }
Source:
public InternetDataConnection.InputStreamProvider forInput() throws IOException { START if (input != null) END throw new RuntimeException("Input has already been enabled"); if (connected) throw new RuntimeException("Cannot enable input after having already connected"); connection.setDoInput(true); input = new InternetDataConnection.InputStreamProvider(); return input; } It is not a good practice to leave the brackets even if there is only one line you should always have them. If someone else comes and adds another line it may produce a bug.

Target:
public InternetDataConnection.InputStreamProvider forInput() throws IOException { if (input != null) { throw new RuntimeException("Input has already been enabled"); } if (connected) { throw new RuntimeException("Cannot enable input after having already connected"); } connection.setDoInput(true); input = new InternetDataConnection.InputStreamProvider(); return input; }
Source:
public InternetDataConnection.OutputStreamProvider forOutput() throws IOException { START if (output != null) END throw new RuntimeException("Output has already been enabled"); if (connected) throw new RuntimeException("Cannot enable output after having already connected"); connection.setDoOutput(true); output = new InternetDataConnection.OutputStreamProvider(); return output; } Missing brackets

Target:
public InternetDataConnection.OutputStreamProvider forOutput() throws IOException { if (output != null) { throw new RuntimeException("Output has already been enabled"); } if (connected) { throw new RuntimeException("Cannot enable output after having already connected"); } connection.setDoOutput(true); output = new InternetDataConnection.OutputStreamProvider(); return output; }
Source:
public InternetDataConnection.BothStreams andInput() throws IOException { if (connected) START throw new RuntimeException("Cannot enable output after having already connected"); END return new InternetDataConnection.BothStreams(new InternetDataConnection.InputStreamProvider(), this); } Missing brackets

Target:
public InternetDataConnection.BothStreams andInput() throws IOException { if (connected) { throw new RuntimeException("Cannot enable output after having already connected"); } return new InternetDataConnection.BothStreams( new InternetDataConnection.InputStreamProvider(), this); }
Source:
public void stop(Throwable cause) throws Exception { START if (body != null) END body.cancel(cause); Run<?, ?> r = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); ThrottleJobProperty.DescriptorImpl descriptor = Jenkins.getActiveInstance().getDescriptorByType(ThrottleJobProperty.DescriptorImpl.class); descriptor.removeThrottledPipelineForCategory(r.getExternalizableId(), getCategory(), listener); } This method can be left blank—will not be called for a block-scoped step anyway, unless it is doing something between returning from `start` and the `BodyInvoker.start`.

Target:
public void stop(Throwable cause) throws Exception { }
Source:
START private Boolean isInMutualCategory(ThrottleJobProperty jobBeingChecked, ThrottleJobProperty executingJob) { END for (String category: jobBeingChecked.getCategories()) { if (executingJob.getCategories().contains(category)) { return true; } } return false; } should be `boolean`

Target:
private boolean isInMutualCategory(ThrottleJobProperty jobBeingChecked, ThrottleJobProperty executingJob) { if (jobBeingChecked != null && executingJob != null) { for (String category : jobBeingChecked.getCategories()) { if (executingJob.getCategories().contains(category)) { return true; } } } return false; }
Source:
private ThrottleJobProperty getThrottleJobProperty(Task task) { if (task instanceof Job) { Job<?,?> p = (Job<?,?>) task; if (task instanceof MatrixConfiguration) { START p = (Job<?,?>)((MatrixConfiguration)task).getParent(); END } ThrottleJobProperty tjp = p.getProperty(ThrottleJobProperty.class); return tjp; } return null; } BTW class cast to Job should not be required here

Target:
private ThrottleJobProperty getThrottleJobProperty(Task task) { if (task instanceof Job) { Job<?,?> p = (Job<?,?>) task; if (task instanceof MatrixConfiguration) { p = ((MatrixConfiguration)task).getParent(); } ThrottleJobProperty tjp = p.getProperty(ThrottleJobProperty.class); return tjp; } return null; }
Source:
START public ThrottleCategory(String categoryName, END Integer maxConcurrentPerNode, Integer maxConcurrentTotal, String blockingCategories, List<NodeLabeledPair> nodeLabeledPairs) { this.maxConcurrentPerNode = maxConcurrentPerNode == null ? 0 : maxConcurrentPerNode; this.maxConcurrentTotal = maxConcurrentTotal == null ? 0 : maxConcurrentTotal; this.categoryName = categoryName; this.blockingCategories = blockingCategories; this.nodeLabeledPairs = nodeLabeledPairs == null ? new ArrayList<NodeLabeledPair>() : nodeLabeledPairs; convertCategoriesToList(blockingCategories); } Please save the previous constructor as well. Otherwise the change affects the binary compatibility with previous versions

Target:
public ThrottleCategory(String categoryName, Integer maxConcurrentPerNode, Integer maxConcurrentTotal, String blockingCategories, List<NodeLabeledPair> nodeLabeledPairs) { this(categoryName, maxConcurrentPerNode, maxConcurrentTotal, nodeLabeledPairs); this.blockingCategories = blockingCategories; convertCategoriesToList(blockingCategories); }
Source:
public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { if (successMessage != null && !successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { if (failMessage != null && !failMessage.isEmpty()) { printError(failMessage); START } END } return success; }); } I don't think this needs changed? Definitely shouldn't need to add the null/isEmpty checks here, not sure about `MessagingUtil.sendStringToChat`

Target:
public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { // The success message can be cleared via flag if (!successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { printError(failMessage); } return success; }); }
Source:
public boolean canFlipToNextPage() { START if (selectedDataObservable.getValue() == null || selectedDataObservable.getValue() instanceof Document) { END return false; } return super.canFlipToNextPage(); } extract variable

Target:
public boolean canFlipToNextPage() { final Object data = selectedDataObservable.getValue(); if (data == null || data instanceof Document) { return false; } return super.canFlipToNextPage(); }
Source:
public boolean isPageComplete() { if (availableBusinessData.isEmpty() && dataTypeSelectionOptions.isBusinessDataTypeSelected()) { return false; } if (availableDocuments.isEmpty() && !dataTypeSelectionOptions.isBusinessDataTypeSelected()) { return false; START } END if (selectedDataObservable.getValue() instanceof BusinessObjectData) { return isNoBusinessDataSelected() ? false : super.isPageComplete(); } if (selectedDataObservable.getValue() instanceof Document) { return super.isPageComplete(); } return super.isPageComplete(); } <> if (availableBusinessData.isEmpty()) return false;

Target:
public boolean isPageComplete() { if (availableBusinessData.isEmpty() && isBusinessDataTypeSelected() || availableDocuments.isEmpty() && !isBusinessDataTypeSelected()) { return false; } if (selectedDataObservable.getValue() instanceof BusinessObjectData) { return isNoBusinessDataSelected() ? false : super.isPageComplete(); } if (selectedDataObservable.getValue() instanceof Document) { return super.isPageComplete(); } return super.isPageComplete(); }
Source:
public void updateButtons() { super.updateButtons(); final Button nextButton = getButton(IDialogConstants.NEXT_ID); if (getCurrentPage() instanceof CreateContractInputFromBusinessObjectWizardPage) { START final CreateContractInputFromBusinessObjectWizardPage page = (CreateContractInputFromBusinessObjectWizardPage) getCurrentPage(); END nextButton.setText(Messages.preview); } else { nextButton.setText(IDialogConstants.NEXT_LABEL); } } page variable is not used.

Target:
public void updateButtons() { super.updateButtons(); final Button nextButton = getButton(IDialogConstants.NEXT_ID); if (getCurrentPage() instanceof CreateContractInputFromBusinessObjectWizardPage) { nextButton.setText(Messages.preview); } else { nextButton.setText(IDialogConstants.NEXT_LABEL); } }
Source:
private JarPackageData configureJar(final ICompilationUnit[] compilationUnits) { final JarPackageData jarPackakeData = newJarPackageData(); jarPackakeData.setJarLocation(Path.fromOSString(toFile.getAbsolutePath())); jarPackakeData.setElements(compilationUnits); jarPackakeData.setDeprecationAware(true); jarPackakeData.setExportJavaFiles(includeSources); jarPackakeData.setOverwrite(true); START jarPackakeData.setExportErrors(false); END return jarPackakeData; } It will have some side effects on connectors. (When sources does not compile.)

Target:
private JarPackageData configureJar(final ICompilationUnit[] compilationUnits) { final JarPackageData jarPackakeData = newJarPackageData(); jarPackakeData.setJarLocation(Path.fromOSString(toFile.getAbsolutePath())); jarPackakeData.setElements(compilationUnits); jarPackakeData.setDeprecationAware(true); jarPackakeData.setExportJavaFiles(includeSources); jarPackakeData.setOverwrite(true); return jarPackakeData; }
Source:
public String getText(final Object element) { if (element instanceof FieldToContractInputMapping) { final FieldToContractInputMapping mapping = (FieldToContractInputMapping) element; START return new Boolean(!mapping.getField().isNullable()).toString(); END } return super.getText(element); } Boolean.valueOf to avoid object instanciation

Target:
public String getText(final Object element) { if (element instanceof FieldToContractInputMapping) { final FieldToContractInputMapping mapping = (FieldToContractInputMapping) element; return Boolean.valueOf(!mapping.getField().isNullable()).toString(); } return super.getText(element); }
Source:
protected boolean isBonitaGroovyBasedValidator(final Instance validator) { final String className = validator.get("validatorClass"); START final boolean isBonitaGroovyBasedValidator = className != null END && (className.contains("GroovyPageValidator") || className.contains("GroovyFieldValidator")); return isBonitaGroovyBasedValidator; } return className != null && (className.contains("GroovyPageValidator") || className.contains("GroovyFieldValidator"));

Target:
protected boolean isBonitaGroovyBasedValidator(final Instance validator) { final String className = validator.get("validatorClass"); return className != null && (className.contains("GroovyPageValidator") || className.contains("GroovyFieldValidator")); }
Source:
START private static IEclipseContext headlessContext() { END if (HEADLESS_CONTEXT == null) { HEADLESS_CONTEXT = EclipseContextFactory.create("headlessContext"); } return HEADLESS_CONTEXT; } shouldn't it be synchronized? (SIngleton)

Target:
private static synchronized IEclipseContext headlessContext() { if (HEADLESS_CONTEXT == null) { HEADLESS_CONTEXT = EclipseContextFactory.create("headlessContext"); } return HEADLESS_CONTEXT; }
Source:
public OutputMappingBuilder setProcessTarget(final Data data) { START outputMapping.setProcessTarget(data);; END return this; } 2 columns

Target:
public OutputMappingBuilder setProcessTarget(final Data data) { outputMapping.setProcessTarget(data); return this; }
Source:
public void update() { if (toolItem != null) { START toolItem.setEnabled(canCreateNewForm() || canEditForm()); END final PageFlow pageFlow = unwrap(selectionProvider.getSelection()); if (pageFlow != null) { if (pageFlow instanceof Pool) { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.pool)); } else { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.task)); } } } } I think the button is always enabled. Either no form is defined -> new form A form is defined -> open form

Target:
public void update() { if (toolItem != null) { toolItem.setEnabled(true); final PageFlow pageFlow = unwrap(selectionProvider.getSelection()); if (pageFlow != null) { if (pageFlow instanceof Pool) { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.pool)); } else { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.task)); } } } }
Source:
public void should_fail_if_neither_name_nor_version_is_changed() throws Exception { final MustUpdateValidator mustUpdateValidator = new MustUpdateValidator(aPool().withName("Pool").withVersion("1.0").build(), new WritableValue("Pool", START String.class), new WritableValue("1.0", END String.class)); final IStatus status = mustUpdateValidator.validate(); StatusAssert.assertThat(status).isNotOK(); } the linebreak place is not the best choice

Target:
public void should_fail_if_neither_name_nor_version_is_changed() throws Exception { final MustUpdateValidator mustUpdateValidator = new MustUpdateValidator(aPool().withName("Pool").withVersion("1.0").build(), new WritableValue("Pool", String.class), new WritableValue("1.0", String.class)); final IStatus status = mustUpdateValidator.validate(); assertThat(status).isNotOK(); }
Source:
protected void validationStatusChanged(final IStatus status) { updateTextEditorFeedback(status); messageManager.removeAllMessages(); if (!status.isOK() && getViewer().isCellEditorActive()) { START messageManager.addMessage("", status.getMessage(), null, new StatusToMessageSeverity(status).toMessageSeverity()); END } } Why using empty string as first argument?

Target:
protected void validationStatusChanged(final IStatus status) { updateTextEditorFeedback(status); messageManager.removeAllMessages(); if (!status.isOK() && getViewer().isCellEditorActive()) { messageManager.addMessage(null, status.getMessage(), null, new StatusToMessageSeverity(status).toMessageSeverity()); } }
Source:
START protected boolean isConnectorIsOnPool(final Connector connector) { END if (connector.eContainer() instanceof Pool) { return true; } return false; } why not directly return connector.eContainer() instanceof Pool; ?

Target:
protected boolean isConnectorIsOnPool(final Connector connector) { return connector.eContainer() instanceof Pool; }
Source:
public void should_failed_when_event_isNot_ON_ENTER_Or_ON_FINISH(){ START ConnectorEventFilter failFilter = new ConnectorEventFilter("a"); END } left operand is useless

Target:
public void should_failed_when_event_isNot_ON_ENTER_Or_ON_FINISH() { new ConnectorEventFilter("a"); }
Source:
public void init() { // Check things are going to work. try { START log.info("Search using solr on: "+ getSolrUrl()); END } catch (IllegalStateException e) { log.error(e.getMessage()); } } It would probably be better to have a clear separation between the call to `getSolrUrl()` and the creation of a log.

Target:
public void init() { // Check things are going to work. try { String url = getSolrUrl(); log.info("Search using solr on: "+ url); } catch (IllegalStateException e) { log.error(e.getMessage()); } }
Source:
public void init() { solrUrl = serverConfigurationService.getString("ses.solr.server", null); solrServer = new ConcurrentUpdateSolrServer(solrUrl, 1000, 1); START Integer.parseInt(serverConfigurationService.getString("recent.days", "14")); END } This doesn't do anything.

Target:
public void init() { solrUrl = serverConfigurationService.getString("ses.solr.server", null); solrServer = new ConcurrentUpdateSolrServer(solrUrl, 1000, 1); }
Source:
public void deleteAll() { try { START String query = new String("*:*"); END solrServer.deleteByQuery(query); } catch (SolrServerException e) { log.error(e.getLocalizedMessage(), e); } catch (IOException e) { log.error(e.getLocalizedMessage(), e); } } new String() is redundant.

Target:
public void deleteAll() { try { String query = "*:*"; solrServer.deleteByQuery(query); } catch (SolrServerException e) { log.error(e.getLocalizedMessage(), e); } catch (IOException e) { log.error(e.getLocalizedMessage(), e); } }
Source:
public void write(OutputStream out) { try { IOUtils.copy(results.getInputStream(), out); START results.disconnect(); END } catch (IOException e) { throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE).entity("Service Unavailable, IO Exception with Search Engine").build()); } } I think the results.disconnect() should be in a finally block as you always want to release the connection back.

Target:
public void write(OutputStream out) { try { IOUtils.copy(results.getInputStream(), out); } catch (IOException e) { throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE).entity("Service Unavailable, IO Exception with Search Engine").build()); } finally { results.disconnect(); } }