auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Optional<Cookie> findCookieWithName(String cookieName, HttpClient httpClient) { START Optional<Cookie> cookie = END Arrays.stream(httpClient.getState().getCookies()) .filter(c -> cookieName.equals(c.getName())) .findFirst(); return cookie; } return immediately, no need to store it in a local var

Target:
private Optional<Cookie> findCookieWithName(String cookieName, HttpClient httpClient) { return Arrays.stream(httpClient.getState().getCookies()) .filter(c -> cookieName.equals(c.getName())) .findFirst(); }
Source:
public void destroy() { // clients must be destroyed before the pools or // you will create a several second busy wait loop for (JettyHttpClient client : clients) { client.close(); } if (pool != null) { pool.close(); pool = null; START if(injector.getExistingBinding(Key.get(MBeanExporter.class)) != null) { END injector.getInstance(MBeanExporter.class) .unexport(generatedNameOf(QueuedThreadPoolMBean.class) + "_" + name); } } destroyed.set(true); } This class is effectively a provider. Instead of doing the export directly, we should bind the JMX export when we bind IO pool and let the export happen the normal way.

Target:
public void destroy() { // clients must be destroyed before the pools or // you will create a several second busy wait loop for (JettyHttpClient client : clients) { client.close(); } if (pool != null) { pool.close(); pool = null; } destroyed.set(true); }
Source:
private Set<String> expandRegionalChannelUris(String channelUri) { Set<String> expandedUris = null; if (BBC1_TXLOG_CHANNEL_URIS.contains(channelUri)) { expandedUris = BBC1_TXLOG_CHANNEL_URIS; } if (BBC2_TXLOG_CHANNEL_URIS.contains(channelUri)) { expandedUris = BBC2_TXLOG_CHANNEL_URIS; } START return expandedUris == null ? null : Sets.difference(expandedUris, ImmutableSet.of(channelUri)); END } you could do the difference and return in inside the if, and save 2 checks.

Target:
private Set<String> expandRegionalChannelUris(String channelUri) { if (BBC1_TXLOG_CHANNEL_URIS.contains(channelUri)) { return Sets.difference(BBC1_TXLOG_CHANNEL_URIS, ImmutableSet.of(channelUri)); } else if (BBC2_TXLOG_CHANNEL_URIS.contains(channelUri)) { return Sets.difference(BBC2_TXLOG_CHANNEL_URIS, ImmutableSet.of(channelUri)); } return null; }
Source:
public void testMultipleBatchesLateral_WithStreamingAgg() throws Exception { String sql = "SELECT t2.maxprice FROM (SELECT customer.c_orders AS c_orders FROM " + "dfs.`lateraljoin/multipleFiles/` customer) t1, LATERAL (SELECT CAST(MAX(t.ord.o_totalprice)" + " AS int) AS maxprice FROM UNNEST(t1.c_orders) t(ord) GROUP BY t.ord.o_orderstatus) t2"; testBuilder() .optionSettingQueriesForTestQuery("alter session set `%s` = true", START PlannerSettings.STREAMAGG.getOptionName()) END .sqlQuery(sql) .unOrdered() .baselineColumns("maxprice") .baselineValues(367190) .baselineValues(316347) .baselineValues(146610) .baselineValues(306996) .baselineValues(235695) .baselineValues(177819) .build().run(); } Should "planner.enable_hashagg" be set to **false** ? "planner.enable_streamagg" defaults to **true** anyway.

Target:
public void testMultipleBatchesLateral_WithStreamingAgg() throws Exception { String sql = "SELECT t2.maxprice FROM (SELECT customer.c_orders AS c_orders FROM " + "dfs.`lateraljoin/multipleFiles/` customer) t1, LATERAL (SELECT CAST(MAX(t.ord.o_totalprice)" + " AS int) AS maxprice FROM UNNEST(t1.c_orders) t(ord) GROUP BY t.ord.o_orderstatus) t2"; testBuilder() .sqlQuery(sql) .unOrdered() .baselineColumns("maxprice") .baselineValues(367190) .baselineValues(316347) .baselineValues(146610) .baselineValues(306996) .baselineValues(235695) .baselineValues(177819) .build().run(); }
Source:
public boolean isType(String value) { GlusterStatus volStatus = START GlusterStatus.valueOf(value); END for (GlusterStatus status : values) { if (status.equals(volStatus)) { return true; } } return false; } This might throw IllegalArgumentException in case `value` doesn't match any enum constant. It's much easier to compare `value` to name() of enum constants: for (GlusterStatus status : values) { if (status.name().equals(value)) { return true; } } return false;

Target:
public boolean isType(String value) { for (GlusterStatus status : values) { if (status.name().equals(value)) { return true; } } return false; }
Source:
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); START ctx.channel().close(); END } `ctx.close()`

Target:
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); }
Source:
START public CloseNoOpServerProtocolHandler(String websocketPath) { END super(websocketPath, null, false); } remove public

Target:
CloseNoOpServerProtocolHandler(String websocketPath) { super(websocketPath, null, false); }
Source:
public MessageView(Context context, AttributeSet attrs) { super(context, attrs); START setOrientation(VERTICAL); END } Since you are forcing the orientation, it might be a good idea to use the `super.setOrientation()` instead, override the `setOrientation()` method and only print a log or throw an exception if someone tries to mess with it

Target:
public MessageView(Context context, AttributeSet attrs) { super(context, attrs); super.setOrientation(VERTICAL); }
Source:
public Canvas addShapeIntoView(final Shape shape) { if (shape.getUUID() == null) { shape.setUUID(UUID.uuid()); } START shape.getShapeView().setUUID(shape.getUUID()); END getView().add(shape.getShapeView()); return this; } Shouldn't it be a part of `shape#setUUID` method?

Target:
public Canvas addShapeIntoView(final Shape shape) { if (shape.getUUID() == null) { shape.setUUID(UUID.uuid()); } getView().add(shape.getShapeView()); return this; }
Source:
public boolean getRequiredParamBoolean(final String key) throws ActionParamsException { START final String errMsg = "Required parameter '" + key + "' missing!"; END final String val = getRequiredParam(key, errMsg); try { return Boolean.parseBoolean(val); } catch (Exception e) { throw new ActionParamsException(errMsg); } } You don't need to give this string (even as other similar do) since it's the default message for getRequiredParam(key).

Target:
public boolean getRequiredParamBoolean(final String key) throws ActionParamsException { final String val = getRequiredParam(key); try { return Boolean.parseBoolean(val); } catch (Exception e) { throw new ActionParamsException(e.getMessage()); } }
Source:
public void onPingFromClient(PingFromClientEvent event, EntityRef entity){ START if (networkSystem.getMode().isServer()) { END Instant end = Instant.now(); endMap.put(entity, end); updatePing(entity); } } In the `@ReceiveEvent` annotation and in the `@RegisterSystem` annotation you can specify if a event handler / all event handlers of that class are for a server or client. So you don't need to check the mode of networkSystem.

Target:
public void onPingFromClient(PingFromClientEvent event, EntityRef entity) { Instant end = Instant.now(); endMap.put(entity, end); updatePing(entity); }
Source:
public boolean areEqual(MapObject o1, MapObject o2) { if (o1 == null ^ o2 == null) { return false; START } else if (o1 == o2) { END return true; } else { return o1.id.equals(o2.id); } } This block is useless.

Target:
public boolean areEqual(MapObject o1, MapObject o2) { if (o1 == null) { return o2 == null; } else { return o1.id.equals(o2.id); } }
Source:
public RedisMetadataStore(RedisConnectionFactory connectionFactory) { Assert.notNull(connectionFactory, "'connectionFactory' must not be null."); this.redisTemplate = new StringRedisTemplate(connectionFactory); START this.redisTemplate.afterPropertiesSet(); END } `StringRedisTemplate` constructor takes care of it.

Target:
public RedisMetadataStore(RedisConnectionFactory connectionFactory) { Assert.notNull(connectionFactory, "'connectionFactory' must not be null."); this.redisTemplate = new StringRedisTemplate(connectionFactory); }
Source:
public CompleteTransactionMessage(long initiatorHSId, long coordinatorHSId, long txnId, boolean isReadOnly, int hash, boolean isRollback, boolean requiresAck, boolean isRestart, boolean isForReplay) { super(initiatorHSId, coordinatorHSId, txnId, 0, isReadOnly, isForReplay); m_hash = hash; setBit(ISROLLBACK, isRollback); setBit(REQUIRESACK, requiresAck); setBit(ISRESTART, isRestart); START m_toLeader = false; END m_ackRequestedFromSender = true; } Can you use the inherited "m_isLeaderToReplica" instead of adding a new "m_toLeader"? The message is either from leader to replica or from MPI to leader?

Target:
public CompleteTransactionMessage(long initiatorHSId, long coordinatorHSId, long txnId, boolean isReadOnly, int hash, boolean isRollback, boolean requiresAck, boolean isRestart, boolean isForReplay) { super(initiatorHSId, coordinatorHSId, txnId, 0, isReadOnly, isForReplay); m_hash = hash; setBit(ISROLLBACK, isRollback); setBit(REQUIRESACK, requiresAck); setBit(ISRESTART, isRestart); }
Source:
private CuEinvoiceDao getCuEinvoiceDao() { START if (ObjectUtils.isNull(null)) { END cuEinvoiceDao = SpringContext.getBean(CuEinvoiceDaoOjb.class); } return cuEinvoiceDao; } This will always return true, did you want cuEinvoiceDao instead of null here

Target:
private CuEinvoiceDao getCuEinvoiceDao() { if (ObjectUtils.isNull(cuEinvoiceDao)) { cuEinvoiceDao = SpringContext.getBean(CuEinvoiceDaoOjb.class); } return cuEinvoiceDao; }
Source:
START public static EchoTagStatementTree newEchoTagStatement(ExpressionTree expression, InternalSyntaxToken eosToken) { END SeparatedList<ExpressionTree> expressionList = new SeparatedListImpl(Collections.singletonList(expression), Collections.emptyList()); return newEchoTagStatement(expressionList, eosToken); } Can we make this method private?

Target:
private static EchoTagStatementTree newEchoTagStatement(ExpressionTree expression, InternalSyntaxToken eosToken) { SeparatedList<ExpressionTree> expressionList = new SeparatedListImpl<>(Collections.singletonList(expression), Collections.emptyList()); return newEchoTagStatement(expressionList, eosToken); }
Source:
private static TextSummarizer getLocalSummarizer() throws IOException { Collection<? extends TextSummarizer> summarizers = Lookup.getDefault().lookupAll(TextSummarizer.class ); if (!summarizers.isEmpty()) { summarizerToUse = summarizers.iterator().next(); return summarizerToUse; } START throw new IOException("No summarizers found"); END } Perhaps it would be better to return null instead of throwing an exception? Nothing has really gone wrong. And then you wouldn't need that empty catch block.

Target:
private static TextSummarizer getLocalSummarizer() { Collection<? extends TextSummarizer> summarizers = Lookup.getDefault().lookupAll(TextSummarizer.class ); if (!summarizers.isEmpty()) { summarizerToUse = summarizers.iterator().next(); return summarizerToUse; } return null; }
Source:
public void verifyNoVideo() { if(checkIfElementOnPage(mediaNode)) START throw new AssertionError("Media Node is still on the page"); END else PageObjectLogging.log("verifyNoVideo", "Verified no video is on page", true, driver); } could you please put it in brackets to make it easier to read?

Target:
public void verifyNoVideo() { if(checkIfElementOnPage(mediaNode)) { throw new AssertionError("Media Node is still on the page"); } else { PageObjectLogging.log("verifyNoVideo", "Verified no video is on page", true, driver); } }
Source:
private void startOrStopGeoDataListener() { if (requireGeodata) { START geoDataSubscription = locationUpdater.start(GeoDirHandler.UPDATE_GEODATA); END } else { geoDataSubscription.unsubscribe(); } } Is it save to assign a new subscription here without unsubscribing a potentially existing previous subscription? Or to ask different: Can you guarantee this is not called two times in a row in the activity lifecycle with requireGeodata==true?

Target:
private void startOrStopGeoDataListener() { geoDataSubscription.unsubscribe(); if (requireGeodata) { geoDataSubscription = locationUpdater.start(GeoDirHandler.UPDATE_GEODATA); } }
Source:
ZipFormatter( START Formatters formatters, END FormatterUtil formatterUtil, HtmlBuilder html) { this.formatters = formatters; this.util = formatterUtil; this.html = html; } not needed.

Target:
ZipFormatter( Formatters formatters, FormatterUtil formatterUtil, HtmlBuilder html) { this.util = formatterUtil; this.html = html; }
Source:
private boolean clusterHasPpcArchitecture() { Cluster cluster = getModel().getSelectedCluster(); return cluster != null && cluster.getArchitecture() != null START && ArchitectureType.ppc.getFamily() == cluster.getArchitecture().getFamily(); END } I think I saw multiple ppc types in the enum: ppc, ppc64, ppcle, ppc64le

Target:
private boolean clusterHasPpcArchitecture() { Cluster cluster = getModel().getSelectedCluster(); return cluster != null && cluster.getArchitecture() != null && ArchitectureType.ppc == cluster.getArchitecture().getFamily(); }
Source:
START protected void createIndex(Connection conn, String indexExt, String columnName) throws PersistenceException { END if (metaData.isIndexingDisabled()) return; boolean indexExists = indexExists(getIndexName(false, indexExt), conn); if (!indexExists) { String ddl = String.format("CREATE INDEX %s ON %s (%s)", getIndexName(true, indexExt), getTableName(), columnName); if (log.isTraceEnabled()) { log.tracef("Adding index with following DDL: '%s'.", ddl); } executeUpdateSql(conn, ddl); } } We can make this private

Target:
private void createIndex(Connection conn, String indexExt, String columnName) throws PersistenceException { if (metaData.isIndexingDisabled()) return; boolean indexExists = indexExists(getIndexName(false, indexExt), conn); if (!indexExists) { String ddl = String.format("CREATE INDEX %s ON %s (%s)", getIndexName(true, indexExt), getTableName(), columnName); if (log.isTraceEnabled()) { log.tracef("Adding index with following DDL: '%s'.", ddl); } executeUpdateSql(conn, ddl); } }
Source:
public Object getValue() { START if (value == null) { END return null; } else { return value; } } This should be simplified to just: >return value;

Target:
public Object getValue() { return value; }
Source:
private boolean needProjectionNode (AbstractPlanNode root) { START if ( false == root.planNodeClassNeedsProjectionNode()) { END return false; } // If there is a complexGroupby at his point, it means that // display columns contain all the order by columns and // does not require another projection node on top of sort node. // If there is a complex aggregation case, the projection plan node is already added // right above the group by plan node. In future, we may inline that projection node. if (m_parsedSelect.hasComplexGroupby() || m_parsedSelect.hasComplexAgg()) { return false; } if (root instanceof AbstractReceivePlanNode && m_parsedSelect.hasPartitionColumnInGroupby()) { // Top aggregate has been removed, its schema is exactly the same to // its local aggregate node. return false; } return true; } `false ==` is a peculiar way to express `!`. BTW, `peculiar` is a polite way to say `wrong`.

Target:
private boolean needProjectionNode (AbstractPlanNode root) { if (!root.planNodeClassNeedsProjectionNode()) { return false; } // If there is a complexGroupby at his point, it means that // display columns contain all the order by columns and // does not require another projection node on top of sort node. // If there is a complex aggregation case, the projection plan node is already added // right above the group by plan node. In future, we may inline that projection node. if (m_parsedSelect.hasComplexGroupby() || m_parsedSelect.hasComplexAgg()) { return false; } if (root instanceof AbstractReceivePlanNode && m_parsedSelect.hasPartitionColumnInGroupby()) { // Top aggregate has been removed, its schema is exactly the same to // its local aggregate node. return false; } return true; }
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 please

Target:
public void isExecutable_HeaderCellSelected() { when(scenarioGridModelMock.getSelectedCells()).thenReturn(Collections.emptyList()); when(scenarioGridModelMock.getSelectedHeaderCells()).thenReturn(Arrays.asList(selectedCell, selectedCell2)); assertTrue(handler.isExecutable(scenarioGridMock)); }
Source:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof XarSecurityRule)) { return false; } XarSecurityRule rhs = (XarSecurityRule) object; return new EqualsBuilder() .append(this.right, rhs.right) .append(this.simple, rhs.simple) START .append(this.securityTool, rhs.securityTool) END .isEquals(); } This is not really relevant IMO. It's not data of that rules, just an internal helper. In practice this is always going to be true anyway since it's a singleton component.

Target:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof XarSecurityRule)) { return false; } XarSecurityRule rhs = (XarSecurityRule) object; return new EqualsBuilder() .append(this.right, rhs.right) .append(this.simple, rhs.simple) .isEquals(); }
Source:
public static boolean containsSearchAnnotations(XClass mappedClass) { START List<XClass> hierarchy = ReflectionHelper.createXClassHierarchy( mappedClass ); END for ( XClass clazz : hierarchy ) { if ( containsLocalSearchAnnotation( clazz ) ) { return true; } } return false; } Any reason why you added `ReflectionHelper.`? Might as well remove it so that we see it's a method of this very class?

Target:
public static boolean containsSearchAnnotations(XClass mappedClass) { List<XClass> hierarchy = createXClassHierarchy( mappedClass ); for ( XClass clazz : hierarchy ) { if ( containsLocalSearchAnnotation( clazz ) ) { return true; } } return false; }
Source:
private static int computeNewVectorCapacity(int usedCapacity, int newPayload, int currentCapacity) { int newUsedCapacity = BaseAllocator.nextPowerOfTwo(usedCapacity + newPayload); assert newUsedCapacity >= 0; START return newUsedCapacity <= currentCapacity ? currentCapacity : newUsedCapacity; END } `Math.max(newUsedCapacity, currentCapacity)` would be a little bit clearer here.

Target:
private static int computeNewVectorCapacity(int usedCapacity, int newPayload, int currentCapacity) { int newUsedCapacity = BaseAllocator.nextPowerOfTwo(usedCapacity + newPayload); assert newUsedCapacity >= 0; return Math.max(currentCapacity, newUsedCapacity); }
Source:
private static void cleanShutdown() { log.info("CleanShutdown: Starting Cleanup."); shutdownServer = true; try { CorfuServerNode current = activeServer; if (current != null) { activeServer.close(); } } catch (Throwable th) { log.error("cleanShutdown: failed during shutdown", th); } // Flush the async appender before exiting to prevent the loss of logs START LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); END loggerContext.stop(); } This doesn't help at all, I suspect it can even cause loss of the logs. Logback already have solved the problem, and we have it enabled https://github.com/CorfuDB/CorfuDB/blob/30c8d154f59dfe22d4cc16b94ab9e2c51851c2e5/infrastructure/src/main/resources/logback.prod.xml#L5

Target:
private static void cleanShutdown() { log.info("CleanShutdown: Starting Cleanup."); shutdownServer = true; try { CorfuServerNode current = activeServer; if (current != null) { current.close(); } } catch (Throwable th) { log.error("cleanShutdown: failed during shutdown", th); } // Flush the async appender before exiting to prevent the loss of logs LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.stop(); }
Source:
public void preInit(FMLPreInitializationEvent event) { START Log.setModLog(event.getModLog()); END configDir = new File(event.getModConfigurationDirectory(), "antiqueatlas"); configDir.mkdir(); extTileIdMap = ExtTileIdMap.instance(); extTileConfig = new ExtTileConfig(new File(configDir, "tileids.json")); extTileConfig.load(extTileIdMap); // Assign default values AFTER the config file loads, so that the old saved values are kept: registerVanillaCustomTiles(); checkSaveConfig(); } As I said in the last PR (https://github.com/AntiqueAtlasTeam/AntiqueAtlas/pull/205) that did something like this, this should use `LogManager.getLogger(...)`. Honestly, `Log#modLog` should just be changed to ```java private static final Logger LOGGER = LogManager.getLogger(AntiqueAtlasMod.ID); ```

Target:
public void preInit(FMLPreInitializationEvent event) { configDir = new File(event.getModConfigurationDirectory(), "antiqueatlas"); configDir.mkdir(); extTileIdMap = ExtTileIdMap.instance(); extTileConfig = new ExtTileConfig(new File(configDir, "tileids.json")); extTileConfig.load(extTileIdMap); // Assign default values AFTER the config file loads, so that the old saved values are kept: registerVanillaCustomTiles(); checkSaveConfig(); }
Source:
public void close() { try { if (this.readingRaw.get() && !finalizeRaw() && LOGGER.isWarnEnabled()) { LOGGER.warn("Finalize on readRaw() returned false for " + this); } START if (this.client.isConnected()) END this.client.logout(); this.client.disconnect(); } catch (Exception e) { LOGGER.warn("failed to disconnect FTPClient", e); } } Checkstyle violation: ``` [ant:checkstyle] [ERROR] /home/travis/build/spring-projects/spring-integration/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/FtpSession.java:157: 'if' construct must use '{}'s. [NeedBraces] ``` You can verify yourself locally using `gradlew clean :spring-integration-ftp:check`

Target:
public void close() { try { if (this.readingRaw.get() && !finalizeRaw() && LOGGER.isWarnEnabled()) { LOGGER.warn("Finalize on readRaw() returned false for " + this); } if (this.client.isConnected()) { this.client.logout(); } this.client.disconnect(); } catch (Exception e) { LOGGER.warn("failed to disconnect FTPClient", e); } }
Source:
protected FileType doGetType() throws Exception { START return (this.stat == null) ? FileType.IMAGINARY : FileType.FILE_OR_FOLDER; END } No extra (clutter) please.

Target:
protected FileType doGetType() throws Exception { return this.stat == null ? FileType.IMAGINARY : FileType.FILE_OR_FOLDER; }
Source:
public EquivalentHashMap( int initialCapacity, float loadFactor, Equivalence<K> keyEq, Equivalence<V> valueEq) { int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; this.loadFactor = loadFactor; START threshold = (int)(capacity * DEFAULT_LOAD_FACTOR); END table = new Node[capacity]; this.keyEq = keyEq; this.valueEq = valueEq; } `capacity * loadFactor` maybe?

Target:
public EquivalentHashMap( int initialCapacity, float loadFactor, Equivalence<K> keyEq, Equivalence<V> valueEq) { int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; this.loadFactor = loadFactor; threshold = (int)(capacity * loadFactor); table = new Node[capacity]; this.keyEq = keyEq; this.valueEq = valueEq; }
Source:
START private void mockSSHClient() { END try { doNothing().when(sshclient).connect(); doNothing().when(sshclient).authenticate(); } catch(Exception e) } just throw the exception upwards..

Target:
private void mockSSHClient() { try { doNothing().when(sshclient).connect(); doNothing().when(sshclient).authenticate(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public static String sanitizeKey(final Contentlet vanityUrl) START throws DotDataException, DotRuntimeException, DotSecurityException { END Host host = hostAPI.find(vanityUrl.getStringProperty(VanityUrlContentType.SITE_FIELD_VAR), APILocator.systemUser(), false); return sanitizeKey(host.getIdentifier(), fixURI(vanityUrl.getStringProperty(VanityUrlContentType.URI_FIELD_VAR)), vanityUrl.getLanguageId()); } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove the redundant '!unknownSymbol!' thrown exception declaration(s). [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3ARedundantThrowsDeclarationCheck)

Target:
public static String sanitizeKey(final Contentlet vanityUrl) throws DotDataException, DotSecurityException { Host host = hostAPI.find(vanityUrl.getStringProperty(VanityUrlContentType.SITE_FIELD_VAR), APILocator.systemUser(), false); return sanitizeKey(host.getIdentifier(), fixURI(vanityUrl.getStringProperty(VanityUrlContentType.URI_FIELD_VAR)), vanityUrl.getLanguageId()); }
Source:
protected void dataTemplateToJsonGenerator(Object data, DataSchema schema, JsonGenerator generator, boolean order) throws IOException { if (order) { JacksonTraverseCallback callback = new SchemaOrderTraverseCallback(schema, generator); Data.traverse(data, callback); } else { START objectToJsonGenerator(data, generator, false); END } } You can revert this change now.

Target:
protected void dataTemplateToJsonGenerator(Object data, DataSchema schema, JsonGenerator generator, boolean order) throws IOException { if (order) { JacksonTraverseCallback callback = new SchemaOrderTraverseCallback(schema, generator); Data.traverse(data, callback); } else { objectToJsonGenerator(data, generator); } }
Source:
START public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { END ListResponse<KubernetesSupportedVersionResponse> response = kubernetesVersionService.listKubernetesSupportedVersions(this); response.setResponseName(getCommandName()); setResponseObject(response); } these exceptions are unacceptable (intended pun miserably failed) we are listing clusters, no resource-, allocation-, or any change related exception should ever occur. at most a entity not found kind of thing.

Target:
public void execute() throws ServerApiException, ConcurrentOperationException { ListResponse<KubernetesSupportedVersionResponse> response = kubernetesVersionService.listKubernetesSupportedVersions(this); response.setResponseName(getCommandName()); setResponseObject(response); }
Source:
public void loggedInUserPropertyFalseTest() throws Exception { START context.turnOffAuthorisationSystem(); END configurationService.setProperty("webui.user.assumelogin", false); context.restoreAuthSystemState(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/authn/status") .header("X-On-Behalf-Of", eperson.getID())) .andExpect(status().isBadRequest()); context.turnOffAuthorisationSystem(); configurationService.setProperty("webui.user.assumelogin", true); context.restoreAuthSystemState(); } the turnOff is not really needed

Target:
public void loggedInUserPropertyFalseTest() throws Exception { configurationService.setProperty("webui.user.assumelogin", false); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/authn/status") .header("X-On-Behalf-Of", eperson.getID())) .andExpect(status().isBadRequest()); }
Source:
protected void addExtraHeaders(Builder webResource) { if (additionalHeaders != null) { START for (String key : additionalHeaders.keySet()) { END webResource.header(key, additionalHeaders.get(key)); } } } Could use an entrySet.

Target:
protected void addExtraHeaders(Builder webResource) { if (additionalHeaders != null) { for (Map.Entry<String, List<Object>> entry: additionalHeaders.entrySet()) { webResource.header(entry.getKey(), entry.getValue()); } } }
Source:
private boolean hasNewFragment(EList<InteractionFragment> currentList, List<InteractionFragment> newList) { START boolean newFragment = false; if (newList.size() > currentList.size()) { newFragment = true; } return newFragment; END } I think return (newList.size() > currentList.size()) is sufficient

Target:
private boolean hasNewFragment(EList<InteractionFragment> currentList, List<InteractionFragment> newList) { return (newList.size() > currentList.size()); }
Source:
void closeResultSets() throws SQLException { closeResultSets(activeResultSets); START END if (generatedKeysResultSet != null && !generatedKeysResultSet.isClosed()) { generatedKeysResultSet.internalClose(); } generatedKeysResultSet = null; } This is unnecessary as generatedKeysResultSet is added to activeResultSets when created

Target:
void closeResultSets() throws SQLException { closeResultSets(activeResultSets); generatedKeysResultSet = null; }
Source:
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.apache.jasper.compiler.JspConfig", classLoader)) { try { String resourceName = getResourceName(view, environment); if (resourceLoader.getResource(resourceName).exists()) { return true; } START return new File("src/main/webapp", resourceName).exists(); END } catch (AccessControlException ex) { return false; } } return false; } The scope of this `try` block is broader than necessary. It only needs to contain this line.

Target:
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.apache.jasper.compiler.JspConfig", classLoader)) { String resourceName = getResourceName(view, environment); if (resourceLoader.getResource(resourceName).exists()) { return true; } try { return new File("src/main/webapp", resourceName).exists(); } catch (AccessControlException ex) { } } return false; }
Source:
START public Object visit(final AntlrBaseNode node) { END return node.accept(this); } Why does this return Object instead of T ?

Target:
public T visit(final AntlrBaseNode node) { return node.accept(this); }
Source:
public static void addDiskToVm(BaseDisk disk, Guid vmId) { DbFacade.getInstance().getBaseDiskDao().save(disk); VmDeviceUtils.addManagedDevice(new VmDeviceId(disk.getId(), vmId), VmDeviceType.DISK, VmDeviceType.DISK, null, true, false, START ""); END } please remove alias setting (should be encapsulated in addManagedDevice

Target:
public static void addDiskToVm(BaseDisk disk, Guid vmId) { DbFacade.getInstance().getBaseDiskDao().save(disk); VmDeviceUtils.addManagedDevice(new VmDeviceId(disk.getId(), vmId), VmDeviceType.DISK, VmDeviceType.DISK, null, true, false); }
Source:
private static Throwable getConfigFailureException(ITestContext context) { Throwable t = null; for (IInvokedMethod method : context.getSuite().getAllInvokedMethods()) { ITestNGMethod m = method.getTestMethod(); if (m.isBeforeSuiteConfiguration() && (!method.getTestResult().isSuccess())) { START t = method.getTestResult().getThrowable(); END break; } } return t; } return here

Target:
private static Throwable getConfigFailureException(ITestContext context) { for (IInvokedMethod method : context.getSuite().getAllInvokedMethods()) { ITestNGMethod m = method.getTestMethod(); if (m.isBeforeSuiteConfiguration() && (!method.getTestResult().isSuccess())) { return method.getTestResult().getThrowable(); } } return null; }
Source:
protected String toString(Operator operator) { START if (Operator.STARTSWITH.equals(operator)) return LIKE; END return operator.toString(); } I recommend adding `{}` here

Target:
protected String toString(Operator operator) { if (Operator.STARTSWITH.equals(operator)) { return LIKE; } return operator.toString(); }
Source:
START static UberDocument toUberDocument(final Object object) { END if (object == null) { return null; } if (object instanceof UberDocument) { return (UberDocument) object; } if (object instanceof Iterable) { } else if (object instanceof Map) { } throw new IllegalArgumentException("Don't know how to handle type : " + object.getClass()); } This looks like a leftover and it hasn't any usage. Can we remove it?

Target:
static UberDocument toUberDocument(final Object object) { if (object == null) { return null; } if (object instanceof UberDocument) { return (UberDocument) object; } throw new IllegalArgumentException("Don't know how to handle type : " + object.getClass()); }
Source:
START public ArgumentSplitter(String arguments) { END this.arguments = arguments; } There is no point exposing this constructor if there is not even a single public method. All methods are private (except for the static, which does not require a constructor to be used)

Target:
private ArgumentSplitter(String arguments) { this.arguments = arguments; }
Source:
public LgoProducts getProducts() { LgoProducts products = null; try { products = this.proxy.getProducts( exchange.getNonceFactory().createValue(), exchange.getSignatureService()); START } catch (HttpStatusIOException e) { END LgoErrorAdapter.adapt(e); } return products; } please improve error handling in accordance to: https://github.com/knowm/XChange/wiki/New-Implementation-Best-Practices#step-7 you should introduce and LgoException that implements HttpStatusExceptionSupport try catch adapt should be done in methods that implement generic interfaces, *Raw methods should throw our the LgoException

Target:
public LgoProducts getProducts() throws IOException { return this.proxy.getProducts( exchange.getNonceFactory().createValue(), exchange.getSignatureService()); }
Source:
protected void addAttachmentToNote(T document, AccountingXmlDocumentBackupLink backupLink, Note note) { try { Attachment attachment = accountingXmlDocumentDownloadAttachmentService.createAttachmentFromBackupLink(document, backupLink); note.setAttachment(attachment); } catch (IOException e) { LOG.error("addAttachmentToNote, unable to create attachment: " + e.getMessage()); String message = MessageFormat.format( configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_CREATE_ACCOUNTING_DOCUMENT_ATTACHMENT_DOWNLOAD), START KFSConstants.BLANK_SPACE + backupLink.getLinkUrl()); END throw new ValidationException(message); } } Do you still need to prepend the blank space, now that you're using MessageFormat.format()? If not, then you should be able to simplify this a little further.

Target:
protected void addAttachmentToNote(T document, AccountingXmlDocumentBackupLink backupLink, Note note) { try { Attachment attachment = accountingXmlDocumentDownloadAttachmentService.createAttachmentFromBackupLink(document, backupLink); note.setAttachment(attachment); } catch (IOException e) { LOG.error("addAttachmentToNote, unable to create attachment: " + e.getMessage()); String message = MessageFormat.format( configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_CREATE_ACCOUNTING_DOCUMENT_ATTACHMENT_DOWNLOAD), backupLink.getLinkUrl()); throw new ValidationException(message); } }
Source:
public Void getResult() { START throw new UnsupportedOperationException(getClass().getName()); END } This is effectively final class, so just `throw new UnsupportedOperationException()`

Target:
public Void getResult() { throw new UnsupportedOperationException(); }
Source:
public PlanWithProperties visitUnnest(UnnestNode node, PreferredProperties preferredProperties) { PreferredProperties translatedPreferred = preferredProperties.translate(variable -> { START checkArgument(variable instanceof VariableReferenceExpression, "Expect VariableReferenceExpression"); END return node.getReplicateVariables().contains(variable) ? Optional.of(variable) : Optional.empty(); }); return rebaseAndDeriveProperties(node, planChild(node, translatedPreferred)); } Please add the actual type, just in case it ever fails

Target:
public PlanWithProperties visitUnnest(UnnestNode node, PreferredProperties preferredProperties) { PreferredProperties translatedPreferred = preferredProperties.translate(variable -> node.getReplicateVariables().contains(variable) ? Optional.of(variable) : Optional.empty()); return rebaseAndDeriveProperties(node, planChild(node, translatedPreferred)); }
Source:
public ValidationResult isAnyDomainInProcess() { List<StoragePoolIsoMap> poolIsoMaps = getStoragePoolIsoMapDao().getAllForStoragePool(storagePool.getId()); for (StoragePoolIsoMap domainIsoMap : poolIsoMaps) { if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, START String.format("$status %1$s", StorageDomainStatus.Locked)); END } } return ValidationResult.VALID; } please put the correct status.

Target:
public ValidationResult isAnyDomainInProcess() { List<StoragePoolIsoMap> poolIsoMaps = getStoragePoolIsoMapDao().getAllForStoragePool(storagePool.getId()); for (StoragePoolIsoMap domainIsoMap : poolIsoMaps) { if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$status %1$s", domainIsoMap.getStatus())); } } return ValidationResult.VALID; }
Source:
START private boolean isFunctionNameMatch(RowExpression rowExpression, String expectedName) END { if (castToExpression(rowExpression) instanceof FunctionCall) { return ((FunctionCall) castToExpression(rowExpression)).getName().toString().equalsIgnoreCase(expectedName); } return false; } static

Target:
private static boolean isFunctionNameMatch(RowExpression rowExpression, String expectedName) { if (castToExpression(rowExpression) instanceof FunctionCall) { return ((FunctionCall) castToExpression(rowExpression)).getName().toString().equalsIgnoreCase(expectedName); } return false; }
Source:
public boolean hasError() { START return result != null && result.getType() != null && CommandResult.Type.ERROR.equals(result.getType()); END } We can slightly simplify: ```java return result != null && Objects.equals(CommandResult.Type.ERROR, result.getType()); ```

Target:
public boolean hasError() { return result != null && CommandResult.Type.ERROR.equals(result.getType()); }
Source:
private void setupVdsNetworkInterfaceDao() { when(getDbFacadeMockInstance().getInterfaceDao()).thenReturn(vdsNetworkInterfaceDaoMock); List<VdsNetworkInterface> expectedVdsNetworkInterface = Collections.singletonList(vdsNetworkInterface); when(vdsNetworkInterfaceDaoMock.getVdsInterfacesByNetworkId(networkId)).thenReturn( START expectedVdsNetworkInterface); END } Why did you have to change the order of the lines here?...

Target:
private void setupVdsNetworkInterfaceDao() { List<VdsNetworkInterface> expectedVdsNetworkInterface = Collections.singletonList(vdsNetworkInterface); when(vdsNetworkInterfaceDaoMock.getVdsInterfacesByNetworkId(networkId)).thenReturn( expectedVdsNetworkInterface); when(getDbFacadeMockInstance().getInterfaceDao()).thenReturn(vdsNetworkInterfaceDaoMock); }
Source:
START public void setProject(IProject project) { END this.project=project; } Do we need this method public ? The place where it's used is in the same package so protected/default should work ?

Target:
protected void setProject(IProject project) { this.project=project; }
Source:
public List<String> values(String name) { START return headers == null ? null : headers.get("Request-Id"); END } I think this should be `headers.get(name)`.

Target:
public List<String> values(String name) { return headers == null ? null : headers.get(name); }
Source:
START @Override protected Pair<Recipients, Boolean> doInBackground(Recipients... recipients) { END Capability textCapability = DirectoryHelper.getUserCapabilities(context, recipients[0]).getTextCapability(); return new Pair<>(recipients[0], textCapability == Capability.SUPPORTED); } dude

Target:
protected Pair<Recipients, Boolean> doInBackground(Recipients... recipients) { Capability textCapability = DirectoryHelper.getUserCapabilities(context, recipients[0]).getTextCapability(); return new Pair<>(recipients[0], textCapability == Capability.SUPPORTED); }
Source:
public void cleanup() { START myIdeFrame = END null; myNavigationHelper.cleanup(); myNavigationHelper = null; myStateComponent = null; myTaskContext = null; } Generally speaking, there's no need to null out the fields of an object if no one is going to hold the reference to the object afterwards. The GC is going to do its job, you don't need to help. :)

Target:
public void cleanup() { myNavigationHelper.cleanup(); }
Source:
START public static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { END DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } // If provided time is after the given issue instant, // modify it to include the issue instant if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; } Why is this public?

Target:
private static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } // If provided time is after the given issue instant, // modify it to include the issue instant if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; }
Source:
private void START setupRestrictedNotification() END { final Resources res = getResources(mContext, mActiveDataSubId); final String title = res.getString(R.string.disable_tether_notification_title); final String message = res.getString(R.string.disable_tether_notification_message); showNotification(R.drawable.stat_sys_tether_general, title, message, ""); } We do not have synchronized protection inside this function, If you would like to protect mUpdateLock from outside of this function, I think you may need to add a note to remind caller in the future to remember protect it.

Target:
void setupRestrictedNotification() { final Resources res = getResources(mContext, mActiveDataSubId); final String title = res.getString(R.string.disable_tether_notification_title); final String message = res.getString(R.string.disable_tether_notification_message); showNotification(R.drawable.stat_sys_tether_general, title, message, ""); }
Source:
START private File getFeatureTypeDir( END File featureTypesBaseDir, String namespacePrefix, String typeName) { return new File(featureTypesBaseDir, getDataStoreName(namespacePrefix, typeName)); } Any specific reason to make this method no ``static`` anymore ?

Target:
protected File getFeatureTypeDir( File featureTypesBaseDir, String namespacePrefix, String typeName) { return new File(featureTypesBaseDir, getDataStoreName(namespacePrefix, typeName)); }
Source:
public static void setupSystemProperties() { START int freePort = TestUtilGit.findFreePort(); END System.setProperty("org.uberfire.nio.git.daemon.port", String.valueOf(freePort)); logger.info("Git port used:{}", freePort); //These are not needed for the tests System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); System.setProperty("org.uberfire.sys.repo.monitor.disabled", "true"); } Just a note about consistency: does it make any sense to find free port and set system property if you're setting `org.uberfire.nio.git.daemon.enabled=false` on the lines below that?

Target:
public static void setupSystemProperties() { //These are not needed for the tests System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); System.setProperty("org.uberfire.sys.repo.monitor.disabled", "true"); }
Source:
public void setPreferredAgencies(String s) { if (s != null && !s.equals("")) START preferredAgencies = Sets.newHashSet(s.split(",")); END } "This method is not actually very useful and will likely be deprecated in the future."

Target:
public void setPreferredAgencies(String s) { if (!s.isEmpty()) { preferredAgencies = new HashSet<>(); Collections.addAll(preferredAgencies, s.split(",")); } }
Source:
synchronized void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { START log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); END subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}updating builder with topic(s) with possible matching regex subscription(s)", logPrefix, subscriptionUpdates.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); } Thanks for the PR! I just noticed these two log messages are completely redundant; can we remove one of them, or combine into a single log?

Target:
synchronized void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); }
Source:
public void releaseCursor(Cursor cursor) { try { cursor.release(); if (cursors.remove(cursor)) { START if (provider.isClosed() && cursors.isEmpty()) { END releaseResources(); } } } catch (Exception e) { LOGGER.warn("Exception was found trying to release cursor resources. Execution will continue", e); } finally { statistics.decrementOpenCursors(); } } why not put this with an `&&` in the previous `if`?

Target:
public void releaseCursor(Cursor cursor) { try { cursor.release(); if (cursors.remove(cursor) && provider.isClosed() && cursors.isEmpty()) { releaseResources(); } } catch (Exception e) { LOGGER.warn("Exception was found trying to release cursor resources. Execution will continue", e); } finally { statistics.decrementOpenCursors(); } }
Source:
protected void doStop() { START autoEncryptionSupport.close(); END super.doStop(); LDAPCache.clear(); } Check for null missing?

Target:
protected void doStop() { if (autoEncryptionSupport != null) { autoEncryptionSupport.close(); } super.doStop(); LDAPCache.clear(); }
Source:
START private Now(A a) { END this.a = a; } make the constructor package private instead of private to avoid going through a generated synthetic constructor.

Target:
Now(A a) { this.a = a; }
Source:
private String getWorkspaceRelativePath(String sourcePath) { if (org.apache.commons.lang.StringUtils.isBlank(sourcePath) || sourcePath.contains("{")) { return sourcePath; } IPath absolutePath = new Path(sourcePath); IContainer container = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(absolutePath); if (container != null) { START return container.getFullPath().toPortableString(); END } return null; } I am not sure that toPortableString() is preferred here to just toString(). IPath.toString() makes only separator '/' for all platforms and it is what we need. Docs say that if toPortableString() is used it has to be matched with fromPortableString() when converting back to Path. toPortableString() doubles all ':' after the one that belongs to the device part (for Windows). For example "c:\one\two:x" will be transformed into "c://one/two::x". If segments have no ':' symbols, then there is no difference from toString(). However if a segment has ':' symbol, fromPortableString() is necessary to restore the original path, even for Linux.

Target:
private String getWorkspaceRelativePath(String sourcePath) { if (org.apache.commons.lang.StringUtils.isBlank(sourcePath) || sourcePath.contains("{")) { return sourcePath; } IPath absolutePath = new Path(sourcePath); IContainer container = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(absolutePath); if (container != null) { return container.getFullPath().toString(); } return null; }
Source:
private void buildErrataDetailPanel() { errataDetailPanel.clear(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); START errataDetailPanel.setStyleName("testtest"); //$NON-NLS-1$ END errataDetailPanel.add(errataDetailFormPanel); } style name wrong? should use the style.something()?

Target:
private void buildErrataDetailPanel() { errataDetailPanel.clear(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); errataDetailPanel.add(errataDetailFormPanel); }