auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private int readStreamToStrBuffer(int length) throws IOException { if (length > strBuffer.length - strBufferIndex) { expandStrBuffer(length); } int bytesRead = inputStream.read(strBuffer, strBufferIndex, Math.min(length, strBuffer.length - strBufferIndex)); if (bytesRead < 0) { throw new IOException("Reached end of stream."); } strBufferIndex += bytesRead; START System.out.println(bytesRead); END return bytesRead; } rm the println

Target:
private int readStreamToStrBuffer(int length) throws IOException { if (length > strBuffer.length - strBufferIndex) { expandStrBuffer(length); } int bytesRead = inputStream.read(strBuffer, strBufferIndex, Math.min(length, strBuffer.length - strBufferIndex)); if (bytesRead < 0) { throw new IOException("Reached end of stream."); } strBufferIndex += bytesRead; return bytesRead; }
Source:
private void readAmount(int numChars) throws IOException { int bytesRead = is.read(buffer, end, Math.min(numChars, buffer.length - end)); if (bytesRead < 0) { // EOF START throw new IOException(String.format("Reached end of stream.")); END } end = end + bytesRead; } just use a raw string here no need for String.format

Target:
private void readAmount(int numChars) throws IOException { int bytesRead = reader.read(buffer, end, Math.min(numChars, buffer.length - end)); if (bytesRead < 0) { // EOF throw new IOException("Reached end of stream."); } end = end + bytesRead; }
Source:
public void createNewComponent () { Engine engine = new Engine(); ComponentD componentD = engine.createComponent(ComponentD.class); START assertNotEquals(componentD, null); END } I think there is `assertNotNull()`, could you please do that?

Target:
public void createNewComponent () { Engine engine = new Engine(); ComponentD componentD = engine.createComponent(ComponentD.class); assertNotNull(componentD); }
Source:
public Span buildAndStartSpan(String name, SpanContext spanContext) { START if(getTracer() == null) { END m_tracer = GlobalTracer.get(); } if (spanContext == null) { return getTracer().buildSpan("Provisiond-" + name).start(); } else { return getTracer().buildSpan("Provisiond-" + name).asChildOf(spanContext).start(); } } Seems odd to mix calls to `getTracer()` and direct access to `m_tracer` in this same method.

Target:
public Span buildAndStartSpan(String name, SpanContext spanContext) { if(m_tracer == null) { m_tracer = GlobalTracer.get(); } if (spanContext == null) { return m_tracer.buildSpan("Provisiond-" + name).start(); } else { return m_tracer.buildSpan("Provisiond-" + name).asChildOf(spanContext).start(); } }
Source:
public void onUnbind(GraphContainerProvider graphContainerProvider, Map<String, String> props) { START if(graphContainerProvider != null) { END graphContainerProviders.remove(graphContainerProvider); final ServiceRegistration<GraphContainerProviderRegistration> serviceRegistration = serviceRegistrationMap.remove(graphContainerProvider); if (serviceRegistration != null) { serviceRegistration.unregister(); } } } Could be simplified by returning immediately if null - would save having to indent the whole block.

Target:
public void onUnbind(GraphContainerProvider graphContainerProvider, Map<String, String> props) { if(graphContainerProvider == null) { return; } graphContainerProviders.remove(graphContainerProvider); final ServiceRegistration<GraphContainerProviderRegistration> serviceRegistration = serviceRegistrationMap.remove(graphContainerProvider); if (serviceRegistration != null) { serviceRegistration.unregister(); } }
Source:
START protected JaxbListWrapper<OnmsIpInterface> createListWrapper(Collection<OnmsIpInterface> list) { END return new OnmsIpInterfaceList(list); } Should be final.

Target:
protected final JaxbListWrapper<OnmsIpInterface> createListWrapper(Collection<OnmsIpInterface> list) { return new OnmsIpInterfaceList(list); }
Source:
public boolean getHasIngressFlows() { if (m_lastIngressFlow == null) { return false; } START return (new Date().getTime() - m_lastIngressFlow.getTime()) / 1000 < OnmsSnmpInterface.MAX_FLOW_AGE; END } `new Date().getTime()` can be replaced by `System.currentTimeMillis()`

Target:
public boolean getHasIngressFlows() { if (m_lastIngressFlow == null) { return false; } return (System.currentTimeMillis() - m_lastIngressFlow.getTime()) / 1000 < OnmsSnmpInterface.MAX_FLOW_AGE; }
Source:
public void addResult(Resource resource, Collection<String> metrics) { START this.m_results.add(new Result(resource, metrics)); END } Even if this was copied, we should fix the `this.m_` references here :)

Target:
public void addResult(Resource resource, Collection<String> metrics) { this.results.add(new Result(resource, metrics)); }
Source:
public Extended80211Payload(final ByteBuf buffer) throws InvalidPacketException { this.ciphersuite = new CipherSuite(buffer); START this.data = new Opaque(buffer, Optional.empty(), buffer1 -> Opaque.parseBytes(buffer1)); END } Revert this.

Target:
public Extended80211Payload(final ByteBuf buffer) throws InvalidPacketException { this.ciphersuite = new CipherSuite(buffer); this.data = new Opaque(buffer, Optional.empty(), Opaque::parseBytes); }
Source:
public Optional<String> getRoutingKey(final TelemetryProtos.TelemetryMessageLog message) { if (message.getUseRoutingKey()) { return Optional.of(String.format("%s@%s:%d", message.getLocation(), message.getSourceAddress(), message.getSourcePort())); } else { START return null; END } } This is an `Optional` value and thus should not return `null`. Use `Optional.of()` and `Optional.empty()` instead.

Target:
public Optional<String> getRoutingKey(final TelemetryProtos.TelemetryMessageLog message) { if (message.getUseRoutingKey()) { return Optional.of(String.format("%s@%s:%d", message.getLocation(), message.getSourceAddress(), message.getSourcePort())); } return Optional.empty(); }
Source:
START public synchronized static VertexHopCriteria createCriteria(String namespace, String nodeId, String nodeLabel) { END VertexHopCriteria criterion = new LinkdHopCriteria(namespace,nodeId, nodeLabel); return criterion; } `synchronized` can be safely removed from this method since it is stateless. ```suggestion public static VertexHopCriteria createCriteria(String namespace, String nodeId, String nodeLabel) { ```

Target:
public static VertexHopCriteria createCriteria(String namespace, String nodeId, String nodeLabel) { VertexHopCriteria criterion = new LinkdHopCriteria(namespace, nodeId, nodeLabel); return criterion; }
Source:
public MetricRegistry getMetrics() { START return metrics != null ? metrics : new MetricRegistry(); END } Shouldn't we store the result of ` new MetricRegistry()` instead of returning a new one on get?

Target:
public MetricRegistry getMetrics() { if(metrics == null) { metrics = new MetricRegistry(); } return metrics; }
Source:
public CollectionSet build(CollectionAgent agent, Object message, Long timestamp) throws ScriptException { final CollectionSetBuilder builder = new CollectionSetBuilder(agent); START if (timestamp != null) { END builder.withTimestamp(new Date(timestamp)); } final SimpleBindings globals = new SimpleBindings(); globals.put("agent", agent); globals.put("builder", builder); globals.put("msg", message); compiledScript.eval(globals); return builder.build(); } For Nxos, JTI should we check if it is not zero since that would be default value.

Target:
public CollectionSet build(CollectionAgent agent, Object message, Long timestamp) throws ScriptException { final CollectionSetBuilder builder = new CollectionSetBuilder(agent); if (timestamp != null && timestamp > 0) { builder.withTimestamp(new Date(timestamp)); } final SimpleBindings globals = new SimpleBindings(); globals.put("agent", agent); globals.put("builder", builder); globals.put("msg", message); compiledScript.eval(globals); return builder.build(); }
Source:
public Collection<E> get() { START return container; END } We should make this immutable to allow manipulation only via the `CaffeineCache` class.

Target:
Collection<E> get() { return container; }
Source:
DefaultExtendedDnsCacheEntry(String hostname, InetAddress address) { this.hostname = hostname; this.address = address; START cause = null; END hostnameFromPtrRecord = null; } Nit: `this` consistency.

Target:
DefaultExtendedDnsCacheEntry(String hostname, InetAddress address) { this.hostname = hostname; this.address = address; this.cause = null; this.hostnameFromPtrRecord = null; }
Source:
public CompletableFuture<S> writeMessage(S message) throws WriteFailedException { final CompletableFuture<S> future = new CompletableFuture<>(); byte[] bytes = sinkModule.marshalSingleMessage(message); START String uuid = UUID.randomUUID().toString(); END Long key = offHeapQueue.writeMessage(sinkModule.getId(), bytes); offHeapFutureMap.put(key, future); firstWrite.countDown(); return future; } This is unused now.

Target:
public CompletableFuture<S> writeMessage(S message) throws WriteFailedException { final CompletableFuture<S> future = new CompletableFuture<>(); byte[] bytes = sinkModule.marshalSingleMessage(message); Long key = offHeapQueue.writeMessage(sinkModule.getId(), bytes); offHeapFutureMap.put(key, future); firstWrite.countDown(); return future; }
Source:
public Response saveRule(RuleDTO ruleDTO) { final Rule rule = convert(ruleDTO); rule.setId(null); START rule.setPosition(0); // new rules get the lowest position (lowest priority) END final int ruleId = classificationService.saveRule(rule); final UriBuilder builder = UriBuilder.fromResource(ClassificationRestService.class); final URI uri = builder.path(ClassificationRestService.class, "getRule").build(ruleId); return Response.created(uri).build(); } Shouldn't this mean `new rules get the lowest position (highest priority)`?

Target:
public Response saveRule(RuleDTO ruleDTO) { final Rule rule = convert(ruleDTO); rule.setId(null); final int ruleId = classificationService.saveRule(rule); final UriBuilder builder = UriBuilder.fromResource(ClassificationRestService.class); final URI uri = builder.path(ClassificationRestService.class, "getRule").build(ruleId); return Response.created(uri).build(); }
Source:
public String getUnmodifiedInstance() { START return null; //For node type resources, use the default instance END } ```suggestion return getInstance(); ```

Target:
public String getUnmodifiedInstance() { return getInstance(); }
Source:
public void setUp() throws Exception { System.setProperty("org.apache.logging.log4j.simplelog.StatusLogger.level", "INFO"); MockLogAppender.setupLogging(); START TemporaryDatabasePostgreSQL temp = new TemporaryDatabasePostgreSQL(); END } AFAICT this does nothing, or are you doing it just for initialization? If so you don't need the variable.

Target:
public void setUp() throws Exception { System.setProperty("org.apache.logging.log4j.simplelog.StatusLogger.level", "INFO"); MockLogAppender.setupLogging(); }
Source:
public void setDstAddrHostname(String dstAddrHostname) { START addHost(dstAddrHostname); END this.dstAddrHostname = dstAddrHostname; } Could you update the `addHost()` method so that it includes an `Objects.requireNonNull()` check on the host. Looks like I missed that originally.

Target:
public void setDstAddrHostname(String dstAddrHostname) { this.dstAddrHostname = dstAddrHostname; }
Source:
public Conversation build() { START return new Conversation(this.location, END this.protocol, this.lowerIp, this.upperIp, this.lowerHostname, this.upperHostname, this.application); } If we switch to the single-arg constructor, we can just pass an instance of the builder `return new Conversation(this)`

Target:
public Conversation build() { return new Conversation(this); }
Source:
public void setTTL(Long ttl) { START this.m_ttl = m_ttl; END } `this` and `m_`

Target:
public void setTTL(Long ttl) { m_ttl = ttl; }
Source:
public void testNodesWithFlows() { START this.m_driver.get(this.getBaseUrl() + "opennms/element/nodeList.htm?flows=true"); END assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText), containsInAnyOrder("TestMachine loc1node2", "TestMachine loc2node2")); } The usage of `this` and `m_` is weird, I'd omit the `this` here.

Target:
public void testNodesWithFlows() { m_driver.get(this.getBaseUrl() + "opennms/element/nodeList.htm?flows=true"); assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText), containsInAnyOrder("TestMachine loc1node2", "TestMachine loc2node2")); }
Source:
private Tracer getTracer() { START return tracerRegistry.getTracer(minionIdentity.getId()+"@"+minionIdentity.getLocation()); END } Can we flip the location and id here so that the all of the systems at the same location a "grouped" together in the Jaeger UI?

Target:
private Tracer getTracer() { return tracerRegistry.getTracer(minionIdentity.getLocation() + "@" + minionIdentity.getId()); }
Source:
public GenericEdge(GenericEdge copyMe) { START this(new GenericVertex(copyMe.source), new GenericVertex(copyMe.target), new HashMap<>(copyMe.getProperties())); END } Either access the properties via name or method, but don't mix.

Target:
public GenericEdge(GenericEdge copyMe) { this(new GenericVertex(copyMe.source), new GenericVertex(copyMe.target), new HashMap<>(copyMe.properties)); }
Source:
public NodeInfo getNodeInfo() { START return this.getProperty(GenericProperties.NODE_INFO); END // final Optional<Object> first = graphProperties.getProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst(); // if (first.isPresent()) { // return (NodeInfo) first.get(); // } // return (NodeInfo) graphProperties.getComputedProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst().orElse(null); } We need to distinguish between computed/enriched and static properties. Either return `null` or `enrichedProperties.getProperty(ComputedProperties.NODE_INFO)`

Target:
public NodeInfo getNodeInfo() { return null; // final Optional<Object> first = graphProperties.getProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst(); // if (first.isPresent()) { // return (NodeInfo) first.get(); // } // return (NodeInfo) graphProperties.getComputedProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst().orElse(null); }
Source:
public static OnmsTopologyVertex create(String id, String label, String address, String iconKey) { START return new OnmsTopologyVertex(Objects.requireNonNull(id, "id is null, cannot create vertex"), label, address, END iconKey); } Can we put the `Objects.requireNonNull(...)` at the beginning of the method? This makes it easier to read.

Target:
public static OnmsTopologyVertex create(String id, String label, String address, String iconKey) { Objects.requireNonNull(id, "id is null, cannot create vertex"); return new OnmsTopologyVertex(id, label, address, iconKey); }
Source:
private static Integer sysPropToIntOrNull(String sysProp) { final String val = System.getProperty(sysProp, null); if (val == null) { return null; } try { return Integer.parseInt(val); } catch (NumberFormatException e) { START LOG.error("Failed to parse value of system property {}='{}' to an integer. Using default value."); END return null; } } Missing the substitutions for the `{}`'s. ```suggestion LOG.error("Failed to parse value of system property {}='{}' to an integer. Using default value.", sysProp, val); ```

Target:
private static Integer sysPropToIntOrNull(String sysProp) { final String val = System.getProperty(sysProp, null); if (val == null) { return null; } try { return Integer.parseInt(val); } catch (NumberFormatException e) { LOG.error("Failed to parse value of system property {}='{}' to an integer. Using default value.", sysProp, val); return null; } }
Source:
public DhcpdImpl() { START Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { END @Override public void run() { DhcpdImpl.this.shutdown = true; DhcpdImpl.this.port67Listener.stop(); DhcpdImpl.this.port68Listener.stop(); LOG.debug("Dhcpd terminated successfully."); } })); } We should cleanup when the bundle is destroyed rather than using a shutdown hook.

Target:
public DhcpdImpl() { }
Source:
public DhcpClient(final String macAddress, final boolean relayMode, final String myIpAddress, final boolean extendedMode, final String requestIpAddress, final int timeout, final int retries, final Dhcpd dhcpd) { START this.m_macAddress = macAddress; END this.m_relayMode = relayMode; this.m_myIpAddress = myIpAddress; this.m_extendedMode = extendedMode; this.m_requestIpAddress = requestIpAddress; this.m_timeout = timeout; this.m_retries = retries; this.m_dhcpd = dhcpd; } `this` and `m_` is redundant

Target:
public DhcpClient(final String macAddress, final boolean relayMode, final String myIpAddress, final boolean extendedMode, final String requestIpAddress, final int timeout, final int retries, final Dhcpd dhcpd) { this.macAddress = macAddress; this.relayMode = relayMode; this.myIpAddress = myIpAddress; this.extendedMode = extendedMode; this.requestIpAddress = requestIpAddress; this.timeout = timeout; this.retries = retries; this.dhcpd = dhcpd; }
Source:
public boolean parseUpdates() { synchronized (m_updates) { START if (m_updates.booleanValue()) { END m_updates = false; return true; } } return false; } No need to call `booleanValue()` here.

Target:
public boolean parseUpdates() { if (m_updates.get()) { m_updates.set(false); return true; } return false; }
Source:
public boolean hasUpdates() { START synchronized (m_updates) { END if (m_updates.booleanValue()) { return true; } } return false; } Can be simplified to `return m_updates`.

Target:
public boolean hasUpdates() { return m_updates.get(); }
Source:
public void onAlarmDeleted(OnmsAlarm alarm) { START final Integer alarmId = alarm.getId(); END final String reductionKey = alarm.getReductionKey(); forEachListener(l -> l.handleDeletedAlarm(alarmId, reductionKey)); } Line 147 and 148 are redundant.

Target:
public void onAlarmDeleted(OnmsAlarm alarm) { forEachListener(l -> l.handleDeletedAlarm(alarm.getId(), alarm.getReductionKey())); }
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } START if (!(obj instanceof IpServiceEdgeRequestDTO)) { return false; } END if (!super.equals(obj)) { return false; } // compare subclass fields return java.util.Objects.equals(applicationId, ((ApplicationEdgeRequestDTO) obj).applicationId); } Looks like the class is wrong in this instanceof comparison. Here is the IntelliJ generated equals if you want to just use that ``` @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ApplicationEdgeRequestDTO that = (ApplicationEdgeRequestDTO) o; return Objects.equals(applicationId, that.applicationId); } ``` ```suggestion if (!(obj instanceof ApplicationEdgeRequestDTO)) { return false; } ```

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof ApplicationEdgeRequestDTO)) { return false; } if (!super.equals(obj)) { return false; } // compare subclass fields return java.util.Objects.equals(applicationId, ((ApplicationEdgeRequestDTO) obj).applicationId); }
Source:
public static Set<String> getReductionKeys(final OnmsApplication application) { Objects.requireNonNull(application); Set<String> reductionKeys = new HashSet<>(); START for(OnmsMonitoredService monitoredService : application.getMonitoredServices()) { END reductionKeys.add(getNodeLostServiceReductionKey(monitoredService)); reductionKeys.add(getInterfaceDownReductionKey(monitoredService)); reductionKeys.add(getNodeDownReductionKey(monitoredService)); } return reductionKeys; } Can we not duplicate the next 3 lines of code? Use the `getReductionKeys(OnmsMonitoredService)` method instead.

Target:
public static Set<String> getReductionKeys(final OnmsApplication application) { Objects.requireNonNull(application); Set<String> reductionKeys = new HashSet<>(); for (OnmsMonitoredService monitoredService : application.getMonitoredServices()) { reductionKeys.addAll(getReductionKeys(monitoredService)); } return reductionKeys; }
Source:
public void init() throws ConfigurationResourceException { final ServiceConfiguration config = serviceConfiguration.get(); for (Service service : config.getServices()) { final String name = service.getName().split("=")[1]; // OpenNMS:Name=Manager => Manager START this.daemonList.add(new DaemonInfo(name, ignoreList.contains(name), service.isEnabled(), service.isReloadable() /* Internal daemons are not reloadable by default */)); END } } The member variables in this class are scoped to ```this``` unnecessarily. Not sure if that is a style preference, just pointing it out. Looks like the same is true for a couple other classes in this PR as well.

Target:
public void init() throws ConfigurationResourceException { final ServiceConfiguration config = serviceConfiguration.get(); for (Service service : config.getServices()) { final String name = service.getName().split("=")[1]; // OpenNMS:Name=Manager => Manager daemonList.add(new DaemonInfo(name, ignoreList.contains(name), service.isEnabled(), service.isReloadable() /* Internal daemons are not reloadable by default */)); } }
Source:
public void setRelatedAlarms(Set<OnmsAlarm> alarms) { m_associatedAlarms.clear(); START alarms.stream().forEach(relatedAlarm -> m_associatedAlarms.add(new AlarmAssociation(this, relatedAlarm))); END } ```suggestion alarms.forEach(relatedAlarm -> m_associatedAlarms.add(new AlarmAssociation(this, relatedAlarm))); ```

Target:
public void setRelatedAlarms(Set<OnmsAlarm> alarms) { m_associatedAlarms.clear(); alarms.forEach(relatedAlarm -> m_associatedAlarms.add(new AlarmAssociation(this, relatedAlarm))); }
Source:
public void acknowledgeAlarm(OnmsAlarm alarm, Date now) { LOG.info("Acknowledging alarm with id: @ {}", alarm.getId(), now); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping ack.", alarm); return; } START OnmsAcknowledgment ack = new OnmsAcknowledgment(alarm, DEFAULT_USER, now); END ack.setAckAction(AckAction.ACKNOWLEDGE); acknowledgmentDao.processAck(ack); } We should use the alarm that was retrieved within the transaction i.e.: ```suggestion OnmsAcknowledgment ack = new OnmsAcknowledgment(alarmInTrans, DEFAULT_USER, now); ```

Target:
public void acknowledgeAlarm(OnmsAlarm alarm, Date now) { LOG.info("Acknowledging alarm with id: @ {}", alarm.getId(), now); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping ack.", alarm); return; } OnmsAcknowledgment ack = new OnmsAcknowledgment(alarmInTrans, DEFAULT_USER, now); ack.setAckAction(AckAction.ACKNOWLEDGE); acknowledgmentDao.processAck(ack); }
Source:
public void debug(String message, Object... objects) { START LOG.warn(message, objects); END } debug vs warn

Target:
public void debug(String message, Object... objects) { LOG.debug(message, objects); }
Source:
public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType())) { START if (providers.add(new ConfigurationProviderState<>(provider))) { END LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); // Force a check on the next get forceReload = true; } } } Eliminate this ```if``` on line 236 and move the condition to the ```if``` with ```&&``` on line 235.

Target:
public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType()) && providers.add(new ConfigurationProviderState<>(provider))) { LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); // Force a check on the next get forceReload = true; } }
Source:
public WsManAssetAdapterConfig getInstance() { START m_config.getReadLock().lock(); END try { return m_config; } finally { m_config.getReadLock().unlock(); } } I suspect this locking code is not needed. The value of m_config can't change so it should be safe to unconditionally return it here. Delete 108 to 113 and replace with: ```return m_config;```

Target:
public WsManAssetAdapterConfig getInstance() { return m_config; }
Source:
public void handleDaemonConfigChanged(final Event event) { DaemonTools.handleReloadEvent(event, "PollerBackEnd", (e)->{ m_pollerBackEnd.configurationUpdated(); START }); END } Can you use the short version of the closure, as it is a one liner, the `{}` are not needed.

Target:
public void handleDaemonConfigChanged(final Event event) { DaemonTools.handleReloadEvent(event, "PollerBackEnd", (e)-> m_pollerBackEnd.configurationUpdated()); }
Source:
PropertiesHolder(final File file) { START this.m_file = file; END this.m_properties = null; } Is there any reason to add the `this.` prefixes? Seems redundant when the member variables are already prefixed with `m_`.

Target:
PropertiesHolder(final File file) { m_file = file; m_properties = null; }
Source:
public Collection<AlarmFeedback> getFeedback(String situationKey) throws FeedbackException { START Gson gson = new Gson(); END String query = "{\n" + " \"query\": { \"match\": { \"situation_key\": " + gson.toJson(situationKey) + " } }\n" + "}"; return search(query); } The gson instance is thread-safe, so we can declare it as a member variable instead of recreating it everytime here.

Target:
public Collection<AlarmFeedback> getFeedback(String situationKey) throws FeedbackException { String query = "{\n" + " \"query\": { \"match\": { \"situation_key\": " + gson.toJson(situationKey) + " } }\n" + "}"; return search(query); }
Source:
private LinkdHopCriteria(String nodeId, String nodeLabel) { super(nodeLabel); START setId(nodeId); END m_nodeId = nodeId; } why not using the super constructor? `super(nodeId, nodeLabel)`?

Target:
private LinkdHopCriteria(String nodeId, String nodeLabel) { super(nodeId,nodeLabel); m_nodeId = nodeId; }
Source:
public void setRelatedAlarms(Set<OnmsAlarm> alarms) { START this.m_relatedAlarms = alarms; END } Nit: `this.` is redundant when used with a variable prefixed with `m_`.

Target:
public void setRelatedAlarms(Set<OnmsAlarm> alarms) { m_relatedAlarms = alarms; }
Source:
public void testKafkaRpcAtRemoteLocation() throws InterruptedException, ExecutionException { assertNotEquals(REMOTE_LOCATION_NAME, identity.getLocation()); START Thread.sleep(5000); END EchoRequest request = new EchoRequest("Kafka-RPC"); request.setLocation(REMOTE_LOCATION_NAME); request.setDelay(5000L); EchoResponse expectedResponse = new EchoResponse("Kafka-RPC"); EchoResponse actualResponse = echoClient.execute(request).get(); assertEquals(expectedResponse, actualResponse); } Why do we need to sleep for 5 seconds here?

Target:
public void testKafkaRpcAtRemoteLocation() throws InterruptedException, ExecutionException { EchoRequest request = new EchoRequest("Kafka-RPC"); request.setLocation(REMOTE_LOCATION_NAME); request.setDelay(5000L); EchoResponse expectedResponse = new EchoResponse("Kafka-RPC"); EchoResponse actualResponse = echoClient.execute(request).get(); assertEquals(expectedResponse, actualResponse); }
Source:
public DateTimeTag(){ String format = System.getProperty(SYSTEM_PROPERTY_DATE_FORMAT); if(format == null) { this.formatter = DEFAULT_FORMATTER; } else { try { this.formatter = DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault()); } catch (IllegalArgumentException e) { log.log(Level.WARNING, String.format("Can not use System Property %s=%s as dateformat, will fall back to default." + " Please see also java.time.format.DateTimeFormatter for the correct syntax", SYSTEM_PROPERTY_DATE_FORMAT, format) START , e); END this.formatter = DEFAULT_FORMATTER; } } } Is there a particular reason, why we use the `java.util.Logging`instead of the `org.slf4j` logging? The usage of String.format in combination with logging looks odd to me.

Target:
public DateTimeTag(){ String format = System.getProperty(SYSTEM_PROPERTY_DATE_FORMAT); if(format == null) { this.formatter = DEFAULT_FORMATTER; } else { try { this.formatter = DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault()); } catch (IllegalArgumentException e) { LOG.log(Level.WARNING, String.format("Can not use System Property %s=%s as dateformat, will fall back to default." + " Please see also java.time.format.DateTimeFormatter for the correct syntax", SYSTEM_PROPERTY_DATE_FORMAT, format) , e); this.formatter = DEFAULT_FORMATTER; } } }
Source:
public int getNumThreads() { getReadLock().lock(); try { START if (m_config.getNumThreads() <= 0) { END return m_config.getNumThreads(); } else { return Runtime.getRuntime().availableProcessors() * 2; } } finally { getReadLock().unlock(); } } I think this condition should be opposite.

Target:
public int getNumThreads() { getReadLock().lock(); try { if (m_config.getNumThreads() <= 0) { return Runtime.getRuntime().availableProcessors() * 2; } else { return m_config.getNumThreads(); } } finally { getReadLock().unlock(); } }
Source:
public static String getConvoKeyAsJsonString(FlowDocument document) { START if (document.isInitiator() == null) { END return null; } final ConversationKey convoKey = document.isInitiator() ? egressKeyFor(document) : ingressKeyFor(document); return toJsonString(convoKey); } Can we just not call this, if `isInitiator() == null` returns `true`

Target:
public static String getConvoKeyAsJsonString(FlowDocument document) { final ConversationKey convoKey = document.isInitiator() ? egressKeyFor(document) : ingressKeyFor(document); return toJsonString(convoKey); }
Source:
public JexlEvaluateFunctions(JexlContext context, JexlEngine jexl){ START Preconditions.checkNotNull(context, "JexlContext context"); END Preconditions.checkNotNull(jexl, "JexlEngine jexl"); m_context= context; m_jexl = jexl; } Just a note, you checkNotNull actually returns the value, so you could do `m_context = Preconditions.checkNotNull(context, ...)` instead of doing this on two lines.

Target:
public JexlEvaluateFunctions(JexlContext context, JexlEngine jexl){ m_context = Preconditions.checkNotNull(context, "JexlContext context"); m_jexl = Preconditions.checkNotNull(jexl, "JexlEngine jexl"); }
Source:
public String[] marshal(final List<String> value) throws Exception { START System.err.println("unmarshal: " + value); END if (value == null) return null; return value.stream().map(String::trim).collect(Collectors.toList()).toArray(TYPE); } `System.err` -> `LOG.trace`?

Target:
public String[] marshal(final List<String> value) throws Exception { if (value == null) return null; return value.stream().map(String::trim).collect(Collectors.toList()).toArray(TYPE); }
Source:
private void restartPoller(final long pollInterval) { LOG.debug("Restarting alarm poller (interval {}s).", pollInterval); START if (m_alarmPoller != null) { END stopPoller(); } startPoller(pollInterval); } Stopping the poller also does check for the poller to be not null. I'd be consistent about this. Either check in stopPoller or before.

Target:
private void restartPoller(final long pollInterval) { LOG.debug("Restarting alarm poller (interval {}s).", pollInterval); stopPoller(); startPoller(pollInterval); }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } START if (o == null || this.getClass() != o.getClass()) { END return false; } final GraphMLEdgeStatus that = (GraphMLEdgeStatus) o; return Objects.equal(this.getSeverity(), that.getSeverity()) && Objects.equal(this.getStyleProperties(), that.getStyleProperties()); } Is there a particular reason why `getClass()` is used instead of `instanceof`. `instanceof` is less restrictive and may be the better choice.

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof GraphMLEdgeStatus)) { return false; } final GraphMLEdgeStatus that = (GraphMLEdgeStatus) o; return Objects.equal(this.getSeverity(), that.getSeverity()) && Objects.equal(this.getStyleProperties(), that.getStyleProperties()); }
Source:
START public void expand() { END try { ui.testCase.setImplicitWait(1, TimeUnit.SECONDS); getElement().findElement(By.xpath("//a[@class='gwt-Anchor icon-plus']")).click(); } catch (NoSuchElementException e) { } finally { ui.testCase.setImplicitWait(); } waitForTransition(); } Why do the expand() and collapse() methods catch `NoSuchElementException`? In addition the `waitForTransition()` only makes sense if the element was clicked.

Target:
public void expand() throws NoSuchElementException { try { ui.testCase.setImplicitWait(1, TimeUnit.SECONDS); getElement().findElement(By.xpath("//a[@class='gwt-Anchor icon-plus']")).click(); waitForTransition(); } finally { ui.testCase.setImplicitWait(); } }
Source:
public DetectRequest buildRequest(String location, InetAddress address, Integer port, Map<String, String> attributes) { START return new DetectRequestImpl(address, port); END } Should we not pass the attributes map here?

Target:
public DetectRequest buildRequest(String location, InetAddress address, Integer port, Map<String, String> attributes) { return new DetectRequestImpl(address, port, attributes); }
Source:
private void reload() throws IOException { START final Reader r = new FileReader(ConfigFileConstants.getFile(ConfigFileConstants.EVENTD_CONFIG_FILE_NAME)); END m_config = JaxbUtils.unmarshal(EventdConfiguration.class, r); } Shouldn't we close the FileReader after the unmarshal? We could also pass the File directly to the JaxbUtils.

Target:
private void reload() throws IOException { try (final Reader r = new FileReader(ConfigFileConstants.getFile(ConfigFileConstants.EVENTD_CONFIG_FILE_NAME))) { m_config = JaxbUtils.unmarshal(EventdConfiguration.class, r); } }
Source:
public boolean requiresTransaction() { START return tokens.stream().filter(t -> t.requiresTransaction()).findAny().isPresent(); END } Can we pre-compute this value instead? The `tokens` are immutable and set in the constructor.

Target:
public boolean requiresTransaction() { return requiresTransaction; }
Source:
public void scan(ScanContext context) throws InterruptedException { InetAddress agentAddress = context.getAgentAddress("SNMP"); START String location = context.getSysLocation(); END if (agentAddress == null) { return; } SnmpAgentConfig agentConfig = m_snmpAgentConfigFactory.getAgentConfig(agentAddress, location); SnmpWalker walker = SnmpUtils.createWalker(agentConfig, getName(), createCollectionTracker(context)); walker.start(); walker.waitFor(); } The sysLocation (http://www.alvestrand.no/objectid/1.3.6.1.2.1.1.6.html) is not necessarily the same as the node's location.

Target:
public void scan(ScanContext context) throws InterruptedException { InetAddress agentAddress = context.getAgentAddress("SNMP"); if (agentAddress == null) { return; } SnmpAgentConfig agentConfig = m_snmpAgentConfigFactory.getAgentConfig(agentAddress, null); SnmpWalker walker = SnmpUtils.createWalker(agentConfig, getName(), createCollectionTracker(context)); walker.start(); walker.waitFor(); }
Source:
private static JAXBContext initOnmsEventParameterContext() { try { return JAXBContext.newInstance(EventParms.class); } catch (JAXBException e) { // TODO Auto-generated catch block START e.printStackTrace(); END } return null; } Lets re-throw this as a RuntimeException instead.

Target:
private static JAXBContext initOnmsEventParameterContext() { try { return JAXBContext.newInstance(EventParms.class); } catch (JAXBException e) { throw new RuntimeException(e); } }
Source:
public Iterator<IPPollAddress> getExcludingInterator(final Iterator<IPPollAddress> it) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize(it, ORDERED | IMMUTABLE), false ) // Filter out excluded addresses START .filter(item -> { return !isExcluded(item.getAddress());}) END .iterator(); } This can even be shorter: `.filter(item -> !isExcluded(item.getAddress()))`

Target:
public Iterator<IPPollAddress> getExcludingInterator(final Iterator<IPPollAddress> it) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize(it, ORDERED | IMMUTABLE), false ) // Filter out excluded addresses .filter(item -> !isExcluded(item.getAddress())) .iterator(); }
Source:
public void execute(List<VertexRef> targets, OperationContext operationContext) { if (operationContext != null && operationContext.getGraphContainer() != null) { START operationContext.getGraphContainer().getBaseTopology().refresh(); END operationContext.getGraphContainer().setDirty(true); operationContext.getGraphContainer().redoLayout(); TopologyUI.getCurrent().markAsDirtyRecursive(); } } Can we then also change the TopologyUI auto refresher logic to use the "RedoLayoutOperation" instead? See https://github.com/OpenNMS/opennms/blob/develop/features/topology-map/org.opennms.features.topology.app/src/main/java/org/opennms/features/topology/app/internal/TopologyUI.java#L166

Target:
public void execute(List<VertexRef> targets, OperationContext operationContext) { if (operationContext != null && operationContext.getGraphContainer() != null) { execute(operationContext.getGraphContainer()); } }
Source:
public void setIsTable(String table) { if ("true".equalsIgnoreCase(table)) { this.m_isTable = true; } else { this.m_isTable = false; } START } END This can be refactored to `m_isTable = "true".equalsIgnoreCase(table)`

Target:
public void setIsTable(String table) { m_isTable = "true".equalsIgnoreCase(table); }
Source:
public BsmAdminPageEditWindow openNewDialog(String businessServiceName) throws InterruptedException { findElementById("createButton").click(); wait.until(pageContainsText("Business Service Edit")); // we wait until the edit dialog appears START return new BsmAdminPageEditWindow(businessServiceName).name(businessServiceName); END } Let's remove the `BsmAdminPageEditWindow(String)` constructor.

Target:
public BsmAdminPageEditWindow openNewDialog(String businessServiceName) throws InterruptedException { findElementById("createButton").click(); wait.until(pageContainsText("Business Service Edit")); // we wait until the edit dialog appears return new BsmAdminPageEditWindow().name(businessServiceName); }
Source:
public BsmAdminPageEditWindow addAttribute(String key, String value) throws InterruptedException { newAttributeWindow() .key(key) .value(value) .confirm(); START wait.until(ExpectedConditions.elementToBeClickable(By.id("addAttributeButton"))); END return this; } This is kinda a duplicate, as we already wait in the confirm() method or is there a particular reason to wait again for another element?

Target:
public BsmAdminPageEditWindow addAttribute(String key, String value) throws InterruptedException { newAttributeWindow() .key(key) .value(value) .confirm(); return this; }
Source:
public BsmAdminPageAttributeEditWindow value(String value) { findElementById("valueField").clear(); START findElementById("valueField").sendKeys(String.valueOf(value)); END return this; } `value` already is a String, so we do not need `String.valueOf(value)` here.

Target:
public BsmAdminPageAttributeEditWindow value(String value) { findElementById("valueField").clear(); findElementById("valueField").sendKeys(value); return this; }
Source:
public BsmAdminPageEditWindow editAttribute(String key, String value) throws InterruptedException { getSelectWebElement("attributeList").selectByVisibleText(key); editAttributeWindow() .value(value) .confirm(); START wait.until(ExpectedConditions.elementToBeClickable(By.id("addAttributeButton"))); END return this; } This is kinda a duplicate, as we already wait in the confirm() method or is there a particular reason to wait again for another element?

Target:
public BsmAdminPageEditWindow editAttribute(String key, String value) throws InterruptedException { getSelectWebElement("attributeList").selectByVisibleText(key); editAttributeWindow() .value(value) .confirm(); return this; }
Source:
public MeasurementsService(MeasurementFetchStrategy fetchStrategy, ExpressionEngine expressionEngine, FilterEngine filterEngine) { START Preconditions.checkNotNull(fetchStrategy); END Preconditions.checkNotNull(expressionEngine); Preconditions.checkNotNull(filterEngine); this.fetchStrategy = fetchStrategy; this.expressionEngine = expressionEngine; this.filterEngine = filterEngine; } checkNotNull returns the object, so these lines can be rewritten in the form of: this.fetchStrategy = Preconditions.checkNotNull(fetchStrategy);

Target:
public MeasurementsService(MeasurementFetchStrategy fetchStrategy, ExpressionEngine expressionEngine, FilterEngine filterEngine) { this.fetchStrategy = Preconditions.checkNotNull(fetchStrategy); this.expressionEngine = Preconditions.checkNotNull(expressionEngine); this.filterEngine = Preconditions.checkNotNull(filterEngine); }
Source:
START public static ByteSource serializeImage( final BufferedImage bufferedImage, final String mimeType, final int quality ) END throws IOException { final byte[] serializedImage; final String format = getFormatByMimeType( mimeType ); if ( quality != 0 ) { serializedImage = writeImage( bufferedImage, format, quality ); } else { serializedImage = writeImage( bufferedImage, format ); } return ByteSource.wrap( serializedImage ); } Avoid ByteSource in API. byte[] is ok here

Target:
public static byte[] serializeImage( final BufferedImage bufferedImage, final String mimeType, final int quality ) throws IOException { final byte[] serializedImage; final String format = getFormatByMimeType( mimeType ); if ( quality != 0 ) { serializedImage = writeImage( bufferedImage, format, quality ); } else { serializedImage = writeImage( bufferedImage, format ); } return serializedImage; }
Source:
public void modifyIcon( final ModifyProjectIconParams params ) { callWithUpdateContext( ( () -> { doModifyIcon( params ); START LOG.info( "Icon for project updated: " + params.getName() ); END return true; } ), params.getName() ); } debug.

Target:
public void modifyIcon( final ModifyProjectIconParams params ) { callWithUpdateContext( ( () -> { doModifyIcon( params ); LOG.debug( "Icon for project updated: " + params.getName() ); return true; } ), params.getName() ); }
Source:
public String modifyLanguage( final ModifyLanguageParamsJson params ) { START return Optional.ofNullable( doApplyLanguage( params.getName(), params.getLanguage() ) ). END map( Locale::toLanguageTag ). orElse( null ); } To improve readability return optional from doApplyLanguage

Target:
public String modifyLanguage( final ModifyLanguageParamsJson params ) { return doApplyLanguage( params.getName(), params.getLanguage() ). map( Locale::toLanguageTag ). orElse( null ); }
Source:
START public ImmutableList<ProjectJson> getProjects() END { return projects; } Should be List

Target:
public List<ProjectJson> getProjects() { return projects; }
Source:
public static ProjectReadAccessType from( final String value ) { START if ( value.equalsIgnoreCase( PUBLIC.toString() ) ) END { return PUBLIC; } else if ( value.equalsIgnoreCase( PRIVATE.toString() ) ) { return PRIVATE; } else if ( value.equalsIgnoreCase( CUSTOM.toString() ) ) { return CUSTOM; } throw new IllegalArgumentException( "Cannot parse ProjectReadAccessType value: " + value ); } @vbradnitski the `value` can be `NULL`, will be better to use `PRIVATE.name().equals(value)` or `Objects.equals(PRIVATE.name(), value)`. Also you can use `ProjectReadAccessType.valueOf(...)`

Target:
public static ProjectReadAccessType from( final String value ) { if ( PUBLIC.value.equals( value ) ) { return PUBLIC; } else if ( PRIVATE.value.equals( value ) ) { return PRIVATE; } else if ( CUSTOM.value.equals( value ) ) { return CUSTOM; } throw new IllegalArgumentException( "Cannot parse ProjectReadAccessType value: " + value ); }
Source:
public ProjectJson create( final MultipartForm form ) throws Exception { final Project project = projectService.create( createParams( form ) ); final ProjectPermissions projectPermissions = getPermissionsFromForm( form ); START projectService.modifyPermissions( project.getName(), getPermissionsFromForm( form ) ); END return new ProjectJson( project, projectPermissions ); } @vbradnitski you can use the `projectPermissions` variable instead of recall the `getPermissionsFromForm( form )` method.

Target:
public ProjectJson create( final MultipartForm form ) throws Exception { final Project project = projectService.create( createParams( form ) ); final ProjectPermissions projectPermissions = getPermissionsFromForm( form ); projectService.modifyPermissions( project.getName(), projectPermissions ); return new ProjectJson( project, projectPermissions ); }
Source:
public ContentAuditLogSupportImpl( final ContentConfig config, @Reference(service = ContentAuditLogExecutor.class) final Executor executor, @Reference AuditLogService auditLogService ) { START this.executor = config.auditlog_enabled() ? executor : null; END this.auditLogService = auditLogService; } Instead of null use `c -> {}` And remove all null checks `if ( executor != null )`

Target:
public ContentAuditLogSupportImpl( final ContentConfig config, @Reference(service = ContentAuditLogExecutor.class) final Executor executor, @Reference AuditLogService auditLogService ) { this.executor = config.auditlog_enabled() ? executor : c -> { }; this.auditLogService = auditLogService; }
Source:
private void register() { if ( this.clientReg != null ) { return; } START this.clientReg = context.registerService( EsClient.class, client, new Hashtable<>() ); END this.isRegistered = true; } don't pass empty Hashtable. pass null. Then legacy class is not in use and it is a few nanoseconds faster :)

Target:
private synchronized void register() { if ( this.clientReg != null ) { return; } this.clientReg = context.registerService( EsClient.class, client, null ); }
Source:
START private Boolean doDelete( final ProjectName projectName ) END { final DeleteRepositoryParams params = DeleteRepositoryParams.from( projectName.getRepoId() ); final RepositoryId deletedRepositoryId = this.repositoryService.deleteRepository( params ); return deletedRepositoryId != null; } boolean instead of Boolean

Target:
private boolean doDelete( final ProjectName projectName ) { final DeleteRepositoryParams params = DeleteRepositoryParams.from( projectName.getRepoId() ); final RepositoryId deletedRepositoryId = this.repositoryService.deleteRepository( params ); return deletedRepositoryId != null; }
Source:
public Certificate getCertificate(String alias) { try { return getUnderlyingKeyStore().getCertificate(alias); } catch (KeyStoreException e) { START logger.info("could not retrieve certificate for alias " + alias, e); END } return null; } better use error/warn log level

Target:
public Certificate getCertificate(String alias) { try { return getUnderlyingKeyStore().getCertificate(alias); } catch (KeyStoreException e) { logger.warn("could not retrieve certificate for alias " + alias, e); } return null; }
Source:
private SSLContext buildSslContext() { SSLContext sslContext = null; try { SSLContextBuilder sslBuilder = sslContextBuilder; if (trustSelfSignCert) { if (sslBuilder != null) { START throw new IllegalStateException("Cannot configure both SSLContextBuilder and TrustSelfSignCert"); END } // trust any self signed certificate sslBuilder = SSLContexts.custom().loadTrustMaterial(TrustSelfSignedMultiChainStrategy.INSTANCE); } if (sslBuilder != null) { sslContext = sslBuilder.build(); } } catch (Exception e) { e.printStackTrace(); } return sslContext != null ? sslContext : SSLContexts.createDefault(); } What is the reason for this validation?

Target:
private SSLContext buildSslContext() { SSLContext sslContext = null; try { SSLContextBuilder sslBuilder = sslContextBuilder; if (trustSelfSignCert) { if (sslBuilder == null) { sslBuilder = SSLContexts.custom(); } // trust any self signed certificate sslBuilder.loadTrustMaterial(TrustSelfSignedMultiChainStrategy.INSTANCE); } if (sslBuilder != null) { sslContext = sslBuilder.build(); } } catch (Exception e) { e.printStackTrace(); } return sslContext != null ? sslContext : SSLContexts.createDefault(); }
Source:
private static String normAutoRangeValue(Object objectValue) { START if (objectValue == null) return null; END String value = objectValue.toString(); if ("auto".equals(value)) { return value; } return normRangeValue(objectValue); } You don't really need a null check here, using `"auto".equals(objectValue)` is enough, if true return `objectValue.toString()`, otherwise continue on to `normRangeValue`. This can be important in case we decide to handle null values differently, and then we won't have to fix it in both places.

Target:
private static String normAutoRangeValue(Object objectValue) { if ("auto".equals(objectValue)) { return objectValue.toString(); } return normRangeValue(objectValue); }