auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testUnmarshallSubprocessLevelEventFilledProperties() throws Exception { final String EVENT_NAME = "It is also not empty ~`!@#$%^&*()_+=-{}|\\][:\";'?><,./"; final String EVENT_DOCUMENTATION = "Some documentation as well\n~`!@#$%^&*()_+=-{}|\\][:\";'?><,./\n"; Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartNoneEvent filledSubprocess = getStartNodeById(diagram, FILLED_SUBPROCESS_LEVEL_EVENT_ID, StartNoneEvent.class); assertGeneralSet(filledSubprocess.getGeneral(), EVENT_NAME, EVENT_DOCUMENTATION); assertStartEventSlaDueDate(filledSubprocess.getExecutionSet(), SLA_DUE_DATE); }

Target:
Missing assertNotNull for executionSet here.
Source:
public DataTypeListItem getItem() { return this.item; }

Target:
Just for consistency, we do not need the keyword `this` here, see the getter of `isEditModeEnabled`.
Source:
private List<ItemDefinition> setItemDefinitionsNamespace(final List<ItemDefinition> itemDefinitions, final String namespace) { return itemDefinitions .stream() .peek(itemDefinition -> setItemDefinitionNamespace(itemDefinition, namespace)) .collect(Collectors.toList()); }

Target:
Reading [this](https://stackoverflow.com/a/44371170) I think we should use `map` instead of `peek` , however I may miss something.
Source:
private void setItemDefinitionNamespace(final ItemDefinition itemDefinition, final String namespace) { final String nameWithNamespace = namespace + "." + itemDefinition.getName(); final List<ItemDefinition> itemComponents = itemDefinition.getItemComponent(); if (itemDefinition.getTypeRef() != null && !isBuiltInType(itemDefinition.getTypeRef())) { itemDefinition.setTypeRef(makeQNameWithNamespace(itemDefinition.getTypeRef(), namespace)); } itemDefinition.setName(nameWithNamespace); setItemDefinitionsNamespace(itemComponents, namespace); }

Target:
Is `namespace` always non empty? Is this why you asked on chat if you can assume it?
Source:
wbFromDMN(final String description) { if (description == null) { return new Description(""); } else { return new Description(description); } }

Target:
Please restore the original formatting.
Source:
public void setAbsoluteBounds(Node<? extends View, ?> node) { Object definition = node.getContent().getDefinition(); setBounds(absoluteBounds(node)); if (definition instanceof BaseAdHocSubprocess || definition instanceof EventSubprocess || definition instanceof EmbeddedSubprocess) { shape.setIsExpanded(true); } }

Target:
This `if` condition could be placed `SubProcessPropertyWriter` overriding this method. Since this is specific to subprocesses. Makes sense?
Source:
public static Node<View, Edge> getDockSourceNode(final Node<? extends View, ?> node) { return (Node<View, Edge>) node .getInEdges() .stream() .filter(PropertyWriterUtils::isDockEdge) .map(Edge::getSourceNode) .findFirst() .orElse(null); }

Target:
why not returning the` Optional<Node> `?
Source:
public void testEqualsId() { import1.setId(new Id("123")); import2.setId(new Id("123")); assertEquals(import1, import2); }

Target:
You don't need to set the `Id` here as it's done in the `setup()` method (but does no harm and makes the test clearer!)
Source:
void onCommandUndoExecuted(final @Observes CanvasCommandUndoneEvent commandUndoExecutedEvent) { CanvasHandler canvasHandler = commandUndoExecutedEvent.getCanvasHandler(); if (getSession().getCanvasHandler().equals(canvasHandler)) { checkNotNull("commandUndoExecutedEvent", commandUndoExecutedEvent); if (null != commandUndoExecutedEvent.getCommand()) { redoCommandHandler.onUndoCommandExecuted(commandUndoExecutedEvent.getCommand()); } checkState(); } }

Target:
This check is pointless, as the NPE would have been thrown on L#120
Source:
void init() { dragArea.onmousedown = this::onDragAreaMouseDown; dragArea.onmouseup = this::onDragAreaMouseUp; dragArea.onmousemove = this::onDragAreaMouseMove; }

Target:
I think this method could be `private`: ```suggestion private void init() { ```
Source:
public static <TYPE> Collection<ScanResult<TYPE>> scan(IOService ioService, Path rootPath, Collection<String> extensions, Function<InputStream, TYPE> converter) { return scan(ioService, rootPath, extensions, converter, resouce -> true); }

Target:
Typo, `resource -> true` (you have `resouce`)
Source:
String toDMNString(final String years, final String months) { final YearsMonthsValue value = new YearsMonthsValue(); value.setYears(years); value.setMonths(months); return toDMNString(value); }

Target:
I think `fromDMNString` and `toDMNString` can be public as they are the main feature of this class, or do I miss something?
Source:
String toDisplayValue(final String dmnValue) { final YearsMonthsValue yearsMonthsValue = fromDMNString(dmnValue); return toDisplayValue(yearsMonthsValue); }

Target:
Maybe also this could be public and rest could be private?
Source:
public static boolean isTypeOf(Class<?> type, Object instance) { return instance.getClass().isAssignableFrom(type); }

Target:
I'm fine on doing this on all server side classes, but in this case for `ClassUtils`, which is inside `core-common` module, it's not correct, because that class is also visible to the GWT compiler, and as far as I know it does not emulate the `isAssignableFrom` method from JRE... That's the reason I remember to do the comparison via classname, which the method is emulated and so we can always compare on js two strings... but feel free to test it guys, if I'm wrong lemme know and I'm agree on this change.
Source:
String toDisplay(final String rawValue) { if (StringUtils.isEmpty(rawValue)) { return ""; } final String dateString = removePrefixAndSuffix(rawValue); try { final java.util.Date date = RAW_FORMAT.parse(dateString); return DISPLAY_FORMAT.format(date); } catch (final IllegalArgumentException exception) { return ""; } }

Target:
Could we please add `java.util.Date ` to imports and use declare variable just like `final Date date = RAW_FORMAT.parse(dateString);`
Source:
private static void mockAdapterRegistry(BackendDefinitionAdapter definitionAdapter, BackendDefinitionSetAdapter definitionSetAdapter, BackendPropertySetAdapter propertySetAdapter, BackendPropertyAdapter propertyAdapter) { when(adapterRegistry.getDefinitionSetAdapter(any(Class.class))).thenReturn(definitionSetAdapter); when(adapterRegistry.getDefinitionAdapter(any(Class.class))).thenReturn(definitionAdapter); when(adapterRegistry.getPropertySetAdapter(any(Class.class))).thenReturn(propertySetAdapter); when(adapterRegistry.getPropertyAdapter(any(Class.class))).thenReturn(propertyAdapter); }

Target:
Do the methods need to be static?
Source:
public void testGetDiagram(){ final CanvasHandler handler = mock(CanvasHandler.class); doNothing().when(presenter).refreshTreeView(); final Diagram expectedDiagram = mock(Diagram.class); doReturn(expectedDiagram).when(handler).getDiagram(); presenter.setHandler(handler); final Diagram actual = presenter.getDiagram(); assertEquals(expectedDiagram, actual); }

Target:
I think there's a format issue here: ```suggestion public void testGetDiagram() { ```
Source:
public UpdateCanvasControlPointPositionCommand(final Edge edge, final ControlPoint[] controlPoints) { this.edge = edge; this.controlPoints = controlPoints; // Actual control points must be cloned at this point, before execution. oldControlPoints = Stream.of(getControlPoints(edge)) .map(ControlPoint::copy) .toArray(ControlPoint[]::new); ; }

Target:
unnecessary **;**
Source:
public void setup() { this.literalExpression = spy(new LiteralExpression()); }

Target:
Do we need `spy` in this case?
Source:
public void disableOkButton() { modal.disableOkButton(); }

Target:
I think this could be `package-private`: ```suggestion void disableOkButton() { ```
Source:
public void testInit() { final DataTypeConstraintRangeView mocked = mock(DataTypeConstraintRangeView.class); doCallRealMethod().when(mocked).init(any()); mocked.init(presenter); verify(mocked).setupInputFields(); }

Target:
We can change the `setup` method to this: ```java @Before public void setup() { view = spy(new DataTypeConstraintRangeView(startValue, endValue, includeStartValue, includeEndValue)); } ``` ..to simplify this method to this: ```java @Test public void testInit() { view.init(presenter); verify(view).setupInputFields(); } ```
Source:
public void setup() { final QName key = new QName(DMNModelInstrumentedBase.Namespace.KIE.getUri(), ConstraintType.CONSTRAINT_KEY, DMNModelInstrumentedBase.Namespace.KIE.getPrefix()); when(dmnUnary.getId()).thenReturn(ID); when(dmnUnary.getAdditionalAttributes()).thenReturn(additionalAttributes); when(dmnUnary.getText()).thenReturn(TEXT); when(additionalAttributes.getOrDefault(key, "")).thenReturn(CONSTRAINT_TYPE_TEXT); }

Target:
```java @RunWith(MockitoJUnitRunner.class) public class InputClauseUnaryTestsPropertyConverterTest { private static final String ID = "thisId"; private static final String TEXT = "1,2,3"; private static final QName key = new QName(DMNModelInstrumentedBase.Namespace.KIE.getUri(), ConstraintType.CONSTRAINT_KEY, DMNModelInstrumentedBase.Namespace.KIE.getPrefix()); @Mock private org.kie.dmn.model.api.UnaryTests dmnUnary; @Mock private Map<QName, String> additionalAttributes; @Before public void setup() { when(dmnUnary.getId()).thenReturn(ID); when(dmnUnary.getAdditionalAttributes()).thenReturn(additionalAttributes); when(dmnUnary.getText()).thenReturn(TEXT); } @Test public void testWbFromDMNEnumeration() { testWbFromDMN(ConstraintType.ENUMERATION); } @Test public void testWbFromDMNExpression() { testWbFromDMN(ConstraintType.EXPRESSION); } @Test public void testWbFromDMNRange() { testWbFromDMN(ConstraintType.RANGE); } private void testWbFromDMN(final ConstraintType constraintType) { when(additionalAttributes.getOrDefault(key, "")).thenReturn(constraintType.name().toLowerCase()); final InputClauseUnaryTests inputClause = InputClauseUnaryTestsPropertyConverter.wbFromDMN(dmnUnary); assertEquals(inputClause.getConstraintType(), constraintType); assertEquals(inputClause.getId().getValue(), ID); assertEquals(inputClause.getText().getValue(), TEXT); } } ```
Source:
void load(final String type, final String value, final ConstraintType constraintType) { this.constraintValue = value; if (!Objects.isNull(value) && !value.isEmpty() && constraintType == null) { this.constraintType = inferComponentType(value); } else { this.constraintType = constraintType; } prepareView(type, value, constraintType); }

Target:
We can shorten this condition: ```java (StringUtils.nonEmpty(value) && constraintType == null) ``` FQN for `StringUtils` is `org.kie.workbench.common.stunner.core.util.StringUtils`
Source:
void onSelectChange(final JQuerySelectPickerEvent event) { final String constraintType = event.target.value; if (!isEmpty(constraintType)) { ConstraintType constraint = ConstraintType.fromString(constraintType); loadComponent(constraint); presenter.setConstraintType(constraint); } }

Target:
I would add a `final` here: ```suggestion final ConstraintType constraint = ConstraintType.fromString(constraintType); ```
Source:
public void setUp() throws Exception { super.setUp(); when(canvasPanel.getLocationConstraints()).thenReturn(PANEL_BOUNDS); when(candidate.getContent()).thenReturn(new ViewImpl<>(mock(Object.class), ELEMENT_BOUNDS)); ; }

Target:
Useless semicolon.
Source:
private String parseFunctionClose() throws ParseException { int index = nextNonBlank(); if (index < 0 || expression.charAt(index) != ')') { throw new ParseException(errorMessage(FUNCTION_CALL_NOT_CLOSED_PROPERLY_ERROR, functionName), parseIndex); } setParseIndex(index + 1); return ")"; }

Target:
Return value of the method is never used.
Source:
private String parseParamDelimiter() throws ParseException { int index = nextNonBlank(); if (index < 0 || expression.charAt(index) != ',') { throw new ParseException(errorMessage(PARAMETER_DELIMITER_EXPECTED_ERROR), parseIndex); } setParseIndex(index + 1); return ","; }

Target:
Return value of the method is never used.
Source:
public void testUnaryFunctionsParsingUnsuccessful() throws Exception { for (String function : unaryFunctions) { testFunctionParsingUnsuccessful(function, failingUnaryFunctionExpressions); } }

Target:
Exception is never thrown in the method.
Source:
ParamDef mockParamDef(String name, String type) { ParamDef paramDef = mock(ParamDef.class); when(paramDef.getName()).thenReturn(name); when(paramDef.getType()).thenReturn(type); return paramDef; }

Target:
This method can be private.
Source:
ConditionParamPresenter mockParamPresenter() { ConditionParamPresenter paramPresenter = mock(ConditionParamPresenter.class); ConditionParamPresenter.View paramPresenterView = mock(ConditionParamPresenter.View.class); HTMLElement element = mock(HTMLElement.class); when(paramPresenter.getView()).thenReturn(paramPresenterView); when(paramPresenterView.getElement()).thenReturn(element); return paramPresenter; }

Target:
This method can be private.
Source:
public void onOrganizationalUnitRemoved(@Observes final AfterDeleteOrganizationalUnitEvent removedOrganizationalUnitEvent) { if (isLibraryPerspectiveOpen() && isSpaceActive(removedOrganizationalUnitEvent)) { projectContext.getActiveOrganizationalUnit() .filter(active -> active.equals(removedOrganizationalUnitEvent.getOrganizationalUnit())) .ifPresent(active -> goToOrganizationalUnits()); } }

Target:
I'm wondering why we even need the method `isSpaceActive` and this additional check `&& isSpaceActive(removedOrganizationalUnitEvent)` when it's doing similar check as the `.filter(active -> active.equals(removedOrganizationalUnitEvent.getOrganizationalUnit()))` below. Can it happen that you can have 2 different OrganizationalUnits that are equal but don't have the same identifier? I think we should remove the newly added private isSpaceActive and remove that && check and it will behave the same.
Source:
public void setup() throws Exception { profileInstances = spy(new MockInstanceImpl<>(profile1, profile2)); tested = new BackendProfileManager(definitionUtils, profileInstances); }

Target:
Method doesn't throw an exception.
Source:
public void setup() throws Exception { profileInstances = spy(new ManagedInstanceStub<Profile>(profile1, profile2)); tested = new ClientProfileManager(definitionUtils, profileInstances); }

Target:
Explicit type argument Profile can be replaced with <>.
Source:
public void save(String id) { context.saveStyle(); HashMap<String, String> map = new HashMap<>(); //setting the node id in case it exists on graph Optional.ofNullable(id).ifPresent(node -> map.put(DEFAULT_NODE_ID, id)); context.addAttributes(map); }

Target:
Dtto.
Source:
public ErrorsAndDMNModelAsSerialized(List<Message> messages, Definitions definitions) { super(); this.messages = Collections.unmodifiableList(messages); this.definitions = definitions; }

Target:
We don't really need a call to `super()`
Source:
public void testSetVisibleSizeAndRefresh() { uiModel.setVisibleSizeAndRefresh(0, 0); verify(delegate).setVisibleSizeAndRefresh(eq(0), eq(0)); }

Target:
IMO it's better to use different values, e.g. `0` and `1` to be sure, for example, that the "delegated" method is not simply using the first parameter twice...
Source:
public Optional<?> getProperty(T pojo, String propertyName) { return ReflectionAdapterUtils.getFields(pojo.getClass()).stream() .filter(f -> Objects.equals(propertyName, f.getName())) .map(field -> Exceptions.swallow(() -> field.get(pojo), null)) .findFirst(); }

Target:
Could we please use `field` instead of `f` to be consistent with line below?
Source:
private Optional<String> getGraphUUID() { final Diagram diagram = getDiagram(); if (Objects.isNull(diagram)) { return Optional.empty(); } final Graph graph = diagram.getGraph(); if (Objects.isNull(graph)) { return Optional.empty(); } return Optional.of(graph.getUUID()); }

Target:
I think we could simplify this method with something like this: ```java private Optional<String> getGraphUUID() { if (Objects.isNull(getDiagram()) || Objects.isNull(getGraph())) { return Optional.empty(); } return Optional.of(getGraph().getUUID()); } ``` ..but feel free to keep it as is :-)
Source:
public BPMNShapeFactory(final BasicShapesFactory basicShapesFactory, final SVGShapeFactory svgShapeFactory, final DelegateShapeFactory<BPMNDefinition, Shape> delegateShapeFactory, final ManagedInstance<WorkItemDefinitionRegistry> workItemDefinitionRegistry, final DefinitionUtils definitionUtils, final StunnerPreferencesRegistries preferencesRegistries) { this.basicShapesFactory = basicShapesFactory; this.svgShapeFactory = svgShapeFactory; this.delegateShapeFactory = delegateShapeFactory; this.workItemDefinitionRegistry = () -> workItemDefinitionRegistry.get(); this.definitionUtils = definitionUtils; this.preferencesRegistries = preferencesRegistries; }

Target:
Not sure, why you replaced it, I prefer as it was, but it is matter of taste, so no needs to revert.
Source:
public void setup() throws Exception { CanvasCommandManagerImpl commandManager = new CanvasCommandManagerImpl(); when(canvasHandler.getCanvas()).thenReturn(canvas); when(clientSessionManager.getCurrentSession()).thenReturn(editorSession); when(editorSession.getCanvasHandler()).thenReturn(canvasHandler); when(editorSession.getCommandRegistry()).thenReturn(commandRegistry); when(editorSession.getCommandManager()).thenReturn(commandManager); this.tested = new RequestCommandManager(clientSessionManager, commandRegisteredEvent); }

Target:
it is missing the `verify` of the commandRegisteredEvent fire on the tests. You can use the `EventSourceMock` to mock the event.
Source:
public void setVirtual(final boolean virtual) { this.isVirtual = virtual; }

Target:
I think this method could be private.
Source:
public double getMedian() { return median; }

Target:
I think this method could be private.
Source:
HTMLOptGroupElement makeOptionGroup(final String groupTitle, final List<DataType> dataTypes, final Function<DataType, String> dataTypeConsumer) { final HTMLOptGroupElement optionGroup = makeHTMLOptGroupElement(); optionGroup.label = groupTitle; dataTypes.stream() .sorted(DATA_TYPE_COMPARATOR) .forEach(dataType -> { final HTMLOptionElement option = makeOption(dataType, dataTypeConsumer); optionGroup.appendChild(option); }); return optionGroup; }

Target:
Here we're ordering the data types by `DataType::getName`, however, take a look here: https://github.com/kiegroup/kie-wb-common/blob/0bb304e4805cabd3879c31d154add5a7ac486d75/kie-wb-common-dmn/kie-wb-common-dmn-client/src/main/java/org/kie/workbench/common/dmn/client/editors/types/listview/DataTypeSelectView.java#L102 ..we're using the `DataType::getType` function for default data types. So, I think they are not being correctly ordered.
Source:
private boolean isNotCyclicEdge(final Edge edge) { final String sourceId = edge.getSourceNode() != null ? edge.getSourceNode().getUUID() : null; final String targetId = edge.getTargetNode() != null ? edge.getTargetNode().getUUID() : null; return !Objects.equals(sourceId, targetId); }

Target:
it can be `static`
Source:
private Lane getLaneNodeById(Diagram<Graph, Metadata> diagram, String id) { Node<? extends Definition, ?> node = getNodebyId(diagram, id); return Lane.class.cast(node.getContent().getDefinition()); }

Target:
I guess `return (Lane) node.getContent().getDefinition();` will be more clear here.
Source:
public List<DataType> all() { return new ArrayList<>(dataTypes.values()); }

Target:
as the `all()` is used just internally I think we can rewrite it as: ```java public Collection<DataType> all() { return dataTypes.values(); } ```
Source:
public static String getCaseFileVariableName(Property p) { String name = p.getName(); // legacy uses ID instead of name return name == null ? p.getId() : name; }

Target:
this could be private, or is it used on other classes?
Source:
public WorkspaceCompilationInfo(Path prjPath, Properties bannedEnvVars) { this.prjPath = prjPath; }

Target:
why the bannedEnvVars, looks left over
Source:
public void setup(final String headerKey, final String labelKey) { getView().setHeader(translationService.format(headerKey)); getView().setLabel(translationService.format(labelKey)); superSetup(); }

Target:
same here, use _setup_
Source:
private static void write(String filename, String content) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write(content); writer.close(); }

Target:
Please use try-with-resources
Source:
public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, final String requestUUID) { this.successful = successful; if(mavenOutput != null) { this.mavenOutput = new ArrayList<>(mavenOutput); }else{ this.mavenOutput = Collections.emptyList(); } this.workingDir = workingDir; this.requestUUID = requestUUID; }

Target:
This constructor should really be calling the more featureful constructor for consistency and to avoid duplication. Something like this: ``` this(successful, mavenOutput, workingDir, Collections.emptyList(), Collections.emptyList(), requestUUID); ```
Source:
public static void setup() { gitDaemonEnabled = System.getProperty("org.uberfire.nio.git.daemon.enabled"); gitSshEnabled = System.getProperty("org.uberfire.nio.git.ssh.enabled"); System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); }

Target:
One more unnecessary "save and restore" of system property value. Please remove it to be consistent in the entire test suite and use `clearProperty` below.
Source:
private <T> List<T> nullToEmpty(List<T> list) { if (list == null) { return Collections.emptyList(); } else { return new ArrayList<>(list); } }

Target:
please remove else, code will be more readable
Source:
private Path getWorkingDir(String workingDir){ if(workingDir!= null){ return Paths.get("file://"+workingDir); } else{ return null; } }

Target:
please remove else, code will be more readable; also follow KIE code style
Source:
public void updateEnhanced(final EnhancedDependency enhancedDependency) { if (this.enhancedDependencies.contains(enhancedDependency)) { this.enhancedDependencies.update(enhancedDependency); } else { this.enhancedDependencies.add(enhancedDependency); } }

Target:
Doesn't seem like this change is needed.
Source:
private ControlPointControlImpl.StunnerControlPointsAcceptor createStunnerControlPointsAcceptor(ControlPointControl controlPointControl) { Function<String, Edge> connectorSupplier = uuid -> uuid.equals(EDGE_UUID) ? edge : null; ; return new ControlPointControlImpl.StunnerControlPointsAcceptor(controlPointControl, connectorSupplier); }

Target:
useless comma.
Source:
public CommandResult<CanvasViolation> execute(AbstractCanvasHandler context) { ShapeUtils.removeControlPoints(candidate, context, controlPoints); ShapeUtils.hideControlPoints(candidate, context); ShapeUtils.showControlPoints(candidate, context); return buildResult(); }

Target:
hide is after remove, doesn't it inverted?
Source:
public static List<URL> readAllDepsAsUrls(List<String> prjDeps) { List<URL> deps = new ArrayList<>(); for(String dep:prjDeps){ try { deps.add(new URL(dep)); }catch (MalformedURLException e){ logger.error(e.getMessage()); } } if(deps.size()>0) { return deps; }else{ return Collections.emptyList(); } }

Target:
This if-else is redundand. Please replace it with just `return deps;` If no deps are added in the for loop, the deps will be empty ;) The same in the method below.
Source:
public void buildAndSkipDepsNonExistentProject() throws Exception{ AFCompilerService service = new DefaultKieCompilerService(); CompletableFuture<KieCompilationResponse> futureRes = service.build(tmpRoot, mavenRepo.toString(), Boolean.FALSE); KieCompilationResponse res = futureRes.get(); assertThat(res.isSuccessful()).isFalse(); assertThat(res.getDependencies().isEmpty()).isTrue(); assertThat(res.getDependencies().size()).isEqualTo(0); }

Target:
Please replace `.size()).isEqualTo(` with `.hasSize(` 16x in this PR: Ctrl+f `.size()).isEqualTo(`
Source:
public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, final List<String> targetContent, final List<String> projectDependencies) { this.successful = successful; this.mavenOutput = mavenOutput; this.workingDir = workingDir; this.targetContent = targetContent; this.projectDependencies = projectDependencies; }

Target:
lists shouldn't be copied, best copy them; ```java this.targetContent = new ArrayList<>(targetContent); ``` as if anyone still holds access to the parameter list, it can modify it
Source:
public int hashCode() { return HashUtil.combineHashCodes(Objects.hashCode(getClass().getName()), Objects.hashCode(general), Objects.hashCode(backgroundSet), Objects.hashCode(fontSet), Objects.hashCode(dimensionsSet), Objects.hashCode(labels)); }

Target:
what about just `getClass()` instead of `getClass().getName()`? Applies for all bellow...
Source:
public Package getSelectedPackage() { if (packages.size() == 0) { return null; } return packages.get(selectedPackage); }

Target:
Optional nitpick: `packages.isEmpty()`
Source:
public Optional<DecisionTable> getModelClass() { final DecisionTable dtable = new DecisionTable(); return Optional.of(dtable); }

Target:
We could shorten now to `return Optional.of(new DecisionTable());`
Source:
public Optional<Context> getModelClass() { final Context context = new Context(); return Optional.of(context); }

Target:
We could shorten to one line `return Optional.of(new Context());`
Source:
public Set<String> getDefinitions(final String label) { final Set<String> ids = definitionsByLabel.get(label); if (null == ids) { return Collections.emptySet(); } return ids; }

Target:
Can be shortened to one line, but take this more as question, if it would be of better performance: ```java return Optional.ofNullable(definitionsByLabel.get(label)).orElse(Collections.emptySet()); ```
Source:
public void setKSessions(final List<String> ksessions) { String[] names = ksessions.toArray(new String[ksessions.size()]); ksessionSelect.setup(ksessionSelectContainer, buildOptions(names), names[0], new Consumer<String>() { @Override public void accept(String s) { onSelectionChange(); } }); }

Target:
Also this consumer could be simplified by lambda but leaving decision to you. `selectedKieSession -> onSelectionChange()`
Source:
private void setItemEnabled(final Class<? extends ClientSessionCommand> type, final boolean enabled) { menuItems.get(type).setEnabled(enabled); }

Target:
This parameter value of private method is always `False`
Source:
private boolean jsonExists(String path){ File test = new File(path + "/" + JSON_POM_FILE); return test.exists() && test.isFile(); }

Target:
It would be nice to provide some feedback if this check fails. Like "The file BLABLA doesn't exist in the directory you provided. Please try again..."
Source:
private boolean jsonExists(String path) { File test = new File(path + File.separator + JSON_POM_FILE); return test.exists() && test.isFile(); }

Target:
Don't worry about changing this, but just FYI there is a constructor on `File` that takes a parent and child path and concatenates them together. It's nice because then you don't have to worry about using `File.separator` and concatenating the path yourself.
Source:
public void testInitAggregator() throws Exception { final List<BuiltinAggregator> aggregators = Arrays.asList(BuiltinAggregator.COUNT, BuiltinAggregator.MAX, BuiltinAggregator.MIN, BuiltinAggregator.SUM); testedView.initBuiltinAggregators(aggregators); aggregators.stream().forEach(agg -> verify(lstBuiltinAggregator).addOption(agg.value())); }

Target:
Out of interest why can you not do ```BuiltinAggregator.values()```?
Source:
public void testInitOrientations() throws Exception { final List<DecisionTableOrientation> orientations = Arrays.asList(DecisionTableOrientation.CROSS_TABLE, DecisionTableOrientation.RULE_AS_COLUMN, DecisionTableOrientation.RULE_AS_ROW); testedView.initDecisionTableOrientations(orientations); orientations.stream().forEach(orientation -> verify(lstDecisionTableOrientation).addOption(orientation.value())); }

Target:
Out of interest why can you not do ```DecisionTableOrientation.values()```?
Source:
public boolean isSupported(String feature) { throwException(); return true; }

Target:
This is redundant line now.
Source:
public void init() { paletteDefinitionBuilder .itemFilter(defId -> true) .categoryFilter(category -> !EXCLUDED_CATEGORIES.contains(category)); }

Target:
Looking on `AbstractPaletteDefinitionBuilder#initDefaults` I think this line can be omitted.
Source:
static <T, U> Function<T, Result<U>> ignored(Class<?> expectedClass) { return t -> Result.ignored( "Ignored: " + Optional.ofNullable(t) .map(o -> o.getClass().getCanonicalName()) .orElse("null -- expected " + expectedClass.getCanonicalName())); }

Target:
Can be private method.
Source:
public static AssociationList fromString(String encoded) { if (encoded.isEmpty()) return new AssociationList(); else return new AssociationList( Arrays.asList(encoded.split(",")).stream() .map(AssociationDeclaration::fromString) .collect(Collectors.toList())); }

Target:
Arrays.asList(encoded.split(",")).stream() can be replaced with Arrays.stream(encoded.split(","))
Source:
void setStringValue(String value) { if (value == null || value.isEmpty()) { return; } DataInputAssociation input = input(value); getIoSpecification(element).getDataInputs().add((DataInput) input.getTargetRef()); element.getDataInputAssociations().add(input); }

Target:
Method can be private
Source:
public static DeclarationList fromString(String encoded) { return new DeclarationList( Arrays.asList(encoded.split(",")).stream() .map(VariableDeclaration::fromString) .collect(Collectors.toList())); }

Target:
Arrays.asList().stream() can be replaced with Arrays.stream()
Source:
public void testMinimalWidthOneCellInEachRowWithPadding() throws Exception { gridData.appendColumn(column); gridData.appendRow(new DMNGridRow()); gridData.appendRow(new DMNGridRow()); gridData.appendRow(new DMNGridRow()); mockCellsWithPadding(0, 0, PADDING, 100d); mockCellsWithPadding(1, 0, PADDING, 150); mockCellsWithPadding(2, 0, PADDING, 125); Assertions.assertThat(column.getMinimumWidth()).isEqualTo(170); }

Target:
I think the `d` is not necessary here, could be simplified to: `mockCellsWithPadding(0, 0, PADDING, 100);`
Source:
private List<Expression> extractColumnData(final int uiColumnIndex) { final int iiIndex = uiColumnIndex - RelationUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT; final List<Expression> values = relation.getRow().stream().map(row -> row.getExpression().get(iiIndex)).collect(Collectors.toList()); return values; }

Target:
Do we have this local variable `values` for debugging purposes? If not, we could shorten the statement: ```java return relation.getRow().stream().map(row -> row.getExpression().get(iiIndex)).collect(Collectors.toList()); ``` Let me know WDYT.
Source:
protected void fireExpressionEditorSelectedEvent() { final Optional<BaseExpressionGrid> parentGrid = findParentGrid(parent); editorSelectedEvent.fire(new ExpressionEditorSelectedEvent(sessionManager.getCurrentSession(), parentGrid)); }

Target:
Maybe your version is more readable, just wanted to ask if you noticed. Here you could update to: ```java final Optional<BaseExpressionGrid> parentGrid = findParentGrid(); ``` if the `findParentGrid` declared as: ```java private Optional<BaseExpressionGrid> findParentGrid() ```
Source:
public void testDefinitionEquals() { DefinitionImpl<String> a = new DefinitionImpl<>("a"); DefinitionImpl<String> b = new DefinitionImpl<>("a"); assertEquals(a, b); b.setDefinition("b"); assertNotEquals(a, b); b.setDefinition("a"); assertEquals(a, b); }

Target:
I guess null check is also will be nice to see here. Like ```java assertNotEquals(a, null); b.setDefinition(null); assertNotEquals(a, b); assertNotEquals(b, a); ```
Source:
private static String loadTaskForm(String taskForm) { String taskFormJson = ""; try { taskFormJson = Resources.toString(FormValuesProcessorTest.class.getResource(taskForm), Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return taskFormJson; }

Target:
Also, when you do that, you'll be able to return directly from the `try` block, reducing the size of the method by nearly a third.
Source:
public static void setup() { textAreaFormFieldValueProcessor = new TextAreaFormFieldValueProcessor(); multipleSubFormFieldValueProcessor = new MultipleSubFormFieldValueProcessor(); subFormFieldValueProcessor = new SubFormFieldValueProcessor(); localDateFieldValueProcessor = new LocalDateFieldValueProcessor(); localDateFieldValueProcessor.init(); formSerializer = new FormDefinitionSerializerImpl(new FieldSerializer(), new FormModelSerializer(), new TestMetaDataEntryManager()); textAreaTaskForm = getFormDefinition("TextareaTask-taskform.frm"); localDateTaskForm = getFormDefinition("LocalDateFieldTask-taskform.frm"); subformTaskForm = getFormDefinition("SubformTask-taskform.frm"); }

Target:
Why not initialize all of those fields at the declaration site? This `@BeforeClass` in my opinion doesn't add much value. (It would make sense if any of these constructors threw exceptions.)
Source:
public void onShowTimeDateTimePicker() { view.showTimeDate(false); String value = view.getTimeDate(); try { Date date = view.parseFromISO(value); view.setTimeDateTimePickerValue(date); } catch (Exception e) { view.setTimeDateTimePickerValue(value); } view.showTimeDateTimePicker(true); }

Target:
is to possible to catch some `Exception` sub-type? I mean some `ParserException`..
Source:
protected void update() { this.view.clear(); this.hideEmptyState(); int offset = getOffset(); this.resolveAssetsCount(); this.getAssets(this.filter, this.filterType, offset, this.currentPage * this.pageSize, this::addAssetsToView); this.view.setCurrentPage(this.currentPage); this.checkPaginationButtons(); }

Target:
Just passing `getOffset()` directly (not introducing local variable `offset`) as argument of `getAssets()` could help improve readability, what do you think?
Source:
String getCreatedTime(final AssetInfo asset) { return ts.format(LibraryConstants.Created) + " " + SocialDateFormatter.format(asset.getCreatedTime()); }

Target:
Please add access modifier, `private` probably?
Source:
public PopulatedAssetsView() { domUtil = new Elemental2DomUtil(); }

Target:
Why not inject this?
Source:
public void init(final DeleteProjectPopUpScreen presenter) { domUtil = new Elemental2DomUtil(); this.presenter = presenter; modalSetup(); }

Target:
Why not inject this?
Source:
private ServerTemplate loadServerTemplate(String serverTemplateId) { ServerTemplate template = getTemplateStorage().load(serverTemplateId); if (template == null) { throw new RuntimeException("No server template found for id " + serverTemplateId); } return template; }

Target:
(`final`)
Source:
private void onSaveError(final ClientRuntimeError error) { showError(error.getThrowable() instanceof DefinitionNotFoundException ? "somps" : error.getMessage()); }

Target:
"somps"? What's this?
Source:
public static Optional<ClassLoader> loadDependenciesClassloaderFromProject(String prjPath, String localRepo) { List<String> poms = new ArrayList<>(); MavenUtils.searchPoms(Paths.get(URI.create(FILE_URI + prjPath)), poms); List<URL> urls = getDependenciesURL(poms, localRepo); return buildResult(urls); }

Target:
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).
Source:
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(mock(Import.class))); }

Target:
This method contains assertion: ``` assertFalse(presenter.isInternalImport(mock(Import.class))); ``` Shouldn't be this? ``` 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(); textViewDecorator.setTextBoundaries(bb); final double width = bb.getWidth(); final double height = bb.getHeight(); updateFillGradient(width, height); } return cast(); }

Target:
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?
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(); 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(); } }

Target:
@pefernan A test that checks the showAssetUsagesDisplayer is invocked will be appreciated please.
Source:
public Map getMap() { return map; }

Target:
Let's avoid raw types, please.
Source:
public BoundingBox getBoundingBox() { if (getPathPartList().size() < 1) { if (!parse(getAttributes())) { return new BoundingBox(0, 0, 0, 0); } } return getPathPartList().getBoundingBox(); }

Target:
Both `if` statements could be erased, `parse` returns always true. WDYT?
Source:
public static NIOKieMavenCompiler getCompiler(KieDecorator decorator) { NIOKieMavenCompiler compiler = compilers.get(decorator); if (compiler == null) { compiler = createAndAddNewCompiler(decorator); } return compiler; }

Target:
decorator is of type KieDecorator, while the map is from Strings. perhaps you missed the `decorator.name()`?
Source:
public void render(FormRenderingContext context) { layoutGenerator.clear(); formContent.clear(); if (context != null) { Panel panel = layoutGenerator.buildLayout(context); formContent.add(panel); } }

Target:
@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?
Source:
public void addVariable(String variable, String type) { if (variables.containsKey(variable)) { String existingType = variables.get(variable); if (!existingType.equals(type)) { valid = false; errors.add("Wrong type for variable task variable '" + variable + "': expected type was '" + existingType + "' but received '" + type + "'."); } } else { variables.put(variable, type); } }

Target:
I see a problem with this error - user doesn't know where the expected type comes from (it is already added from other task).
Source:
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); } } }

Target:
Is it package private intentionally? Also this method has no test and, probably, not used.
Source:
public String getFormId() { FormDefinition def = renderingContext.getRootForm(); return renderingContext.getRootForm().getId(); }

Target:
I think this line should be `def.getId();` or the code on line 112 is useless.
Source:
private void buildTestedInstance() { ; this.tested = new ClientFullSessionImpl(factory, canvasCommandManager, sessionCommandManager, requestCommandManager, registryFactory); }

Target:
Floating semicolon
Source:
public ListBoxBaseDefinition getDefaultField() { StringListBoxFieldDefinition result = new StringListBoxFieldDefinition(); result.setStandaloneClassName(String.class.getName()); return result; }

Target:
same here, and so on, in case it could make sense
Source:
public String getDescription() { final String description = translationService.getTranslation(FormEditorConstants.NewFormDefinitionlHandlerForm); return description != null && !description.isEmpty() ? description : "Form (Preview)"; }

Target:
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.
Source:
private void formFieldsShouldNotBeGeneratedForPersistenceId(List<FieldDefinition> formModelFields) { assertTrue(dataObject.getProperty("id") != null); 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()); }

Target:
Hi @jsoltes you can use Assert#assertNotNull(java.lang.Object) method here.
Source:
public CanvasHighlight invalid(final Iterable<? extends RuleViolation> violations) { violations.forEach(v -> { final String uuid = v.getUUID(); if (null != uuid) { applyStateToShape(uuid, ShapeState.INVALID); } }); getCanvas().draw(); return this; }

Target:
Consider use of ```Optional```
Source:
protected Optional<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 Optional.of(move(element, x, y)); }

Target:
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?
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); ; } } return result; }

Target:
Floating ```;```
Source:
protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { final org.kie.workbench.common.stunner.core.graph.Graph graph = getGraph(context); final Collection<RuleViolation> cardinalityRuleViolations = doEvaluate(context, RuleContextBuilder.GraphContexts.cardinality(graph, getCandidate(), CardinalityContext.Operation.ADD)); return new GraphCommandResultBuilder(cardinalityRuleViolations).build(); }

Target:
Do we need FQCN?
Source:
private RuleExtensionHandler getExtensionHandler(final RuleExtension rule, final RuleEvaluationContext context) { final RuleExtensionHandler handler = registry.getExtensionHandler(rule.getHandlerType()); return null != handler && accepts(handler, rule, context) ? handler : null; }

Target:
Since you've used ```Optional``` elsewhere in this class; perhaps use of ```Optional``` here too would be nice?
Source:
public static RuleViolation addViolationSourceUUID(final String uuid, final RuleViolation violation) { try { ((AbstractRuleViolation) violation).setUuid(uuid); } catch (final ClassCastException ignored) { } return violation; }

Target:
Why would we expect a CCE? To me this smells of a hack to fix a problem you had.
Source:
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().filter( r -> r != null ) ).collect( Collectors.toList() ); }

Target:
Can we really have ```null``` ```ValidationMessage```? (it looks like you filter the list from validation for nulls)
Source:
public void applyTitle(final String title, final W element, final MutationContext mutationContext) { if (title.trim().length() > 0) { // Apply title's value. viewHandler.applyTitle(title, mutationContext); // Apply title's font styles. applyFont(element, mutationContext); } }

Target:
This condition is not covered by tests, but anyway I don't sure we are need this condition here.
Source:
void updateSelectedOrganizationalUnit() { libraryService.call( new RemoteCallback<OrganizationalUnitRepositoryInfo>() { @Override public void callback( final OrganizationalUnitRepositoryInfo newInfo ) { refreshLibrary( newInfo ); } } ).getOrganizationalUnitRepositoryInfo( getViewSelectedOrganizationalUnit() ); }

Target:
Lamda?
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(); this.canvasHighlight.destroy(); }

Target:
This method lead to NullPointerException: ```java this.canvasHighlight = null; [...] this.canvasHighlight.destroy(); ```
Source:
public void destroy() { destroyToolbar(); destroyPalette(); sessionManager.dispose(); getDisplayer().destroy(); getView().destroy(); diagram = null; }

Target:
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?
Source:
public void initializeWithProjectsTest() { doReturn( true ).when( libraryService ).thereIsAProjectInTheWorkbench(); libraryMonitor.initialize(); assertTrue( libraryMonitor.thereIsAtLeastOneProjectAccessible() ); verify( workbench ).addStartupBlocker( LibraryMonitor.class ); verify( workbench ).removeStartupBlocker( LibraryMonitor.class ); }

Target:
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.
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() ); grid.onAddAll( packages ); }

Target:
There's a missing assert here?
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() ) { for ( Diagram diagram : diagrams ) { getRegistry().register( diagram ); } } }

Target:
start using Java8. diagrams.forEach...
Source:
private Button button( final String text, final Command command, final ButtonType type ) { Button button = new Button( text, new ClickHandler() { @Override public void onClick( ClickEvent event ) { command.execute(); } } ); button.setType( type ); return button; }

Target:
And here... re: @karreiro mention of lamdas :-)
Source:
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 ); }

Target:
@paulovmr in the future we should move this to uberfire.
Source:
public DataObjectCreatedEvent( Project currentProject, DataObject currentDataObject ) { super( null, currentProject, currentDataObject ); }

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

Target:
I'm not a lover of passing nulls to methods or constructors.. would another constructor without the contextId be better?