auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testPutHeaders() { PutOptions options = new PutOptions().headers(ImmutableMultimap.of(OBJECT_DELETE_AT, "123456789")); START assertEquals(ImmutableList.of("123456789"), options.buildRequestHeaders().get(OBJECT_DELETE_AT)); END } As above, assertions the wrong way around?

Target:
public void testPutHeaders() { PutOptions options = new PutOptions().headers(ImmutableMultimap.of(OBJECT_DELETE_AT, "123456789")); assertEquals(options.buildRequestHeaders().get(OBJECT_DELETE_AT), ImmutableList.of("123456789")); }
Source:
public void testStaticWebsiteListingsCSS() { Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_LISTINGS_CSS, "listings.css"); UpdateContainerOptions options = new UpdateContainerOptions().headers(headers); START assertEquals(ImmutableList.of("listings.css"), options.buildRequestHeaders().get(STATIC_WEB_LISTINGS_CSS)); END } As above, assertions the wrong way around?

Target:
public void testStaticWebsiteListingsCSS() { Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_LISTINGS_CSS, "listings.css"); UpdateContainerOptions options = new UpdateContainerOptions().headers(headers); assertEquals(options.buildRequestHeaders().get(STATIC_WEB_LISTINGS_CSS), ImmutableList.of("listings.css")); }
Source:
public void testList() throws Exception { for (String regionId : regions) { ObjectApi objectApi = api.objectApiInRegionForContainer(regionId, containerName); ObjectList response = objectApi.list(); assertEquals(response.getContainer(), api.containerApiInRegion(regionId).get(containerName)); START assertNotNull(response); END for (SwiftObject object : response) { checkObject(object); } } } Don't need this assertion?

Target:
public void testList() throws Exception { for (String regionId : regions) { ObjectApi objectApi = api.objectApiInRegionForContainer(regionId, containerName); ObjectList response = objectApi.list(); assertEquals(response.getContainer(), api.containerApiInRegion(regionId).get(containerName)); for (SwiftObject object : response) { checkObject(object); } } }
Source:
public void testNonExistentVersion() throws Exception { // The referenced resource only an endpoint for v999.999 of the GlanceApi HttpResponse localVersionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload( payloadFromResourceWithContentType("/glanceVersionResponseVersionUnavailable.json", "application/json")).build(); GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, versionNegotiationRequest, localVersionNegotiationResponse); try { apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").list(); } catch (UncheckedExecutionException e) { if (e.getCause().getClass() == HttpException.class) return; } START fail("Did not throw expected HttpException"); END } Instead of the `try...catch...fail`, can we use `@Test(expected = HttpException)` here?

Target:
public void testNonExistentVersion() throws Exception { // The referenced resource only an endpoint for v999.999 of the GlanceApi HttpResponse localVersionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload( payloadFromResourceWithContentType("/glanceVersionResponseVersionUnavailable.json", "application/json")).build(); GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, versionNegotiationRequest, localVersionNegotiationResponse); apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").list(); }
Source:
public Builder metadata(Map<String, Object> metadata) { if (metadata == null) { this.metadata = ImmutableMap.of(); } else { this.metadata = ImmutableMap.copyOf(metadata); START } END return this; } The constructor already does this logic. Could this just be `this.metadata = metadata`?

Target:
public Builder metadata(Map<String, Object> metadata) { this.metadata = metadata; return this; }
Source:
public static NetworkType fromValue(String value) { START if (value == null) return null; END return NetworkType.valueOf(value.toUpperCase()); } Is `null` a valid input value here at all?

Target:
public static NetworkType fromValue(String value) { return NetworkType.valueOf(value.toUpperCase()); }
Source:
public static Properties defaultProperties() { System.setProperty(TTL_MIN_IN_SEC, "60"); System.setProperty(TTL_MAX_IN_SEC, "1209600"); System.setProperty(MESSAGE_MAX, "20"); START System.setProperty(MESSAGE_BODY_MAX_IN_BYTES, "262144"); END Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(SERVICE_TYPE, ServiceType.QUEUES); properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS); return properties; } Do we do this anywhere else? Any reason why these are in System?

Target:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(SERVICE_TYPE, ServiceType.QUEUES); properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS); return properties; }
Source:
public Builder ttl(int ttl) { checkArgument(ttl >= getInteger(TTL_MIN_IN_SEC), "ttl must be >= %s", getInteger(TTL_MIN_IN_SEC)); START checkArgument(ttl <= getInteger(TTL_MAX_IN_SEC), "ttl must be <= %s", getInteger(TTL_MAX_IN_SEC)); END this.ttl = ttl; return self(); } See above. In fact, combine these into one check: "ttl must be between X and Y (inclusive) but was Z"?

Target:
public Builder ttl(int ttl) { this.ttl = ttl; return self(); }
Source:
START protected static String getMessageId(String rawMessageHref) { END // strip off everything but the message id return rawMessageHref.substring(rawMessageHref.lastIndexOf('/')+1); } Make an injectable "hrefToMessageId" function?

Target:
private static String getMessageId(String rawMessageHref) { // strip off everything but the message id return rawMessageHref.substring(rawMessageHref.lastIndexOf('/')+1); }
Source:
protected void configure() { START bind(DateAdapter.class).to(Iso8601DateAdapter.class); END super.configure(); } This binding is redundant if the `AutoscaleParserModule` already adds it. Remove it from here?

Target:
protected void configure() { super.configure(); }
Source:
public int compareTo(SwiftResource that) { START if (that == null) END return 1; if (this == that) return 0; return this.getTransactionId().compareTo(that.getTransactionId()); } Better to throw NullPointerException?

Target:
public int compareTo(SwiftResource that) { return this.getTransactionId().compareTo(that.getTransactionId()); }
Source:
public HttpRequest filter(HttpRequest request) throws HttpException { String endpoint = request.getEndpoint().toString(); START Pattern pattern = Pattern.compile("/[^/]*$"); // From last / to the end of the line END Matcher matcher = pattern.matcher(endpoint); matcher.find(); String encodable = matcher.group(); String encoded = encodable.replace(".", "%2e"); String newEndpoint = matcher.replaceFirst(encoded); return request.toBuilder().endpoint(newEndpoint).build(); } Extract as a constant?

Target:
public HttpRequest filter(HttpRequest request) throws HttpException { String endpoint = request.getEndpoint().toString(); Matcher matcher = pattern.matcher(endpoint); if(!matcher.find()) return request; // do not modify if not found. This however is not expected to happen. String encodable = matcher.group(); String encoded = encodable.replace(".", "%2e"); String newEndpoint = matcher.replaceFirst(encoded); return request.toBuilder().endpoint(newEndpoint).build(); }
Source:
public CmdLineParser(Object bean, ParserProperties parserProperties) { // A 'return' in the constructor just skips the rest of the implementation // and returns the new object directly. if (bean==null) return; // Parse the metadata and create the setters new ClassParser().parse(bean,this); if (parserProperties.shouldSortOptions()) { // for display purposes, keep the arguments in argument order, but sort the options in alphabetical order Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } START setUsageWidth(parserProperties.getUsageWidth()); END } I think it's better to store the reference for future enhancements instead of just copying the content. I love the idea of a configuration object :+1:

Target:
public CmdLineParser(Object bean, ParserProperties parserProperties) { this.parserProperties = parserProperties; // A 'return' in the constructor just skips the rest of the implementation // and returns the new object directly. if (bean==null) return; // Parse the metadata and create the setters new ClassParser().parse(bean,this); if (parserProperties.shouldSortOptions()) { // for display purposes, keep the arguments in argument order, but sort the options in alphabetical order Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } }
Source:
public ParserProperties withUsageWidth(int usageWidth) { if (usageWidth < 0) throw new IllegalArgumentException("Usage width is negative"); if (this.usageWidth == usageWidth) return this; START return new ParserProperties(usageWidth, this.shouldSortOptions); END } This looks like a builder pattern in combination with fluent interface and some kind of immutable class pattern. The immutable class makes it much more complicated when the class grows. Every setter will be a big constructor call. Is it really necessary?

Target:
public ParserProperties withUsageWidth(int usageWidth) { if (usageWidth < 0) throw new IllegalArgumentException("Usage width is negative"); this.usageWidth = usageWidth; return this; }
Source:
public static List<Class<?>> getSuperInterfaces(Class clazz) { START ArrayList<Class<?>> result = new ArrayList<Class<?>>(); END addImplementedSuperInterfaces(clazz, result); return result; } You should be able to use the diamond operator here, i.e. new ArrayList<>()

Target:
public static List<Class<?>> getSuperInterfaces(Class clazz) { ArrayList<Class<?>> result = new ArrayList<>(); addImplementedSuperInterfaces(clazz, result); return result; }
Source:
public static void onUpgrade(Context context, SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion <= 2) { db.execSQL(QUERY_TABLE_DROP); onCreate(context, db); } else if (newVersion >= 3) { final String ALTER_TBL = "ALTER TABLE " + TABLENAME + " ADD COLUMN " + COLUMN_IS_PAID_ACCOUNT + " integer default 0;"; START db.execSQL(ALTER_TBL); END } } In this case you're going to alter the table for every new version. it must be newVersion == 3 && oldVersion <= 2

Target:
public static void onUpgrade(Context context, SQLiteDatabase db, int oldVersion, int newVersion) { //Update database to add the Paid Account flag. This was introduced in DB version 3. if (oldVersion <= 2) { final String ALTER_TBL = "ALTER TABLE " + TABLENAME + " ADD COLUMN " + COLUMN_IS_PAID_ACCOUNT + " integer default 0;"; db.execSQL(ALTER_TBL); } }
Source:
public void testRetrieveKeyAndValueNull() { // setup target JdbcCodeList jdbcCodeList = new JdbcCodeList(); // setup parameters\ jdbcCodeList.setDataSource(dataSource); jdbcCodeList.setLabelColumn("valueColumn"); jdbcCodeList.setValueColumn("labelColumn"); jdbcCodeList.setQuerySql("Select code_id, code_name from codelist"); Map<String, String> mapOutput = jdbcCodeList.retrieveMap(); // assert assertThat(mapOutput.size(), is(0)); assertNull(mapOutput.get("valueColumn")); START assertNull(mapOutput.get("labelColumn")); END } - [x] Follows are unnecessary, because `mapOutput.size` is zero. ``` assertNull(mapOutput.get("valueColumn")); assertNull(mapOutput.get("labelColumn")); ``` --- It was removed. 059df0362e3fc35b1ec81490950162cfbd065425

Target:
public void testRetrieveKeyAndValueNull() { // setup target JdbcCodeList jdbcCodeList = new JdbcCodeList(); // setup parameters\ jdbcCodeList.setDataSource(dataSource); jdbcCodeList.setLabelColumn("valueColumn"); jdbcCodeList.setValueColumn("labelColumn"); jdbcCodeList.setQuerySql("Select code_id, code_name from codelist"); Map<String, String> mapOutput = jdbcCodeList.retrieveMap(); // assert assertThat(mapOutput.size(), is(0)); }
Source:
private void postConstruct() throws IOException { START LOGGER.debug("Fedora staging: {}", fedoraOcflStaging); END LOGGER.debug("Fedora OCFL root: {}", ocflRepoRoot); LOGGER.debug("Fedora OCFL temp: {}", ocflTemp); Files.createDirectories(fedoraOcflStaging); Files.createDirectories(ocflRepoRoot); Files.createDirectories(ocflTemp); } Normally I do not like the logs to be too chatty... but these three messages are important to see at startup. Can you change them to `LOGGER.info()`?

Target:
private void postConstruct() throws IOException { LOGGER.info("Fedora staging: {}", fedoraOcflStaging); LOGGER.info("Fedora OCFL root: {}", ocflRepoRoot); LOGGER.info("Fedora OCFL temp: {}", ocflTemp); Files.createDirectories(fedoraOcflStaging); Files.createDirectories(ocflRepoRoot); Files.createDirectories(ocflTemp); }
Source:
public DefaultOCFLObjectSessionFactory( @Value("#{ocflPropsConfig.fedoraOcflStaging}") final Path ocflStagingDir) { START LOGGER.info("Fedora OCFL persistence staging directory:\n- {}", END ocflStagingDir); try { this.ocflStagingDir = Files.createDirectories(ocflStagingDir); } catch (IOException e) { throw new UncheckedIOException(e); } } Maybe reduce this logging to `debug`, in favor of the cleaner output of `OcflPropsConfig`.

Target:
public DefaultOCFLObjectSessionFactory( @Value("#{ocflPropsConfig.fedoraOcflStaging}") final Path ocflStagingDir) { LOGGER.debug("Fedora OCFL persistence staging directory:\n- {}", ocflStagingDir); try { this.ocflStagingDir = Files.createDirectories(ocflStagingDir); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
START private String encode(final String value) throws Exception { END return URLEncoder.encode(value, StandardCharsets.UTF_8); } Can remove `throws` clause.

Target:
private String encode(final String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); }
Source:
START public static final Operator fromString(final String str) { END for (Operator o : Operator.values()) { if (o.value.equals(str)) { return o; } } throw new IllegalArgumentException("Value " + str + " not recognized."); } Can remove `final`... as this method is `static`.

Target:
public static Operator fromString(final String str) { for (Operator o : Operator.values()) { if (o.value.equals(str)) { return o; } } throw new IllegalArgumentException("Value " + str + " not recognized."); }
Source:
START public Condition(final Field field, final Operator operator, final String object) { END this.field = field; this.operator = operator; this.object = object; } Just a thought, but you could push the expression parse logic down into this class. I could see `Condition` having the following `public static` methods: * `public static Condition fromExpression(final String conditionExpression);` * `public static Condition fromStrings(final String field, final String operator, final String object);` * `public static Condition fromEnums(final Field field, final Operator operator, final String object);` Or something along those lines.

Target:
private Condition(final Field field, final Operator operator, final String object) { this.field = field; this.operator = operator; this.object = object; }
Source:
public void stop(BundleContext context) throws Exception { START Preferences.getInstance().dispose(); END super.stop(context); } It doesn't feel right. Why it is required?

Target:
public void stop(BundleContext context) throws Exception { try { Preferences.getInstance().dispose(); } finally { super.stop(context); } }
Source:
protected Object doReadObject(final boolean unshared) throws ClassNotFoundException, IOException { START final Object obj = objectPreResolver.readResolve(doReadObject(readUnsignedByte(), unshared)); END if (depth == 0) { final SortedSet<Validator> validators = this.validators; if (validators != null) { this.validators = null; validatorSeq = 0; for (Validator validator : validators) { validator.getValidation().validateObject(); } } } return obj; } I think this placement might be a problem, because there are a number of call sites which call doReadObject(int, boolean) which would essentially bypass this resolution. I think you may have to either edit the main doReadObject method, capturing every return statement, or else wrap the whole method with a method that does the substitution (though this will reduce the maximum stack depth that can be achieved).

Target:
protected Object doReadObject(final boolean unshared) throws ClassNotFoundException, IOException { final Object obj = doReadObject(readUnsignedByte(), unshared); if (depth == 0) { final SortedSet<Validator> validators = this.validators; if (validators != null) { this.validators = null; validatorSeq = 0; for (Validator validator : validators) { validator.getValidation().validateObject(); } } } return obj; }
Source:
protected RemoteCallback<List<String>> getRemoteCallback(Consumer<List<KieAssetsDropdownItem>> assetListConsumer) { return response -> { List<KieAssetsDropdownItem> toAccept = response.stream() .map(this::getKieAssetsDropdownItem) START .filter(this::filterTargetDirectory) END .sorted(Comparator.comparing(KieAssetsDropdownItem::getText, String.CASE_INSENSITIVE_ORDER)) .collect(Collectors.toList()); assetListConsumer.accept(toAccept); }; } Could you please tell me why dont we use an Optional for for "toAccept"? Isnt that possible that user would have some leftovers in target but removed all dmn files in the project?

Target:
protected RemoteCallback<List<String>> getRemoteCallback(Consumer<List<KieAssetsDropdownItem>> assetListConsumer) { return response -> { List<KieAssetsDropdownItem> toAccept = response.stream() .map(this::getKieAssetsDropdownItem) .sorted(Comparator.comparing(KieAssetsDropdownItem::getText, String.CASE_INSENSITIVE_ORDER)) .collect(Collectors.toList()); assetListConsumer.accept(toAccept); }; }
Source:
protected void resetDocks() { START abstractScenarioSimulationDocksHandler.getSettingsPresenter().ifPresent(SubDockView.Presenter::reset); abstractScenarioSimulationDocksHandler.getCheatSheetPresenter().ifPresent(SubDockView.Presenter::reset); abstractScenarioSimulationDocksHandler.getTestToolsPresenter().ifPresent(SubDockView.Presenter::reset); scenarioSimulationEditorWrapper.resetAdditionalDocks(); END } Is it possible to uniform this code and not have two different approaches?

Target:
protected void resetDocks() { abstractScenarioSimulationDocksHandler.resetDocks(); }
Source:
START protected double getColumnWidth(String expressionIdentifierName) { END ExpressionIdentifier.NAME expressionName; try { expressionName = ExpressionIdentifier.NAME.valueOf(expressionIdentifierName); } catch (IllegalArgumentException e) { expressionName = ExpressionIdentifier.NAME.Other; } switch (expressionName) { case Index: return 70; case Description: return 300; default: return 114; } } I remember a similar (the same?) code somewhere else. Am I wrong?

Target:
protected static double getColumnWidth(String expressionIdentifierName) { ExpressionIdentifier.NAME expressionName; try { expressionName = ExpressionIdentifier.NAME.valueOf(expressionIdentifierName); } catch (IllegalArgumentException e) { expressionName = ExpressionIdentifier.NAME.Other; } switch (expressionName) { case Index: return 70; case Description: return 300; default: return 114; } }
Source:
private boolean isTypeGuvnorEnum() { return conditionColumn != null && conditionColumn.getValueList() != null && START conditionColumn.getValueList().split(",").length > 1; END } Shouldn't we handle case when single enum is specified? ```java private boolean isTypeGuvnorEnum() { if (conditionColumn != null && conditionColumn.getValueList() != null) { if (conditionColumn.getValueList().split(",").length > 1) { return true; } else { return conditionColumn.getValueList().trim().length() > 0; } } else { return false; } } ```

Target:
private boolean isTypeGuvnorEnum() { return conditionColumn != null && conditionColumn.getValueList() != null && !conditionColumn.getValueList().trim().isEmpty(); }
Source:
protected static JSIScenarioType getScenario(Scenario source) { JSIScenarioType toReturn = new JSIScenarioType(); JSIFactMappingValuesType factMappingValuesType = new JSIFactMappingValuesType(); toReturn.setFactMappingValues(factMappingValuesType); final List<FactMappingValue> unmodifiableFactMappingValues = source.getUnmodifiableFactMappingValues(); START List<JSIFactMappingValueType> toSet = new ArrayList<>(); populateJSIFactMappingValuesType(toSet, unmodifiableFactMappingValues); factMappingValuesType.setFactMappingValue(toSet); END return toReturn; } We should either make `populateJSIFactMappingValuesType` private or move the `toSet` variable inside of `populateJSIFactMappingValuesType` because currently we do not do any check in `populateJSIFactMappingValuesType` if `toSet` is not null.

Target:
protected static JSIScenarioType getScenario(Scenario source) { JSIScenarioType toReturn = new JSIScenarioType(); JSIFactMappingValuesType factMappingValuesType = new JSIFactMappingValuesType(); toReturn.setFactMappingValues(factMappingValuesType); final List<FactMappingValue> unmodifiableFactMappingValues = source.getUnmodifiableFactMappingValues(); List<JSIFactMappingValueType> toSet = populateJSIFactMappingValuesType(unmodifiableFactMappingValues); factMappingValuesType.setFactMappingValue(toSet); return toReturn; }
Source:
protected static Imports getImports(JSIImportsType source) { Imports toReturn = new Imports(); START if (source != null) { final JSIWrappedImportsType imports = source.getImports(); if (imports != null) { imports.getImport().forEach(importsType -> toReturn.addImport(getImport(importsType))); } } END return toReturn; } This variant is a little bit shorter and still well readable, what do you think? ```java if (source != null && source.getImports() != null) { final JSIWrappedImportsType imports = source.getImports(); imports.getImport().forEach(importsType -> toReturn.addImport(getImport(importsType))); } ```

Target:
protected static Imports getImports(JSIImportsType source) { Imports toReturn = new Imports(); if (source != null && source.getImports() != null) { final JSIWrappedImportsType imports = source.getImports(); imports.getImport().forEach(importsType -> toReturn.addImport(getImport(importsType))); } return toReturn; }
Source:
public void getItems(Consumer<List<KieAssetsDropdownItem>> assetListConsumer) { List<KieAssetsDropdownItem> toAccept = new ArrayList<>(); START assetListConsumer.accept(toAccept); END } Can't be just `assetListConsumer.accept(Collections.emptyList())`?

Target:
public void getItems(Consumer<List<KieAssetsDropdownItem>> assetListConsumer) { assetListConsumer.accept(new ArrayList<>()); }
Source:
private String parseActualValue(final String value) { START if (value != null && value.indexOf("=") > 1) { END return value.substring(0, value.indexOf("=")); } else { return value; } } I think this should be `> 0` since a value list item of `1=One` does not work.

Target:
private String parseActualValue(final String value) { if (value != null && value.indexOf("=") > 0) { return value.substring(0, value.indexOf("=")); } else { return value; } }
Source:
public void setGridWidgetBACKGROUND() { testToolsPresenterSpy.setGridWidget(GridWidget.BACKGROUND); verify(testToolsPresenterSpy, times(1)).onDisableEditorTab(); verify(testToolsPresenterSpy, times(1)).hideInstances(); START verify(testToolsPresenterSpy, never()).showInstanceListContainerSeparator(eq(true)); END } @yesamer This can be removed, I think

Target:
public void setGridWidgetBACKGROUND() { testToolsPresenterSpy.setGridWidget(GridWidget.BACKGROUND); verify(testToolsPresenterSpy, times(1)).onDisableEditorTab(); verify(testToolsPresenterSpy, times(1)).hideInstances(); }
Source:
public void onBackgroundTabSelected() { setItemMenuEnabled(true); START runScenarioMenuItem.setEnabled(false); END scenarioBackgroundGridWidget.clearSelections(); scenarioBackgroundGridWidget.select(); scenarioMainGridWidget.deselect(); populateRightDocks(TestToolsPresenter.IDENTIFIER); } Please enable run button in background tab

Target:
public void onBackgroundTabSelected() { setItemMenuEnabled(true); scenarioBackgroundGridWidget.clearSelections(); scenarioBackgroundGridWidget.select(); scenarioMainGridWidget.deselect(); populateRightDocks(TestToolsPresenter.IDENTIFIER); }
Source:
protected void checkExpressionSyntax() { START String value = getValue(); END if (!value.startsWith(EXPRESSION_VALUE_PREFIX)) { if (value.startsWith(MVEL_ESCAPE_SYMBOL)) { widget.setValue(value.replaceFirst(MVEL_ESCAPE_SYMBOL, EXPRESSION_VALUE_PREFIX)); } else if (value.startsWith(" ")) { widget.setValue(value.replaceFirst(" ", EXPRESSION_VALUE_PREFIX)); } else { widget.setValue(EXPRESSION_VALUE_PREFIX + value); } } } could be final

Target:
protected void checkExpressionSyntax() { final String value = getValue(); if (!value.startsWith(EXPRESSION_VALUE_PREFIX)) { if (value.startsWith(MVEL_ESCAPE_SYMBOL)) { widget.setValue(value.replaceFirst(MVEL_ESCAPE_SYMBOL, EXPRESSION_VALUE_PREFIX)); } else if (value.startsWith(" ")) { widget.setValue(value.replaceFirst(" ", EXPRESSION_VALUE_PREFIX)); } else { widget.setValue(EXPRESSION_VALUE_PREFIX + value); } } }
Source:
protected FactModelTree createTopLevelFactModelTree(String factName, DMNType type, SortedMap<String, FactModelTree> hiddenFacts, FactModelTree.Type fmType) throws WrongDMNTypeException { START return isToBeManagedAsCollection((BaseDMNTypeImpl) type) ? createFactModelTreeForCollection(new HashMap<>(), factName, type, hiddenFacts, fmType, new ArrayList<>()) : createFactModelTreeForNoCollection(new HashMap<>(), factName, factName, type.getName(), type, hiddenFacts, fmType, new ArrayList<>()); END } @danielezonca Since it is always cast, is it not possible to directly set _BaseDMNTypeImpl_ for "type" instead of _DMNType_ ?

Target:
protected FactModelTree createTopLevelFactModelTree(String factName, DMNType type, SortedMap<String, FactModelTree> hiddenFacts, FactModelTree.Type fmType) throws WrongDMNTypeException { return isToBeManagedAsCollection(type) ? createFactModelTreeForCollection(new HashMap<>(), factName, type, hiddenFacts, fmType, new ArrayList<>()) : createFactModelTreeForNoCollection(new HashMap<>(), factName, factName, type.getName(), type, hiddenFacts, fmType, new ArrayList<>()); }
Source:
public void onSaveButton(String scenarioType) { if (saveCommand != null) { simulationDescriptor.setSkipFromBuild(view.getSkipFromBuild().isChecked()); switch (ScenarioSimulationModel.Type.valueOf(scenarioType)) { case RULE: saveRuleSettings(); break; case DMN: saveDMNSettings(); START break; END } saveCommand.execute(); } } Just a small suggestion to add a default with new IlligalStateException in case if we would add some new scenario type.

Target:
public void onSaveButton(String scenarioType) { if (saveCommand != null) { simulationDescriptor.setSkipFromBuild(view.getSkipFromBuild().isChecked()); switch (ScenarioSimulationModel.Type.valueOf(scenarioType)) { case RULE: saveRuleSettings(); break; case DMN: saveDMNSettings(); break; default: // nop } saveCommand.execute(); } }
Source:
START public void onDownload(final Supplier<Path> pathSupplier) { END final String downloadURL = getFileDownloadURL(pathSupplier); open(downloadURL); } @yesamer Why those have been changed to _public_ ? Just to understand

Target:
protected void onDownload(final Supplier<Path> pathSupplier) { final String downloadURL = getFileDownloadURL(pathSupplier); open(downloadURL); }
Source:
public void isExecutable_HeaderCellSelected() { when(scenarioGridModelMock.getSelectedCells()).thenReturn(Collections.emptyList()); START when(scenarioGridModelMock.getSelectedHeaderCells()).thenReturn(Lists.create(selectedCell, selectedCell2)); END assertTrue(handler.isExecutable(scenarioGridMock)); } just one cell should be here

Target:
public void isExecutable_HeaderCellSelected() { when(scenarioGridModelMock.getSelectedCells()).thenReturn(Collections.emptyList()); when(scenarioGridModelMock.getSelectedHeaderCells()).thenReturn(Arrays.asList(selectedCell)); assertTrue(handler.isExecutable(scenarioGridMock)); }
Source:
private boolean hasEntryPoint(final Pattern52 pattern) { START return pattern.getEntryPointName() != null && !pattern.getEntryPointName().trim().isEmpty(); END } We could use `org.drools.core.util.StringUtils` for the implementation.

Target:
private boolean hasEntryPoint(final Pattern52 pattern) { return !StringUtils.isEmpty(pattern.getEntryPointName()); }
Source:
protected boolean isToSkip(FactMapping factMapping) { return OTHER.equals(factMapping.getExpressionIdentifier().getType()) || EMPTY.equals(factMapping.getFactIdentifier()) || START factMapping.getExpressionElements().size() == 0; END } Just for the sake of short codebase `.size() == 0` could be replaced by `.isEmpty()`

Target:
public static boolean isToSkip(FactMapping factMapping) { return OTHER.equals(factMapping.getExpressionIdentifier().getType()) || EMPTY.equals(factMapping.getFactIdentifier()) || factMapping.getExpressionElements().isEmpty(); }
Source:
public void deleteColumn(int columnIndex) { checkSimulation(); final GridColumn<?> toDelete = getColumns().get(columnIndex); deleteColumn(toDelete); simulation.removeFactMappingByIndex(columnIndex); START synchronizeFactMappingsWidths(); END } @yesamer I think that's to be removed. `synchronizeFactMappingsWidths` put the current columns widht inside factmappings, but we decided it should happen **only** when the user saves the scenario - otherwise rely on the "status" implementation to manage them

Target:
public void deleteColumn(int columnIndex) { checkSimulation(); final GridColumn<?> toDelete = getColumns().get(columnIndex); deleteColumn(toDelete); simulation.removeFactMappingByIndex(columnIndex); }
Source:
public void onImport(String fileContents) { START GWT.log(this.toString() + "onImport(" + fileContents + ")"); END scenarioSimulationEditorWrapper.onImport(fileContents, getImportCallBack(), getImportErrorCallback(), context.getStatus().getSimulation()); } Is this log necessary?

Target:
public void onImport(String fileContents) { scenarioSimulationEditorWrapper.onImport(fileContents, getImportCallBack(), getImportErrorCallback(), context.getStatus().getSimulation()); }
Source:
public void onEvent(AppendColumnEvent event) { context.getStatus().setColumnId(String.valueOf(new Date().getTime())); context.getStatus().setColumnGroup(event.getColumnGroup()); commonExecution(context, new AppendColumnCommand()); START context.getScenarioGridPanel().setFocus(true); END } @jomarko If there is nothing preventing this, move all those "context.getScenarioGridPanel().setFocus(true);" inside commonExecution

Target:
public void onEvent(AppendColumnEvent event) { context.getStatus().setColumnId(String.valueOf(new Date().getTime())); context.getStatus().setColumnGroup(event.getColumnGroup()); commonExecution(context, new AppendColumnCommand(), true); }
Source:
public String getType(final Optional<String> operatorFromCell) throws ValueResolveException { try { Logger.add("Getting type from utils"); if (operatorFromCell.isPresent()) { return conditionColumn.getFieldType(); } final String type = utils.getType(conditionColumn, columnIndex); START Logger.add("Resolver type from utils: " + type); END return type; } catch (final Exception e) { throw new ValueResolveException("Failed to get type for " + ToString.toString(conditionColumn) + " columnIndex: " + columnIndex, e); } } Do we want to keep the logging in this class. Asking because we do not log what type was resolved if operator was in the cell.

Target:
public String getType(final Optional<String> operatorFromCell) throws ValueResolveException { try { if (operatorFromCell.isPresent()) { return conditionColumn.getFieldType(); } final String type = utils.getType(conditionColumn, columnIndex); return type; } catch (final Exception e) { throw new ValueResolveException("Failed to get type for " + ToString.toString(conditionColumn) + " columnIndex: " + columnIndex, e); } }
Source:
START protected FactModelTree getSimpleClassFactModelTree(Class clazz) { END String key = clazz.getSimpleName(); Map<String, String> simpleProperties = new HashMap<>(); String fullName = clazz.getCanonicalName(); simpleProperties.put("value", fullName); String packageName = fullName.substring(0, fullName.lastIndexOf(".")); return new FactModelTree(key, packageName, simpleProperties); } This seems to me as util method that could be used by **delegation** instead of **inheritance**. Is the inheritance used because of the testeability?

Target:
protected static FactModelTree getSimpleClassFactModelTree(Class clazz) { String key = clazz.getSimpleName(); Map<String, String> simpleProperties = new HashMap<>(); String fullName = clazz.getCanonicalName(); simpleProperties.put("value", fullName); String packageName = fullName.substring(0, fullName.lastIndexOf(".")); return new FactModelTree(key, packageName, simpleProperties); }
Source:
public ScenarioGridColumn build() { List<GridColumn.HeaderMetaData> headerMetaDataList = headerBuilder.build(); ScenarioGridColumnRenderer actualScenarioGridColumnRenderer = scenarioGridColumnRenderer != null ? scenarioGridColumnRenderer : new ScenarioGridColumnRenderer(); ScenarioGridColumn scenarioGridColumn = new ScenarioGridColumn(headerMetaDataList, actualScenarioGridColumnRenderer, width, isMovable, factoryCell, placeHolder ); // by default scenario columns should be auto to have auto resize scenarioGridColumn.setColumnWidthMode(GridColumn.ColumnWidthMode.auto); START scenarioGridColumn.setMinimumWidth(width); END return scenarioGridColumn; } If these are the defaults for ScenarioGridColumn, should we set them inside the ScenarioGridColumn constructor?

Target:
public ScenarioGridColumn build() { List<GridColumn.HeaderMetaData> headerMetaDataList = headerBuilder.build(); ScenarioGridColumnRenderer actualScenarioGridColumnRenderer = scenarioGridColumnRenderer != null ? scenarioGridColumnRenderer : new ScenarioGridColumnRenderer(); return new ScenarioGridColumn(headerMetaDataList, actualScenarioGridColumnRenderer, width, isMovable, factoryCell, placeHolder ); }
Source:
START public void removeFactMapping(FactMapping toRemove) { END factMappings.remove(toRemove); } I prefer to move these methods to `Simulation` (or better create also two methods there and change these to package private) so they can remove also existing related `FactMappingValue` from the `Scenario`s before to remove them from the header. Otherwise it is easy to forget to cleanup `Scenario`s and have inconsistent data

Target:
void removeFactMapping(FactMapping toRemove) { factMappings.remove(toRemove); }
Source:
public IndexBuilder fillIndexBuilder(final Path path) throws Exception { InputStream inputStream = null; try { inputStream = ioService.newInputStream(path, StandardOpenOption.READ); START final String drl = DecisionTableFactory.loadFromInputStream(inputStream, END null); return fillDrlIndexBuilder(path, drl); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // no-op } } } } Worth to use try with resources: ```java try (final InputStream inputStream = ioService.newInputStream(path, StandardOpenOption.READ)) { final String drl = DecisionTableFactory.loadFromInputStream(inputStream, null); return fillDrlIndexBuilder(path, drl); } ```

Target:
public IndexBuilder fillIndexBuilder(final Path path) throws Exception { try (final InputStream inputStream = ioService.newInputStream(path, StandardOpenOption.READ)) { final String drl = DecisionTableFactory.loadFromInputStream(inputStream, null); return fillDrlIndexBuilder(path, drl); } }
Source:
public ScenarioSimulationEditorPresenter(final Caller<ScenarioSimulationService> service, final ScenarioSimulationResourceType type, final ImportsWidgetPresenter importsWidget, final AsyncPackageDataModelOracleFactory oracleFactory) { super(); START this.baseView = newScenarioSimulationView(); // Indirection added for test-purpose END this.service = service; this.type = type; this.importsWidget = importsWidget; this.oracleFactory = oracleFactory; } You should use the super(baseView) to provide the view for base and then set the view for this class so that you don't need to later cast for the actual view.

Target:
public ScenarioSimulationEditorPresenter(final Caller<ScenarioSimulationService> service, final ScenarioSimulationResourceType type, final ImportsWidgetPresenter importsWidget, final AsyncPackageDataModelOracleFactory oracleFactory) { super(); this.view = newScenarioSimulationView(); // Indirection added for test-purpose this.baseView = view; this.service = service; this.type = type; this.importsWidget = importsWidget; this.oracleFactory = oracleFactory; }
Source:
void submit() { view.submit(versionRecordManager.getCurrentPath()); START versionRecordManager.restoreToCurrentVersion(); END concurrentUpdateSessionInfo = null; } Are you sure this is the correct method!? From what I can see (from the code) that will show a popup to restore the file to the current version. Other editors use ```versionRecordManager.reloadVersions(path);``` in their "save success callbacks". You might also want to check the XLS Score Card Editor and the "Upload file" Editor for similar problems. I'll compile this PR and _see_ what it's doing; in case my code review is misguided.

Target:
void submit() { view.submit(versionRecordManager.getCurrentPath()); concurrentUpdateSessionInfo = null; }
Source:
public DeleteColumnManagementAnchorWidget() { super(); setText(GuidedDecisionTableConstants.INSTANCE.Delete()); setTitle(GuidedDecisionTableConstants.INSTANCE.DeleteThisColumn()); addClickHandler((clickEvent) -> { START deletePopUpPresenter.getToggleCommentPresenter().getViewElement().setAttribute("hidden", END "true"); deletePopUpPresenter.show((comment) -> afterDeleteConfirmedCommand.execute()); }); } @jomarko I don't think it's going to be quite so easy :-( IMO this is really an abuse of the ```DeletePopupPresenter``` as we should not be tweaking it's visual appearance from outside the class (adding a ```enableComment(boolean)``` is probably quite acceptable)... but that also brings me onto...

Target:
public DeleteColumnManagementAnchorWidget() { }
Source:
START public CEPOperatorsDropdown getNewOperatorDropdown(String[] operators, END SingleFieldConstraint constraint) { return new CEPOperatorsDropdown(operators, constraint); } Did you want this to ideally be package protected?

Target:
CEPOperatorsDropdown getNewOperatorDropdown(String[] operators, SingleFieldConstraint constraint) { return new CEPOperatorsDropdown(operators, constraint); }
Source:
public static void assertDoesNotContain(final String notExpected, final Set<Issue> result, final int rowNumber) { assertFalse("Found " + notExpected, result.stream() .filter(issue -> titleEquals(issue, notExpected) && rowNumberContains(issue, START new HashSet<Integer>() {{ END add(rowNumber); }})) .count() > 0); } `Collections.singletonSet(rowNumber)`

Target:
public static void assertDoesNotContain(final String notExpected, final Set<Issue> result, final int rowNumber) { assertFalse("Found " + notExpected, result.stream() .filter(issue -> titleEquals(issue, notExpected)) .filter(issue -> rowNumberContains(issue, Arrays.asList(rowNumber))) .count() > 0); }
Source:
public void init(final AdditionalInfoPage page) { this.page = page; clear(); START setup(); END } This could be considered a strange implementation of MVP; as your P is calling ```V.init(..)``` which then calls ```V.setup()``` which then calls the P to call the V to setup some UI elements. Why not have P call perform the complete setup rather than have the V call the P to call the V to complete setup? Or did I miss something?

Target:
public void init(final AdditionalInfoPage page) { this.page = page; }
Source:
private void setupFieldList() { final String selectField = translate(GuidedDecisionTableErraiConstants.FieldPageView_SelectField); fieldsList.clear(); fieldsList.addItem("-- " + selectField + " --", ""); START page.forEachFactField(fieldName -> fieldsList.addItem(fieldName)); END fieldsList.setSelectedIndex(getCurrentIndexFromList(getCurrentValue(), fieldsList)); } It took a little "unwinding" but I followed the code OK!

Target:
public void setupFieldList() { final String selectField = translate(GuidedDecisionTableErraiConstants.FieldPageView_SelectField); fieldsList.clear(); fieldsList.addItem("-- " + selectField + " --", ""); }
Source:
public int hashCode() { int result = severity != null ? severity.hashCode() : 0; result = 31 * result + (rowNumbers != null ? rowNumbers.hashCode() : 0); result = 31 * result + (checkType != null ? checkType.hashCode() : 0); result = 31 * result + (debugMessage != null ? debugMessage.hashCode() : 0); START return result; END } GWT Client side and hashCode tend to cause trouble, the workaround is to use ~~ Like this: https://github.com/kiegroup/drools-wb/blob/1fabbdea01b75ac325e97df72d58d87a65d3955d/drools-wb-services/drools-wb-verifier/drools-wb-verifier-api/src/main/java/org/drools/workbench/services/verifier/api/client/index/FieldBase.java#L100-L105

Target:
public int hashCode() { int result = severity != null ? ~~severity.hashCode() : 0; result = 31 * result + (rowNumbers != null ? ~~rowNumbers.hashCode() : 0); result = 31 * result + (checkType != null ? ~~checkType.hashCode() : 0); result = 31 * result + (debugMessage != null ? ~~debugMessage.hashCode() : 0); return ~~result; }
Source:
public int hashCode() { int result = factType.hashCode(); START result = 31 * result + name.hashCode(); END return result; } I'm still scared something stupid not using `result = ~~result` in your `hashCode` implementations.. but if you're happy.. then.... you'll be the one scratching your head _if_ the JIRAs start rolling in about V&V going crazy after a while..

Target:
public int hashCode() { int result = ~~factType.hashCode(); result = 31 * result + ~~name.hashCode(); return ~~result; }
Source:
protected String[] getDuplicates() { START System.out.println("getting duplicates"); END return duplicates; } Sorry, @zkrejcov I missed this the first time round.. it'd be best to remove this type of logging (which I assume you added to help debug your tests, or the like)

Target:
protected String[] getDuplicates() { return duplicates; }
Source:
public int hashCode() { START return 37 * pattern.hashCode() + factField.hashCode(); END } If you find your analysis panel starts going a bit loopy (IIRC you said it does), you might want to check your `hashCode` implementations - you should try to use `result = ~~result` type construct.. I can dig out the original email if you like?

Target:
public int hashCode() { final int result = 37 * pattern.hashCode() + factField.hashCode(); return ~~result; }
Source:
void initialiseLockManager() { lockManager.init( new LockTarget( currentPath, parent.getView().asWidget(), placeRequest, new LockTarget.TitleProvider() { @Override public String getTitle() { return currentPath.getFileName() + " - " + resourceType.getDescription(); } }, new Runnable() { @Override public void run() { //Nothing to do } START } ), END parent ); } last two parameters to LockTarget constructor could be lambda expressions to make this statement shorter.

Target:
void initialiseLockManager() { lockManager.init( new LockTarget( currentPath, parent.getView().asWidget(), placeRequest, () -> currentPath.getFileName() + " - " + resourceType.getDescription(), () -> {/*nothing*/} ), parent ); }
Source:
private boolean isSelfSigned(X509Certificate[] chain) { START if(chain[0].getIssuerX500Principal().getName().equals(chain[0].getSubjectX500Principal().getName())){ END return true; } else { return false; } } Perhaps replace by: `return chain[0].getIssuerX500Principal().getName().equals(chain[0].getSubjectX500Principal().getName())` (there's no need for the if/else)?

Target:
private boolean isSelfSigned(X509Certificate[] chain) { return chain[0].getIssuerX500Principal().getName().equals(chain[0].getSubjectX500Principal().getName()) && chain.length == 1; }
Source:
private int asLit(SetVar var, DecisionOperator<SetVar> op, int val) { int l; START if (op == DecisionOperatorFactory.makeSetForce()) { l = SatSolver.negated(png.Literal(var, val, true)); } else if (op == DecisionOperatorFactory.makeSetRemove()) { END l = png.Literal(var, val, true); } else { throw new UnsupportedOperationException("Cannot deal with such operator: " + op); } return l; } Method `equals()` should be used instead of `==`.

Target:
private int asLit(SetVar var, DecisionOperator<SetVar> op, int val) { int l; if (DecisionOperatorFactory.makeSetForce().equals(op)) { l = SatSolver.negated(png.Literal(var, val, true)); } else if (DecisionOperatorFactory.makeSetRemove().equals(op)) { l = png.Literal(var, val, true); } else { throw new UnsupportedOperationException("Cannot deal with such operator: " + op); } return l; }
Source:
public int getPropagationConditions(int idx) { START if (fast) { END return IntEventType.instantiation(); } return IntEventType.boundAndInst(); } remove fast attribute?

Target:
public int getPropagationConditions(int idx) { return IntEventType.boundAndInst(); }
Source:
private void findSingletons(BitSet restriction) { for (int i = restriction.nextSetBit(0); i >= 0; i = restriction.nextSetBit(i + 1)) { START if (graph.getPredOf(i).size() * graph.getSuccOf(i).size() == 0) { END nodeSCC[i] = nbSCC; sccFirstNode[nbSCC++] = i; restriction.clear(i); } } } I suggest: `if (graph.getPredOf(i).size() == 0 || graph.getSuccOf(i).size() == 0) {`

Target:
private void findSingletons(BitSet restriction) { for (int i = restriction.nextSetBit(0); i >= 0; i = restriction.nextSetBit(i + 1)) { if (graph.getPredOf(i).size() == 0 || graph.getSuccOf(i).size() == 0) { nodeSCC[i] = nbSCC; sccFirstNode[nbSCC++] = i; restriction.clear(i); } } }
Source:
public static void free(ByteBuffer buffer) { try { if (buffer.isDirect()) { clean((DirectBuffer) buffer); } } START catch (Exception e) { END throw Throwables.propagate(e); } } Is try-catch needed here?

Target:
public static void free(ByteBuffer buffer) { if (buffer.isDirect()) { clean((DirectBuffer) buffer); } }
Source:
START public static Boolean isZip(String fName) END { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(ZIP_SUFFIX); // Technically a file named `.zip` would be fine } why Boolean, and not boolean?

Target:
public static boolean isZip(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(ZIP_SUFFIX); // Technically a file named `.zip` would be fine }
Source:
public static Boolean isGz(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } START return fName.endsWith(GZ_SUFFIX) && fName.length() > GZ_SUFFIX.length(); END } why is this logic different than for .zip?

Target:
public static boolean isGz(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(GZ_SUFFIX) && fName.length() > GZ_SUFFIX.length(); }
Source:
START private void addSizedFiles(Collection<File> files) END { if (files == null || files.isEmpty()) { return; } long size = 0l; for (File file : files) { size += file.length(); } this.files.addAll(files); this.size += size; } Why is this private, when addFiles does the same thing and is public?

Target:
protected void addSizedFiles(Collection<File> files) { if (files == null || files.isEmpty()) { return; } long size = 0l; for (File file : files) { size += file.length(); } this.files.addAll(files); this.size += size; }
Source:
public static void copyToFileAndClose(InputStream is, File file) throws IOException { OutputStream os = null; try { file.getParentFile().mkdirs(); os = new BufferedOutputStream(new FileOutputStream(file)); ByteStreams.copy(is, os); } finally { CloseQuietly.close(is); START CloseQuietly.close(os); END } } try with resources might be better here?

Target:
public static void copyToFileAndClose(InputStream is, File file) throws IOException { file.getParentFile().mkdirs(); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { ByteStreams.copy(is, os); } finally { CloseQuietly.close(is); } }