auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void handleConsumed(ConsumerRecord record) { Span span = startAndFinishConsumerSpan(record); // remove propagation headers from the record tracing.propagation().keys().forEach(key -> record.headers().remove(key)); // Inject new propagation headers START tracing.propagation().injector(injector) END .inject(span.context(), record); } save some overhead by declaring injector as a field and reusing it. `injector = tracing.propagation().injector(injector)`

Target:
private void handleConsumed(ConsumerRecord record) { Span span = startAndFinishConsumerSpan(record); // remove propagation headers from the record tracing.propagation().keys().forEach(key -> record.headers().remove(key)); // Inject new propagation headers injector.inject(span.context(), record); }
Source:
public <T> T trace(String component, String operation, Callable<T> callable) throws RuntimeException { try { startNewSpan(component, operation); return callable.call(); } catch (Exception e) { START throw new RuntimeException(e.getMessage(), e); END } finally { finishSpan(); } } if something throws an exception, you should probably propagate it vs wrap

Target:
public <T> T trace(String component, String operation, Callable<T> callable) { try { startNewSpan(component, operation); return callable.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { finishSpan(); } }
Source:
public void trace(String component, String operation, Runnable runable) throws RuntimeException { try { startNewSpan(component, operation); runable.run(); } catch (Exception e) { START throw new RuntimeException(e.getMessage(), e); END } finally { finishSpan(); } } iirc Runnable doesn't have declared exceptions, so this will just wrap runtime exceptions in another runtime exception?

Target:
public void trace(String component, String operation, Runnable runable) { try { startNewSpan(component, operation); runable.run(); } finally { finishSpan(); } }
Source:
private void internalFinishSpan(Span span, long duration) { synchronized (span) { span.setDuration(duration); START reporter().report(span.toZipkin()); END } spanAndEndpoint().state().setCurrentLocalSpan(null); } Is it worth moving the reporting out of the synchronized block (though I wouldn't expect convention on that span)?

Target:
private void internalFinishSpan(Span span, long duration) { synchronized (span) { span.setDuration(duration); } reporter().report(span.toZipkin()); spanAndEndpoint().state().setCurrentLocalSpan(null); }
Source:
synchronized Long startTick(Span span) { START return span.startTick; END } Should this be synchronizing on the span rather than `this`?

Target:
Long startTick(Span span) { synchronized (span) { return span.startTick; } }
Source:
public URI getUri() { START return getRequest().url().uri(); END } It's wasteful to be calling `getRequest()` in these methods. Consider taking in the original `Request` and storing it in a field alongside the mutable result of `newBuilder()`

Target:
public URI getUri() { return request.url().uri(); }
Source:
public SVGReadParam() { super(); START allowExternalResources = true; END } Same here, just remove all this, and leave the value as `false`.

Target:
public SVGReadParam() { super(); }
Source:
private void decodeRowType2() throws IOException { START if(optionByteAligned) resetBuffer(); END decode1D(); } Code style: Always use curly brackets, and space after `if`.

Target:
private void decodeRowType2() throws IOException { if (optionByteAligned) { resetBuffer(); } decode1D(); }
Source:
private void decodeRowType4() throws IOException { START if(optionByteAligned) resetBuffer(); END eof: while (true) { // read till next EOL code Node n = eolOnlyTree.root; while (true) { n = n.walk(readBit()); if (n == null) { continue eof; } if (n.isLeaf) { break eof; } } } if (!optionG32D || readBit()) { decode1D(); } else { decode2D(); } } Code style: Always use curly brackets, and space after `if`.

Target:
private void decodeRowType4() throws IOException { if (optionByteAligned) { resetBuffer(); } eof: while (true) { // read till next EOL code Node n = eolOnlyTree.root; while (true) { n = n.walk(readBit()); if (n == null) { continue eof; } if (n.isLeaf) { break eof; } } } if (!optionG32D || readBit()) { decode1D(); } else { decode2D(); } }
Source:
private ImmutableList<Dimension> createDimensions(Iterable<Map<String, Object>> dimensions) { START if (dimensions == null) { END return ImmutableList.of(); } return FluentIterable.from(dimensions).transform(MAP_ENTRY_TO_DIMENSION).toList(); } Please handle the nullity in the constructor

Target:
private ImmutableList<Dimension> createDimensions(Iterable<Map<String, Object>> dimensions) { return FluentIterable.from(dimensions).transform(MAP_ENTRY_TO_DIMENSION).toList(); }
Source:
START public String getAlias() { END if (alias == null) { return null; } return alias; } No need to check whether alias is null

Target:
public String getAlias() { return alias; }
Source:
private void doMain() throws Exception { // Start the process START start(); END while (true) { // look for some terminator // attempt to read off queue // process message // TODO : Make something here, maybe watch for files? try { Thread.sleep(5); } catch (Exception e) { log.info("shutting down", e); break; } } unregisterMBeans(); } There are many unneeded changes, mostly code style, in this PR. Removing `this.` is not needed and adds unnecessary noise to this PR. Maybe move this to another PR.

Target:
private void doMain() throws Exception { // Start the process this.start(); while (true) { // look for some terminator // attempt to read off queue // process message // TODO : Make something here, maybe watch for files? try { Thread.sleep(5); } catch (Exception e) { log.info("shutting down", e); break; } } this.unregisterMBeans(); }
Source:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { START LogWriter logwriter = new LogWriter(logger,delimiter); END graphiteWriter.write(logwriter, server, query, results); } This logwriter could be a field, no need to instantiate a new one for each message.

Target:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { graphiteWriter.write(logwriter, server, query, results); }
Source:
protected void after() { System.setOut(originalOut); System.setErr(originalErr); // I guess it's useful to print this after completion START System.out.println("What was captured:"); END System.out.println(out); } I would disagree... It is the job of the client of OutputCapture to print stuff if it make sense. In most cases, it probably does not. And even if it does, it should be sent to a logger.

Target:
protected void after() { System.setOut(originalOut); System.setErr(originalErr); // I guess it's useful to print this after completion //System.out.println("What was captured:"); //System.out.println(out); }
Source:
public void close() throws IOException { markedAsDestroyed = true; if (connector != null) { START executor.submit(new Runnable() { END public void run() { if (connector != null) { try { connector.close(); } catch (IOException e) { logger.error("Error occurred during close connection {}", this, e); } } } }); } } Why delegate the closing to an executor?

Target:
public void close() { if (connector != null) { try { connector.close(); } catch (IOException e) { logger.error("Error occurred during close connection {}", this, e); } } }
Source:
public JMXConnection(@Nullable JMXConnector connector, @Nonnull MBeanServerConnection mBeanServerConnection) { this.connector = connector; this.mBeanServerConnection = mBeanServerConnection; this.markedAsDestroyed = false; START executor = Executors.newSingleThreadExecutor(); END } We should probably extract that executor at least as high as `MBeanServerConnectionFactory` and share it between connections. Keeping a single thread executor is probably fine for this case (if we have enough servers in trouble to saturate the single thread executor, we probably want to apply some back pressure to the connection pool anyway, we can tune that in the future if need be). This would also allow the use of a sameThreadExecutor in the test, slightly simpler.

Target:
public JMXConnection(@Nullable JMXConnector connector, @Nonnull MBeanServerConnection mBeanServerConnection) { this.connector = connector; this.mBeanServerConnection = mBeanServerConnection; this.markedAsDestroyed = false; }
Source:
public OpenTSDBWriter build() throws LifecycleException, UnknownHostException { return new OpenTSDBWriter( typeNames.build(), booleanAsNumber, debugEnabled, host, port, tags.build(), tagName, mergeTypeNamesTags, metricNamingExpression, START (addHostnameTag == null) ? true : addHostnameTag, END null ); } Damn autoboxing... A `firstNonNull()` would make findbugs happy. And cleaner still, as `addHostnameTag` is a Boolean object, `true` should be as well (so `Boolean.TRUE` in this case).

Target:
public OpenTSDBWriter build() throws LifecycleException, UnknownHostException { return new OpenTSDBWriter( typeNames.build(), booleanAsNumber, debugEnabled, host, port, tags.build(), tagName, mergeTypeNamesTags, metricNamingExpression, addHostnameTag, null ); }
Source:
public void stop() throws LifecycleException { try { target.stop(); START } catch (LifecycleException ex) { END throw(ex); } } Catching an Exception and just rethrowing it as-is is equivalent to not catching it at all. So the implementation of this method should be just `target.stop();`, with no exception management at all (much simpler!).

Target:
public void stop() throws LifecycleException { target.stop(); }
Source:
START private Boolean isHeartBeating() throws Exception { END Stat stat = this.clClient.checkExists().forPath(clConfig.getWorkerNodePath()); return (null != stat); } this should be `boolean` (with a small `b`).

Target:
private boolean isHeartBeating() throws Exception { Stat stat = this.clClient.checkExists().forPath(clConfig.getWorkerNodePath()); return (null != stat); }
Source:
START private Boolean hasAffinityForJvm(){ END return this.clConfig.getWorkerAlias().equals(this.affinity); } `boolean`with small `b`

Target:
private boolean hasAffinityForJvm() throws Exception{ return (affinity.isPresent() && clConfig.getWorkerAlias().equals(affinity.get())); }
Source:
public void setup() { START openTSDBMessageFormatter = Mockito.mock(OpenTSDBMessageFormatter.class); END writer = new OpenTSDBWriter2(openTSDBMessageFormatter); outputWriter = Mockito.mock(Writer.class); result = Mockito.mock(Result.class); } Just for fun ... I'd fid it more readable to have a static import of `Mockito.mock()` (this is a complete detail, feel free to ignore).

Target:
public void setup() { openTSDBMessageFormatter = mock(OpenTSDBMessageFormatter.class); writer = new OpenTSDBWriter2(openTSDBMessageFormatter); outputWriter = mock(Writer.class); result = mock(Result.class); }
Source:
public String getPid() { START if(this.pid == null) { END return null; } return this.pid; } This `if` is useless, if you remove it you will get the exact same behaviour.

Target:
public String getPid() { return this.pid; }
Source:
public void testValidationWithoutSettings() throws ValidationException { CloudWatchWriter writer = createCloudWatchWriter(); Query query = Query.builder() .setObj("test") .build(); Server server = Server.builder().setHost("localhost").setPort("123").build(); writer.validateSetup(server, query); START System.out.println("I got here"); END } Remove this. =)

Target:
public void testValidationWithoutSettings() throws ValidationException { CloudWatchWriter writer = createCloudWatchWriter(); Query query = Query.builder() .setObj("test") .build(); Server server = Server.builder().setHost("localhost").setPort("123").build(); writer.validateSetup(server, query); }
Source:
public void toggleFlagDown() { if (flagdown == true) { flagdown = false; } if (flagdown == false) { flagdown = true; } START } END This won´t work this way. Maybe u meant: `flagdown = !flagdown`?

Target:
public void toggleFlagDown() { flagdown = !flagdown; }
Source:
public boolean getFlagDown() { if (flagdown == true) { return true; } else{ return false; } START } END return flagdown; ?

Target:
public boolean getFlagDown() { return this.flagdown; }
Source:
public DroolsAbstractPMMLTest() { super(); START Properties props = System.getProperties(); props.setProperty("drools.dump.dir", "/home/gcardosi/NotBackedUp/old_pmml_dump_dir"); END } To be removed or at least moved to a different path :)

Target:
public DroolsAbstractPMMLTest() { super(); }
Source:
public Optional<KiePMMLModel> getModel(String modelName) { START logger.trace("getModel {}", modelName); END return KnowledgeBaseUtils.getModel(knowledgeBase, modelName); } Can you please add `isTraceEnabled` check?

Target:
public Optional<KiePMMLModel> getModel(String modelName) { return KnowledgeBaseUtils.getModel(knowledgeBase, modelName); }
Source:
private String fieldTypeUnwrapped() { if (fieldDMNType.isCollection()) { START String typeName = index.asJava(fieldDMNType.getBaseType()); END return typeName; } throw new IllegalArgumentException(); } here we rather 1) inline the whole statement 2) split into significant different statements (`index.asJava` and `fieldDMNType.getBaseType`)

Target:
private String fieldTypeUnwrapped() { if (fieldDMNType.isCollection()) { return index.asJava(fieldDMNType.getBaseType()); } throw new IllegalArgumentException(); }
Source:
private List getListFromSerializableCollection(Collection<?> objects) { List serializableItems = new ArrayList<>(objects.size()); START Iterator<? extends Object> iterator = objects.iterator(); END while (iterator.hasNext()) { Object o = iterator.next(); serializableItems.add(o); } return serializableItems; } You can use ``` serializableItems.addAll(objects); ``` instead of iterating the collection.

Target:
private List getListFromSerializableCollection(Collection<?> objects) { List serializableItems = new ArrayList<>(objects.size()); serializableItems.addAll(objects); return serializableItems; }
Source:
public static Properties getConfiguration(String filename) { Properties props = new Properties(); InputStream in = null; START try { END in = ClientUtils.class.getClassLoader().getResourceAsStream(filename); } catch (Exception e) { } finally { try { props.load(in); if(in != null) { in.close(); } } catch (IOException ioe) { } } return props; } You can use try with resources here so the Input stream is closed automatically.

Target:
public static Properties getConfiguration(String filename) { Properties props = new Properties(); try (InputStream in = ClientUtils.class.getClassLoader().getResourceAsStream(filename)) { props.load(in); } catch (IOException e) { logger.error(e.getMessage(), e); } return props; }
Source:
START protected <Z extends ScesimDataWithIndex> List<Z> toScesimDataWithIndex(BiFunction<Integer, T, Z> producer) { END List<Z> toReturn = new ArrayList<>(); List<T> data = getUnmodifiableData(); for (int index = 0; index < data.size(); index += 1) { toReturn.add(producer.apply(index + 1, data.get(index))); } return toReturn; } @danielezonca I think `<Z extends ScesimDataWithIndex<T>> `

Target:
protected <Z extends ScesimDataWithIndex<T>> List<Z> toScesimDataWithIndex(BiFunction<Integer, T, Z> producer) { List<Z> toReturn = new ArrayList<>(); List<T> data = getUnmodifiableData(); for (int index = 0; index < data.size(); index += 1) { toReturn.add(producer.apply(index + 1, data.get(index))); } return toReturn; }
Source:
private boolean isjPMMLAvailableToClassLoader(ClassLoader classLoader) { try { classLoader.loadClass("org.kie.dmn.jpmml.DMNjPMMLInvocationEvaluator"); return true; START } catch (ClassNotFoundException e) { END } return false; } Please handle this exception. Either rethrow or handle other way.

Target:
private boolean isjPMMLAvailableToClassLoader(ClassLoader classLoader) { try { classLoader.loadClass("org.kie.dmn.jpmml.DMNjPMMLInvocationEvaluator"); return true; } catch (ClassNotFoundException e) { return false; } }
Source:
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); START InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); END return dBuilder.parse(inputStream); } We do not close this stream nowhere, or am I missing something?

Target:
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); try (InputStream inputStream = new ByteArrayInputStream(xml.getBytes())) { return dBuilder.parse(inputStream); } }
Source:
protected Object createObject(String className, List<String> genericClasses) { if (ScenarioSimulationSharedUtils.isMap(className)) { return new HashMap(); } else { try { if (SIMPLE_TYPES_LIST.contains(className)) { return null; START } END return classLoader.loadClass(className).newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Impossible to instantiate " + className, e); } } } Can be the `className` null? If not I would maybe rewrite as [1], what do you think? My point is to not nesting expression into try catch, if an exception can not be thrown. [1] ```java if (ScenarioSimulationSharedUtils.isMap(className)) { return new HashMap(); } else if (SIMPLE_TYPES_LIST.contains(className)) { return null; } else { try { return classLoader.loadClass(className).newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Impossible to instantiate " + className, e); } } ```

Target:
protected Object createObject(String className, List<String> genericClasses) { if (ScenarioSimulationSharedUtils.isMap(className)) { return new HashMap(); } else { try { return classLoader.loadClass(className).newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Impossible to instantiate " + className, e); } } }
Source:
public boolean isThereANeedToSetDefaultType(final InterpolationVariable newVar, final InterpolationVariable oldVar) { START if (newVar.getDataType().equals(oldVar.getDataType()) END && Objects.equals(newVar.getFactType(), oldVar.getFactType()) && Objects.equals(newVar.getFactField(), oldVar.getFactField())) { return false; } else { return true; } } I'm surprised @jomarko didn't report this! It'd be more consistent to use `Objects.equals(...)` on all three checks.

Target:
public boolean isThereANeedToSetDefaultType(final InterpolationVariable newVar, final InterpolationVariable oldVar) { if (Objects.equals(newVar.getDataType(), oldVar.getDataType()) && Objects.equals(newVar.getFactType(), oldVar.getFactType()) && Objects.equals(newVar.getFactField(), oldVar.getFactField())) { return false; } else { return true; } }
Source:
public synchronized long getTimeToNextJob() { TimerJobInstance item = (TimerJobInstance) queue.peek(); START return (item != null && item.getTrigger().hasNextFireTime() != null) ? item.getTrigger().hasNextFireTime().getTime() - this.timer.get() : -1; END } This should also never happen.

Target:
public synchronized long getTimeToNextJob() { TimerJobInstance item = (TimerJobInstance) queue.peek(); return (item != null) ? item.getTrigger().hasNextFireTime().getTime() - this.timer.get() : -1; }
Source:
public boolean equals(Object o) { START if (this == o) END return true; if (o == null || getClass() != o.getClass()) return false; org.drools.constraint.parser.JavaToken javaToken = (org.drools.constraint.parser.JavaToken) o; if (kind != javaToken.kind) return false; if (!text.equals(javaToken.text)) return false; return true; } I know that this is a generated code, however please include curly braces for the ifs. Without them, the code could be misinterpreted more easily.

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } org.drools.constraint.parser.JavaToken javaToken = (org.drools.constraint.parser.JavaToken) o; if (kind != javaToken.kind) { return false; } if (!text.equals(javaToken.text)) { return false; } return true; }
Source:
public NullSafeFieldAccessExpr setName(final SimpleName name) { assertNotNull(name); if (name == this.name) { return (NullSafeFieldAccessExpr) this; } notifyPropertyChange(ObservableProperty.NAME, this.name, name); START if (this.name != null) END this.name.setParentNode(null); this.name = name; setAsParentNodeOf(name); return this; } Please add curly bracers here. Also please check other places, because I saw it also on more other places. You could use IDEA formatting highlights for that.

Target:
public NullSafeFieldAccessExpr setName(final SimpleName name) { assertNotNull(name); if (name == this.name) { return (NullSafeFieldAccessExpr) this; } notifyPropertyChange(ObservableProperty.NAME, this.name, name); if (this.name != null) { this.name.setParentNode(null); } this.name = name; setAsParentNodeOf(name); return this; }
Source:
public Object get(String name) { START return getCurrentEntries().get( EvalHelper.normalizeVariableName( name ) ); END } If the variable name is normalized on the set() method, is it necessary to normalize on the get() as well?

Target:
public Object get(String name) { return getCurrentEntries().get( name ); }
Source:
protected void initOutputClauses(CompilerContext feelctx, Map<String, CompiledFEELExpression> compilationCache) { START logger.info("Reading " + outputs.size() + " outputs from class loader"); END iterateOverOutputClauses((output, defaultValue) -> output.compiledDefault = (CompiledFEELExpression) readFieldWithRuntimeCheck(instanceName(getOutputName(defaultValue)))); } Can you please change these to `debug` ?

Target:
protected void initOutputClauses(CompilerContext feelctx, Map<String, CompiledFEELExpression> compilationCache) { logger.debug("Reading " + outputs.size() + " outputs from class loader"); iterateOverOutputClauses((output, defaultValue) -> output.compiledDefault = (CompiledFEELExpression) readFieldWithRuntimeCheck(instanceName(getOutputName(defaultValue)))); }
Source:
protected List<ExternalBeanDefinition> getExternalMiningClasses() { List<ExternalBeanDefinition> list = null; if (externalMiningFields != null && !externalMiningFields.isEmpty()) { list = externalMiningFields.stream() .map(ref -> ref.getBeanDefinition()) .distinct() .collect(Collectors.toList()); } START return list != null ? list : new ArrayList<>(); END } The fix proposed here may address some issue, but it does not address the issue that I have seen with drools-scorecards; mainly that there are some tests that periodically fail. I have applied the fixes from this PR to my local machine and I still get the intermittent errors in the ScorecardReasonCodeTest. Please see https://issues.jboss.org/browse/DROOLS-2592 to see my latest notes and results from my testing.

Target:
protected List<ExternalBeanDefinition> getExternalMiningClasses() { List<ExternalBeanDefinition> list = null; if (externalMiningFields != null && !externalMiningFields.isEmpty()) { list = externalMiningFields.stream() .map(ref -> ref.getBeanDefinition()) .distinct() .collect(Collectors.toList()); } // DO NOT USE Collections.emptyList() here!!! emptyList() returns an EmptyList instance // which is an internal class from Collections class, therefore not accessible // by reflection - when mvel parses a RuleUnit template and there is // a size call, it tries to invoke the method using reflection return list != null ? list : new ArrayList<>(0); }
Source:
public static String normalizeVariableName(String name) { START if (normalizationCache.containsKey(name)){ END return normalizationCache.get(name); } String normalized = SPACES_PATTERN.matcher( name.trim() ).replaceAll( " " ); normalizationCache.put(name, normalized); return normalized; } Are we caching the result of the application of a regular expression to a String here? Unless there are very good reason to do this, and we can demonstrate it with a benchmark, this seems really a bad idea.

Target:
public static String normalizeVariableName(String name) { return SPACES_PATTERN.matcher( name.trim() ).replaceAll( " " ); }
Source:
public ExternalBeanDefinition(String beanInfo) throws Exception { if (beanInfo == null || beanInfo.isEmpty()) { START throw new Exception("External type name missing"); END } int lastPos = beanInfo.lastIndexOf("."); if (lastPos >= 0) { this.beanPackageName = beanInfo.substring(0, lastPos); this.beanName = beanInfo.substring(lastPos + 1); } else { this.beanPackageName = DEFAULT_BEAN_PKG; this.beanName = beanInfo; } } Please don't use general Exception type for throwing exceptions. This makes handling of such exceptions very hard, because the type of the exception is hidden. For this, IllegalArgumentException can be used - it makes the exception specific - Illegal value for beanInfo argument was provided. Minor edit: please reformat the throw line, it is off to the right by 4 spaces.

Target:
public ExternalBeanDefinition(String beanInfo) throws IllegalArgumentException { if (beanInfo == null || beanInfo.isEmpty()) { throw new IllegalArgumentException("External type name missing"); } int lastPos = beanInfo.lastIndexOf("."); if (lastPos >= 0) { this.beanPackageName = beanInfo.substring(0, lastPos); this.beanName = beanInfo.substring(lastPos + 1); } else { this.beanPackageName = DEFAULT_BEAN_PKG; this.beanName = beanInfo; } }
Source:
public ExternalBeanRef(String modelFieldName, String beanInfo, ModelUsage usage) throws Exception { this.modelFieldName = modelFieldName; this.usage = usage; try { START this.beanDefinition = new ExternalBeanDefinition(beanInfo); END } catch (Exception e) { throw new Exception("Unable to construct ExternalBeanRef. ", e); } } Please reformat this try-catch.

Target:
public ExternalBeanRef(String modelFieldName, String beanInfo, ModelUsage usage) throws IllegalArgumentException { this.modelFieldName = modelFieldName; this.usage = usage; try { this.beanDefinition = new ExternalBeanDefinition(beanInfo); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unable to construct ExternalBeanRef. ", e); } }
Source:
protected void initFieldMaps() { try { initMiningFieldMap(); initOutputFieldMap(); START } catch(Exception e) { END logger.error(e.getMessage()); } } Please don't catch general Exception class, this could catch also exceptions that we don't want to be catched. E.g. NullPointerException.

Target:
protected void initFieldMaps() throws IllegalArgumentException { initMiningFieldMap(); initOutputFieldMap(); }
Source:
static FEEL newInstance() { START return new FEELImpl(Thread.currentThread().getContextClassLoader()); END } Same here, better to wrap the classloader creation inside a method.

Target:
static FEEL newInstance() { return new FEELImpl(); }
Source:
public JPAPlaceholderResolverStrategy(String persistenceUnit, ClassLoader cl) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { // override tccl so persistence unit can be found from within given class loader - e.g. kjar Thread.currentThread().setContextClassLoader(cl); this.emf = Persistence.createEntityManagerFactory(persistenceUnit); initializeManagedClasses(); this.closeEmf = true; } finally { Thread.currentThread().setContextClassLoader(tccl); } this.classLoader = cl; START this.name += ":" + persistenceUnit; END } I believe this is breaking backward compatibility as it will register itself with different name then it was persisted before this change so I think we should make it via additional cunstructor so we won't break existing sessions

Target:
public JPAPlaceholderResolverStrategy(String persistenceUnit, ClassLoader cl) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { // override tccl so persistence unit can be found from within given class loader - e.g. kjar Thread.currentThread().setContextClassLoader(cl); this.emf = Persistence.createEntityManagerFactory(persistenceUnit); initializeManagedClasses(); this.closeEmf = true; } finally { Thread.currentThread().setContextClassLoader(tccl); } this.classLoader = cl; }
Source:
public void testCopy() { final DSLVariableValue original = new DSLVariableValue("value"); final DSLVariableValue copy = original.copy(); assertEquals(original, copy); START assertNotSame(original, END copy); } You could possibly check values too (but I guess, if the ```equals()``` method is broken we're really screwed!)

Target:
public void testCopy() { final DSLVariableValue original = new DSLVariableValue("value"); final DSLVariableValue copy = original.copy(); assertEquals(original.getValue(), copy.getValue()); assertEquals(original, copy); assertNotSame(original, copy); }
Source:
public XStreamMarshaller (List<DMNExtensionRegister> extensionRegisters) { this.extensionRegisters = new ArrayList<DMNExtensionRegister>(); START this.extensionRegisters.addAll(extensionRegisters); END } `new ArrayList<>(extensionRegisters)` will do the same thing, with the additional benefit of properly sizing the list.

Target:
public XStreamMarshaller (List<DMNExtensionRegister> extensionRegisters) { this.extensionRegisters.addAll(extensionRegisters); }
Source:
public void testInsertFirstAndAdd2() throws Exception { KieSession ksession = session.getStateful(); insertNotEvent(ksession); ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isFalse(); insertNotEvent(ksession, "different value"); insertNotEvent(ksession, "different value"); START insertNotEvent(ksession, "different value"); END ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isTrue(); } Looks like a loop.

Target:
public void testInsertFirstAndAdd2() throws Exception { KieSession ksession = session.getStateful(); insertNotEvent(ksession); ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isFalse(); for (int i = 0; i < 3; i++) { insertNotEvent(ksession, "different value"); } ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isTrue(); }
Source:
private boolean equalsIgnoreNull(Object o1, Object o2) { START return o1 != null ? o1.equals(o2) : o2 != null; END } If the o1 is diff than null, o1 must equals o2. If the o1 is null, return "o2 is _diff than_ null" ? I think this second part is wrong?

Target:
private boolean equalsIgnoreNull(Object o1, Object o2) { return o1 != null ? o1.equals(o2) : o2 == null; }
Source:
public Object getResult(VarianceData data) { START return new Double(data.squaredSum / data.count); END } new Double() is redundant here

Target:
public Double getResult(VarianceData data) { return data.squaredSum / data.count; }
Source:
public Object getResult(VarianceData data) { START return new Double(Math.sqrt(data.squaredSum / data.count)); END } new Double is redundant here

Target:
public Double getResult(VarianceData data) { return Math.sqrt(super.getResult(data)); }
Source:
private void startScanTask(long pollingInterval) { status = Status.RUNNING; this.pollingInterval = pollingInterval; timer = new Timer(true); START timer.schedule(new ScanTask(this), pollingInterval, pollingInterval); END } ScanTask is a non-static inner class, so it already has a reference to this and it is not necessary to pass it.

Target:
private void startScanTask(long pollingInterval) { status = Status.RUNNING; this.pollingInterval = pollingInterval; timer = new Timer(true); timer.schedule(new ScanTask(), pollingInterval, pollingInterval); }
Source:
private void logActiveFacts() { LOGGER.warn("facts: "); for (FactHandle handle : session.getFactHandles()) { LOGGER.warn(handle.toString()); START } END } Again, could be a much nicer one-liner using Java 8 streams and/or `StringJoiner`.

Target:
private void logActiveFacts() { LOGGER.warn("facts: "); session.getFactHandles().stream().map(Object::toString).forEach(LOGGER::warn); }
Source:
@Override protected DataSource getDatasourceImpl( String dataSourceName ) throws Exception { START IDBDatasourceService datasourceService = PentahoSystem.getObjectFactory().get( IDBDatasourceService.class, null ); END return datasourceService.getDataSource( dataSourceName ); } @jvelasques , Override is usually in the previous line

Target:
protected DataSource getDatasourceImpl( String dataSourceName ) throws Exception { IDBDatasourceService datasourceService = PentahoSystem.getObjectFactory().get( IDBDatasourceService.class, null ); return datasourceService.getDataSource( dataSourceName ); }
Source:
protected String getRequestParameterAsString( String parameter, String defaultValue, String encoding ) throws UnsupportedEncodingException { String enc = StringUtils.isEmpty( encoding ) ? CharsetHelper.getEncoding() : encoding; START END if( getRequestParameters() != null && getRequestParameters().hasParameter( parameter ) ){ return URLDecoder.decode( getRequestParameters().getStringParameter( parameter, defaultValue ) ); } return defaultValue; } @pedrofvteixeira , enc is not being used in the decode call. Is that on purpose ?

Target:
protected String getRequestParameterAsString( String parameter, String defaultValue, String encoding ) throws UnsupportedEncodingException { String enc = StringUtils.isEmpty( encoding ) ? CharsetHelper.getEncoding() : encoding; if( getRequestParameters() != null && getRequestParameters().hasParameter( parameter ) ){ return URLDecoder.decode( getRequestParameters().getStringParameter( parameter, defaultValue ), enc ); } return defaultValue; }
Source:
public boolean supports(MediaType delimiter) { START if (this.mediaTypes == null) { END return true; } else { for (MediaType mediaType : this.mediaTypes) { if (mediaType.isCompatibleWith(delimiter)) { return true; } } return false; } } This by definition will never happen, I think we have to check for an empty collection here.

Target:
public boolean supports(MediaType delimiter) { if (this.mediaTypes.isEmpty()) { return true; } else { for (MediaType mediaType : this.mediaTypes) { if (mediaType.isCompatibleWith(delimiter)) { return true; } } return false; } }
Source:
public boolean advancePhase(float minWeight) { boolean changed = false; for (QueryTree child : children) { changed |= child.advancePhase(minWeight); } START children.sort(Comparator.comparingDouble(QueryTree::weight)); END return changed; } If changed is false, do the children need to be resorted?

Target:
public boolean advancePhase(float minWeight) { boolean changed = false; for (QueryTree child : children) { changed |= child.advancePhase(minWeight); } if (changed == false) { return false; } children.sort(Comparator.comparingDouble(QueryTree::weight)); return changed; }
Source:
private DisjunctionNode(List<QueryTree> children) { START this.children.addAll(children); END this.children.sort(Comparator.comparingDouble(QueryTree::weight)); } Instead of making new ArrayList in the class body, could move the new ArrayList to within constructor = this.children = new ArrayList<>(children) which would exactly size every time.

Target:
private DisjunctionNode(List<QueryTree> children) { this.children = new ArrayList<>(children); this.children.sort(Comparator.comparingDouble(QueryTree::weight)); }
Source:
public List<String> getMetadataDatasourceIds() { List<String> metadataIds = new ArrayList<String>(); Set<String> domainIds = metadataDomainRepository.getDomainIds(); START List<String> domainsIdArr = new ArrayList<>( domainIds ); END for ( String id : domainsIdArr ) { if ( isMetadataDatasource( id ) ) { metadataIds.add( id ); } } return metadataIds; } Why do this ? You can iterate over the set just fine - no need to copy it to an arraylist

Target:
public List<String> getMetadataDatasourceIds() { List<String> metadataIds = new ArrayList<String>(); for ( String id : metadataDomainRepository.getDomainIds() ) { if ( isMetadataDatasource( id ) ) { metadataIds.add( id ); } } return metadataIds; }
Source:
public void removeDatasourceConfirm() { if ( messageBundle != null ) { XulLabel removeDatasourceConfirmationDialogLabel = (XulLabel) removeDatasourceConfirmationDialog.getElementById( "removeDatasourceConfirmationDialogLabel" ); START LogicalModelSummary logicalModelSummary = getDialogResult(); END removeDatasourceConfirmationDialogLabel.setValue( messageBundle.getString( REMOVE_DS_MSG_ID, logicalModelSummary.getModelName() ) ); } removeDatasourceConfirmationDialog.show(); } This method happily returns null from time to time. Kaboom? And yeah, I know, that binding probably should not be active if there is no selection. But at the same time would it hurt to add a explicit if (datasourceSelectionDialogModel.getSelectedIndex() == -1) return; to the method to protect it?

Target:
public void removeDatasourceConfirm() { if ( messageBundle != null ) { XulLabel removeDatasourceConfirmationDialogLabel = (XulLabel) removeDatasourceConfirmationDialog.getElementById( "removeDatasourceConfirmationDialogLabel" ); LogicalModelSummary logicalModelSummary = getDialogResult(); if ( removeDatasourceConfirmationDialogLabel != null && logicalModelSummary != null ) { removeDatasourceConfirmationDialogLabel.setValue( messageBundle.getString( REMOVE_DS_MSG_ID, logicalModelSummary.getModelName() ) ); } } removeDatasourceConfirmationDialog.show(); }
Source:
public DatasourceService() { START metadataDomainRepositoryReal = PentahoSystem.get( IMetadataDomainRepository.class, PentahoSessionHolder.getSession() ); END metadataDomainRepository = new PentahoMetadataDomainRepository( getRepository() ); mondrianCatalogService = PentahoSystem.get( IMondrianCatalogService.class, PentahoSessionHolder.getSession() ); repositoryFileAclAdapter = new RepositoryFileAclAdapter(); } We very rarely, almost never, directly construct an Implementation like this. What happens if an OEM has their own MetadataDomainRepository which needs to be used? A better solution is query for the "real" and the "plain" beans metadataDomainRepositoryReal = PentahoSystem.get( IMetadataDomainRepository.class, "IMetadataDomainRepositoryImpl", PentahoSessionHolder.getSession() ); metadataDomainRepository = PentahoSystem.get( IMetadataDomainRepository.class, "IMetadataDomainRepository", PentahoSessionHolder.getSession() );

Target:
public DatasourceService() { metadataDomainRepository = PentahoSystem.get( IMetadataDomainRepository.class, PentahoSessionHolder.getSession() ); mondrianCatalogService = PentahoSystem.get( IMondrianCatalogService.class, PentahoSessionHolder.getSession() ); repositoryFileAclAdapter = new RepositoryFileAclAdapter(); }
Source:
START private String getPropertySortOrder(Sort.Order order) { END StringBuilder sb = new StringBuilder(); if(order.isIgnoreCase()){ sb.append("toLower(").append(order.getProperty()).append(")"); } else { sb.append(order.getProperty()); } sb.append(" ").append(order.getDirection()); return sb.toString(); } ```suggestion private static String getPropertySortOrder(Sort.Order order) { ```

Target:
private static String getPropertySortOrder(Sort.Order order) { StringBuilder sb = new StringBuilder(); if(order.isIgnoreCase()){ sb.append("toLower(").append(order.getProperty()).append(")"); } else { sb.append(order.getProperty()); } sb.append(" ").append(order.getDirection()); return sb.toString(); }
Source:
private Filter createLowerBoundFilter(Object value, boolean inclusive) { Filter filter = createBoundFilter(Bound.LOWER, value, inclusive); START filter.setBooleanOperator(booleanOperator); END return filter; } Can we pass on the operator on both of those (lower and upper)? The "and" is used for the boolean operator between previous and this or this and next?

Target:
private Filter createLowerBoundFilter(Object value, boolean inclusive) { return createBoundFilter(Bound.LOWER, value, inclusive, booleanOperator); }
Source:
private static DatabaseHolder createAndStartEmbeddedInstance() throws IOException { START final File dataStore1 = Files.createTempDirectory("neo4j.db").toFile(); END final GraphDatabaseService graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(dataStore1) .newGraphDatabase(); return new DatabaseHolder(dataStore1, graphDatabaseService); } Why `final` at variable level?

Target:
private static DatabaseHolder createAndStartEmbeddedInstance() throws IOException { File dataStore1 = Files.createTempDirectory("neo4j.db").toFile(); GraphDatabaseService graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(dataStore1) .newGraphDatabase(); return new DatabaseHolder(dataStore1, graphDatabaseService); }
Source:
public List<Filter> build(Stack<Object> params) { START final Object value = params.pop(); END final Filter filter = new Filter(propertyName(), convertToComparisonOperator(part.getType()), value); filter.setOwnerEntityType(entityType); filter.setBooleanOperator(booleanOperator); filter.setNegated(isNegated()); setNestedAttributes(part, filter); applyCaseInsensitivityIfShouldIgnoreCase(part, filter); return Collections.singletonList(filter); } We usually don `final` local variables.

Target:
public List<Filter> build(Stack<Object> params) { Object value = params.pop(); Filter filter = new Filter(propertyName(), convertToComparisonOperator(part.getType()), value); filter.setOwnerEntityType(entityType); filter.setBooleanOperator(booleanOperator); filter.setNegated(isNegated()); setNestedAttributes(part, filter); applyCaseInsensitivityIfShouldIgnoreCase(part, filter); return Collections.singletonList(filter); }
Source:
private static void attachShutdownHook() { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { LOGGER.info("JMXFetch is closing"); // Properly close log handlers START LogManager.shutdown(); END } } ); } Definitely not! JMXFetch is known to have quite a bit of code that could use some cleanup, so this is definitely welcome.

Target:
private static void attachShutdownHook() { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { log.info("JMXFetch is closing"); // Properly close log handlers LogManager.shutdown(); } } ); }
Source:
public void displayMatchingAttributeName(JMXAttribute jmxAttribute, int rank, int limit) { START LOGGER.debug(" Matching: " + rank + "/" + limit + ". " + jmxAttribute); END } These methods have associated commands in `datadog-agent` (stuff like `datadog-agent jmxfetch list-matching`) that is expected to print to stdout always, as it's a debugging command. These `LOGGER.debug` changes, unless I'm missing something, would make it subject to the log level, thus potentially breaking the agent commands. If we're going to keep this, it should probably be `info` or `warning` at the least - still maybe preferable to print to `stdout`.... 🤔

Target:
public void displayMatchingAttributeName(JMXAttribute jmxAttribute, int rank, int limit) { LOGGER.info(" Matching: " + rank + "/" + limit + ". " + jmxAttribute); }
Source:
private String getCassandraAlias() { if (renameCassandraMetrics()) { Map<String, String> beanParameters = getBeanParameters(); START String type = beanParameters.get("type"); END String metricName = beanParameters.get("name"); String attributeName = getAttributeName(); if (attributeName.equals("Value")) { return "cassandra." + metricName; } return "cassandra." + metricName + "." + attributeName; } //Deprecated Cassandra metric. Remove domain prefix. return getDomain().replace("org.apache.", "") + "." + getAttributeName(); } This variable is never used.

Target:
private String getCassandraAlias() { if (renameCassandraMetrics()) { Map<String, String> beanParameters = getBeanParameters(); String metricName = beanParameters.get("name"); String attributeName = getAttributeName(); if (attributeName.equals("Value")) { return "cassandra." + metricName; } return "cassandra." + metricName + "." + attributeName; } //Deprecated Cassandra metric. Remove domain prefix. return getDomain().replace("org.apache.", "") + "." + getAttributeName(); }
Source:
protected void sendMetricPoint(String metricName, double value, String[] tags) { if (System.currentTimeMillis() - this.initializationTime > 300 * 1000) { this.statsDClient.stop(); init(); } START statsDClient.gauge(StatsdReporter.formatDataName(metricName), value, tags); END } `metricName` should be alias names defined in user configurations. I don't think we want/need to format it.

Target:
protected void sendMetricPoint(String metricName, double value, String[] tags) { if (System.currentTimeMillis() - this.initializationTime > 300 * 1000) { this.statsDClient.stop(); init(); } statsDClient.gauge(metricName, value, tags); }
Source:
private void sendEvent(E e) { String message = _layout.doLayout(e); if (message == null) { throw new IllegalArgumentException(String.format( "The logback layout %s is probably incorrect, " + "and fails to format the message.", _layout.toString())); } START this.sender.send( END "", message, "", "", null, null, "" ); } This looks a bit odd by passing in several empty args. Is there a better way of doing this?

Target:
private void sendEvent(E e) { String message = _layout.doLayout(e); if (message == null) { throw new IllegalArgumentException(String.format( "The logback layout %s is probably incorrect, " + "and fails to format the message.", _layout.toString())); } this.sender.send(message); }
Source:
protected BaseCommand(SelectedOptions selectedOptions) { this.options = selectedOptions; this.paths = selectedOptions.getPaths(); if (options.isQuiet()) { this.printStream = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { // throw away output START } END }); } } There's a setter for the printstream. This should use that but also it's also interesting that this shows a design flaw that we could set the printstream and override the quiet option without knowing it.

Target:
protected BaseCommand(SelectedOptions selectedOptions) { this.options = selectedOptions; this.paths = selectedOptions.getPaths(); if (options.isQuiet()) { this.printStream = new PrintStream(new OutputStream() { @Override public void write(int b) { // throw away output } }); } }
Source:
public BitOutputStream(Object outputBase, long outputAddress, int outputSize) { checkArgument(outputSize >= SIZE_OF_LONG, "Output buffer too small"); this.outputBase = outputBase; container = 0; START bitCount = 0; END this.outputAddress = outputAddress; outputLimit = this.outputAddress + outputSize - SIZE_OF_LONG; currentAddress = this.outputAddress; } Did you want to initialize these to Java defaults?

Target:
public BitOutputStream(Object outputBase, long outputAddress, int outputSize) { checkArgument(outputSize >= SIZE_OF_LONG, "Output buffer too small"); this.outputBase = outputBase; this.outputAddress = outputAddress; outputLimit = this.outputAddress + outputSize - SIZE_OF_LONG; currentAddress = this.outputAddress; }
Source:
public int compress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) { int tableSize = computeTableSize(inputLength); Arrays.fill(table, 0, tableSize, 0); long inputAddress = ARRAY_BYTE_BASE_OFFSET + inputOffset; long outputAddress = ARRAY_BYTE_BASE_OFFSET + outputOffset; START return Lz4RawCompressor.compress(input, inputAddress, inputLength, output, outputAddress, maxOutputLength, table, tableSize); END } I find it a bit strange that you calculate and initialize the table outside of the compressor instead of leaving these private details to the raw compressor code. It is also strange that there is a min table size but it is defined outside the compressor logic

Target:
public int compress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) { long inputAddress = ARRAY_BYTE_BASE_OFFSET + inputOffset; long outputAddress = ARRAY_BYTE_BASE_OFFSET + outputOffset; return Lz4RawCompressor.compress(input, inputAddress, inputLength, output, outputAddress, maxOutputLength, table); }
Source:
START public void readyToForward() END { started = true; if(created.get() == 0) forward(); } This needs to be synchronised, as otherwise threads might not see the updated value of 'started'.

Target:
public synchronized void readyToForward() { started = true; if(created.get() == 0) forward(); }