auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static byte[] getSha1(InputStream shaFis) throws IOException { MessageDigest sha1; try { sha1 = MessageDigest.getInstance("SHA-1"); int bufSiz = 1024; byte buf[] = new byte[bufSiz]; int bytesRead; while ((bytesRead = shaFis.read(buf)) != -1) { sha1.update(buf, 0, bytesRead); } } catch (NoSuchAlgorithmException e){ throw new IllegalStateException(e); <START> } catch (IOException e) { <END> throw e; } return sha1.digest(); }</code><technical_language>Remove catch block for IOException</technical_language>

Target:
public static byte[] getSha1(InputStream shaFis) throws IOException { MessageDigest sha1; try { sha1 = MessageDigest.getInstance("SHA-1"); int bufSiz = 1024; byte buf[] = new byte[bufSiz]; int bytesRead; while ((bytesRead = shaFis.read(buf)) != -1) { sha1.update(buf, 0, bytesRead); } } catch (NoSuchAlgorithmException e){ throw new IllegalStateException(e); } return sha1.digest(); }
Source:
<code>public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://mymangacomics.com/index.php/([a-zA-Z0-9-]*)$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } <START> throw new MalformedURLException("Expected imgur.com URL format: " + <END> "mymangacomics.com/index.php/albumName - got " + url + " instead"); }</code><technical_language>Replace imgur.com</technical_language>

Target:
public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://mymangacomics.com/index.php/([a-zA-Z0-9-]*)$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } throw new MalformedURLException("Expected mymangacomics.com URL format: " + "mymangacomics.com/index.php/albumName - got " + url + " instead"); }
Source:
<code>protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { String pathInfo = req.getPathInfo(); CIServer ciServer = CIServerFactory.getServer(pathInfo, jenkins, req.getParameterMap(), authContext.getCurrentUser(), projectService); <START> Map<String,String[]> parameters = req.getParameterMap(); <END> for (String parameter:parameters.keySet()){ logger.debug("doPost: parameter "+parameter+ " contains values:"); for(String value:parameters.get(parameter)){ logger.debug(" - \""+value+"\""); } } if (req.getParameter("submit").equals("Test Jenkins Settings")) { render(res, ciServer.JENKINS_SETTINGS, ciServer.testSettings()); } else { boolean clearSettings = req.getParameter("clear-settings") != null && "on".equals(req.getParameter("clear-settings")); Map<String, Object> renderLoc = ciServer.postSettings(clearSettings); if (renderLoc != null) { render(res, ciServer.JENKINS_SETTINGS, renderLoc); } else { doGet(req, res); } } } catch (Exception e) { logger.error("Exception in CIServlet.doPost: " + e.getMessage(), e); } }</code><technical_language>Is this artifact debugging? If so, please remove this change</technical_language>

Target:
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { String pathInfo = req.getPathInfo(); CIServer ciServer = CIServerFactory.getServer(pathInfo, jenkins, req.getParameterMap(), authContext.getCurrentUser(), projectService); if (req.getParameter("submit").equals("Test Jenkins Settings")) { render(res, ciServer.JENKINS_SETTINGS, ciServer.testSettings()); } else { boolean clearSettings = req.getParameter("clear-settings") != null && "on".equals(req.getParameter("clear-settings")); Map<String, Object> renderLoc = ciServer.postSettings(clearSettings); if (renderLoc != null) { render(res, ciServer.JENKINS_SETTINGS, renderLoc); } else { doGet(req, res); } } } catch (Exception e) { logger.error("Exception in CIServlet.doPost: " + e.getMessage(), e); } }
Source:
<code>public void create() { if (cidrlist != null) { throw new InvalidParameterValueException( "Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); } Ip privateIp = getVmSecondaryIp(); if (privateIp != null) { if (!NetUtils.isValidIp4(privateIp.toString())) { throw new InvalidParameterValueException("Invalid vm ip address"); } } try { PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId, privateIp, getOpenFirewall(), isDisplay()); setEntityId(result.getId()); setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.trace("Network Rule Conflict: ", ex); <START> throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); <END> } }</code><technical_language>code is throwing a new exception. instead of ex.getMessage(), ex a parameter; then, stack logged full stack trace, this point in code. Ex: throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex);</technical_language>

Target:
public void create() { if (cidrlist != null) { throw new InvalidParameterValueException( "Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); } Ip privateIp = getVmSecondaryIp(); if (privateIp != null) { if (!NetUtils.isValidIp4(privateIp.toString())) { throw new InvalidParameterValueException("Invalid vm ip address"); } } try { PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId, privateIp, getOpenFirewall(), isDisplay()); setEntityId(result.getId()); setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException ex) { s_logger.trace("Network Rule Conflict: ", ex); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage(), ex); } }
Source:
<code>public void testNormalize() throws Exception { List<URL> urls = new ArrayList<URL>(); urls.add(new URL("jar:file:/tmp/mesos/slaves/3014350f-cd05-44af-9c9c-3974bdeed86e-S1/frameworks/3014350f-cd05-44af-9c9c-3974bdeed86e-0016/executors/3014350f-cd05-44af-9c9c-3974bdeed86e-S1/runs/3697bc14-f0bd-48b9-8599-9683867eec63/elasticsearch-spark_2.10-2.2.0-m1.jar!/")); urls.add(new URL("jar:file:/tmp/mesos/slaves/3014350f-cd05-44af-9c9c-3974bdeed86e-S1/frameworks/3014350f-cd05-44af-9c9c-3974bdeed86e-0016/executors/3014350f-cd05-44af-9c9c-3974bdeed86e-S1/runs/3697bc14-f0bd-48b9-8599-9683867eec63/./elasticsearch-spark_2.10-2.2.0-m1.jar!/")); <START> File file = new File(urls[0].toString); <END> if (file.createNewFile()){ System.out.println("File is created!"); } else { System.out.println("File already exists."); } List<String> normalized = StringUtils.normalize(urls); System.out.println(normalized); assertEquals(1, normalized.size()); }</code><technical_language>This compile for me? urls.get(0).toString()</technical_language>

Target:
public void testNormalize() throws Exception { List<URL> urls = new ArrayList<URL>(); urls.add(new URL("jar:file:/tmp/mesos/slaves/3014350f-cd05-44af-9c9c-3974bdeed86e-S1/frameworks/3014350f-cd05-44af-9c9c-3974bdeed86e-0016/executors/3014350f-cd05-44af-9c9c-3974bdeed86e-S1/runs/3697bc14-f0bd-48b9-8599-9683867eec63/elasticsearch-spark_2.10-2.2.0-m1.jar!/")); urls.add(new URL("jar:file:/tmp/mesos/slaves/3014350f-cd05-44af-9c9c-3974bdeed86e-S1/frameworks/3014350f-cd05-44af-9c9c-3974bdeed86e-0016/executors/3014350f-cd05-44af-9c9c-3974bdeed86e-S1/runs/3697bc14-f0bd-48b9-8599-9683867eec63/./elasticsearch-spark_2.10-2.2.0-m1.jar!/")); String originPath = url.get(0).toString(); File file = new File(originPath); if (file.createNewFile()){ System.out.println("File is created!"); } else { System.out.println("File already exists."); } Path existingFilePath = Paths.get(originPath); Path symLinkPath = Paths.get(System.getProperty("java.io.tmpdir") + File.separator + "elasticsearch-spark_2.10-2.2.0-m1.jar"); Files.createSymbolicLink(symLinkPath, existingFilePath); Set<String> normalized = StringUtils.normalize(urls); System.out.println(normalized); assertEquals(1, normalized.size()); }
Source:
<code>public boolean matches(Attribute<?> other) { if (other == null) return false; if (!this.definition.equals(other.definition)) return false; if (this.definition.isGlobal()) { if (Matchable.class.isAssignableFrom(this.definition.getType())) { return ((Matchable)value).matches(other.value); <START> } else if (value != null) { <END> return value.equals(other.value); } else { return other.value == null; } } return true; }</code><technical_language>suggestion } else { return Objects.equals(value, other.value); }</technical_language>

Target:
public boolean matches(Attribute<?> other) { if (other == null) return false; if (!this.definition.equals(other.definition)) return false; if (this.definition.isGlobal()) { if (Matchable.class.isAssignableFrom(this.definition.getType())) { return ((Matchable)value).matches(other.value); } else { return Objects.equals(value, other.value); } } return true; }
Source:
<code>protected ConnectionAnchor createAnchor(PrecisionPoint p) { if (!myLinkLFIsEnabled) { return super.createAnchor(p); } if (p == null) { return createDefaultAnchor(); } <START> ConnectionAnchor result; <END> if (followSVGPapyrusPath) { result = new PapyrusSlidableSnapToGridAnchor(this, p); } else { result = new SlidableRoundedRectangleAnchor(this, p); } ((PapyrusSlidableSnapToGridAnchor) result).setEditPart(myHost); return result; }</code><technical_language>create a "PapyrusSlidableSnapToGridAnchor" variable instead of "ConnectionAnchor"</technical_language>

Target:
protected ConnectionAnchor createAnchor(PrecisionPoint p) { if (!myLinkLFIsEnabled) { return super.createAnchor(p); } if (p == null) { return createDefaultAnchor(); } PapyrusSlidableSnapToGridAnchor result; if (followSVGPapyrusPath) { result = new PapyrusSlidableSnapToGridAnchor(this, p); } else { result = new SlidableRoundedRectangleAnchor(this, p); } result.setEditPart(myHost); return result; }
Source:
<code>public void testExportPackageCannotContainJavaPackages() throws Exception { File config = OSGiTestsActivator.getContext().getDataFile(getName()); Map<String, String> headers = new HashMap<String, String>(); headers.put(Constants.BUNDLE_MANIFESTVERSION, "2"); headers.put(Constants.BUNDLE_SYMBOLICNAME, getName()); headers.put(Constants.EXPORT_PACKAGE, JAVA_LANG); config.mkdirs(); File bundle = SystemBundleTests.createBundle(config, getName(), headers); Equinox equinox = new Equinox(Collections.singletonMap(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath())); try { equinox.start(); BundleContext systemContext = equinox.getBundleContext(); Bundle testBundle = systemContext.installBundle(bundle.toURI().toString()); testBundle.start(); fail("Failed to test Export-Package header"); } catch (BundleException e) { <START> assertTrue("It should throw a Bundle Exception stating Invalid manifest header Export-Package", e.getMessage().contains("Cannot specify java.* packages in Export headers")); <END> } finally { try { equinox.stop(); equinox.waitForStop(10000); } catch (Exception e) { } } }</code><technical_language>assert BundleException.getType is org.osgi.framework.BundleException.MANIFEST_ERROR</technical_language>

Target:
public void testExportPackageCannotContainJavaPackages() throws Exception { File config = OSGiTestsActivator.getContext().getDataFile(getName()); Map<String, String> headers = new HashMap<String, String>(); headers.put(Constants.BUNDLE_MANIFESTVERSION, "2"); headers.put(Constants.BUNDLE_SYMBOLICNAME, getName()); headers.put(Constants.EXPORT_PACKAGE, JAVA_LANG); config.mkdirs(); File bundle = SystemBundleTests.createBundle(config, getName(), headers); Equinox equinox = new Equinox(Collections.singletonMap(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath())); try { equinox.start(); BundleContext systemContext = equinox.getBundleContext(); Bundle testBundle = systemContext.installBundle(bundle.toURI().toString()); testBundle.start(); fail("Failed to test Export-Package header"); } catch (BundleException e) { assertEquals("It should throw a bundle exception of type manifest error", BundleException.MANIFEST_ERROR, e.getType()); assertTrue("It should throw a Bundle Exception stating Invalid manifest header Export-Package", e.getMessage().contains("Cannot specify java.* packages in Export headers")); } finally { try { equinox.stop(); equinox.waitForStop(10000); } catch (Exception e) { } } }
Source:
<code>public void verifyTextEllipsis(int anchorIndex) { waitForElementVisibleByElement(noChevrons.get(anchorIndex)); waitForElementVisibleByElement(chevrons.get(anchorIndex)); <START> if (noChevrons.get(anchorIndex).getCssValue("text-overflow").contains("ellipsis") && chevrons.get(anchorIndex).getCssValue("text-overflow").contains("ellipsis")) { <END> PageObjectLogging.log("verifyTextEllipsis", "CSS selector is set to ellipsis", true); } else { PageObjectLogging.log("verifyTextEllipsis", "CSS sellector isn't set to ellipsis", false); } }</code><technical_language>extract booleans 2 variables right if block, improve readibility</technical_language>

Target:
public void verifyTextEllipsis(int anchorIndex) { waitForElementVisibleByElement(noChevrons.get(anchorIndex)); waitForElementVisibleByElement(chevrons.get(anchorIndex)); boolean noChevronsEllipsis = noChevrons.get(anchorIndex).getCssValue("text-overflow").contains("ellipsis"); boolean chevronsEllipsis = chevrons.get(anchorIndex).getCssValue("text-overflow").contains("ellipsis"); if (noChevronsEllipsis && chevronsEllipsis) { PageObjectLogging.log("verifyTextEllipsis", "CSS selector is set to ellipsis", true); } else { PageObjectLogging.log("verifyTextEllipsis", "CSS sellector isn't set to ellipsis", false); } }
Source:
<code>public void test_coverage() { coverageSensor.execute(context); <START> testUtAndItReportsCoverageData(); <END> }</code><technical_language>start this method name assert verb,</technical_language>

Target:
public void test_coverage() { settings.setProperty(JavaScriptPlugin.LCOV_REPORT_PATHS, TWO_REPORTS); coverageSensor.execute(context); assertTwoReportsCoverageDataPresent(); }
Source:
<code>public static String getStandardDeviationString(double[] standardDeviationDoubles) { if (standardDeviationDoubles == null) { return null; } StringBuilder standardDeviationString = new StringBuilder(standardDeviationDoubles.length * 9); <START> DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(); <END> decimalFormatSymbols.setDecimalSeparator('.'); DecimalFormat exponentialFormat = new DecimalFormat("0.0#E0"); exponentialFormat.setDecimalFormatSymbols(decimalFormatSymbols); DecimalFormat decimalFormat = new DecimalFormat("0.0#"); decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols); boolean first = true; for (double standardDeviationDouble : standardDeviationDoubles) { if (first) { first = false; } else { standardDeviationString.append("/"); } String abbreviated; if (0.001 <= standardDeviationDouble && standardDeviationDouble <= 10000000.0) { abbreviated = decimalFormat.format(standardDeviationDouble); } else { abbreviated = exponentialFormat.format(standardDeviationDouble); } standardDeviationString.append(abbreviated); } return standardDeviationString.toString(); }</code><technical_language>this work? DecimalFormatSymbols symbols = new DecimalFormatSymbols(EN_US); DecimalFormat exponentialFormat = new DecimalFormat("0.0#E0", symbols);</technical_language>

Target:
public static String getStandardDeviationString(double[] standardDeviationDoubles) { if (standardDeviationDoubles == null) { return null; } StringBuilder standardDeviationString = new StringBuilder(standardDeviationDoubles.length * 9); DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.US); DecimalFormat exponentialFormat = new DecimalFormat("0.0#E0", decimalFormatSymbols); DecimalFormat decimalFormat = new DecimalFormat("0.0#", decimalFormatSymbols); boolean first = true; for (double standardDeviationDouble : standardDeviationDoubles) { if (first) { first = false; } else { standardDeviationString.append("/"); } String abbreviated; if (0.001 <= standardDeviationDouble && standardDeviationDouble <= 10000000.0) { abbreviated = decimalFormat.format(standardDeviationDouble); } else { abbreviated = exponentialFormat.format(standardDeviationDouble); } standardDeviationString.append(abbreviated); } return standardDeviationString.toString(); }
Source:
<code>private void emitAssociationCreatedEvent(String publicIpId, HostAndPort publicEndpoint, Location location, int privatePort) { AssociationMetadata metadata = new AssociationMetadata(publicIpId, publicEndpoint, location, privatePort); for (Map.Entry<AssociationListener, Predicate<? super AssociationMetadata>> entry : associationListeners.entrySet()) { if (entry.getValue().apply(metadata)) { <START> entry.getKey().onAssociationCreated(metadata); <END> } } }</code><technical_language>wrap this in try-catch block, log.warn exception. exception in listener other listeners called. However, in catch block do Exceptions.propagateIfFatal(e). for call onAssociationDeleted(metadata)</technical_language>

Target:
private void emitAssociationCreatedEvent(String publicIpId, HostAndPort publicEndpoint, Location location, int privatePort) { AssociationMetadata metadata = new AssociationMetadata(publicIpId, publicEndpoint, location, privatePort); for (Map.Entry<AssociationListener, Predicate<? super AssociationMetadata>> entry : associationListeners.entrySet()) { if (entry.getValue().apply(metadata)) { try { entry.getKey().onAssociationCreated(metadata); } catch (Exception e) { Exceptions.propagateIfFatal(e); log.warn("Exception thrown when emitting association creation event " + metadata, e); } } } }
Source:
<code>public void should_use_upstream_trigger() { FreeStyleJob main = jenkins.jobs.create(FreeStyleJob.class); FreeStyleJob trigger = jenkins.jobs.create(FreeStyleJob.class); <START> main.edit(() -> { <END> UpstreamJobTrigger configuration = main.addTrigger(UpstreamJobTrigger.class); configuration.setUpstreamProjects(trigger.name); }); Build build = trigger.scheduleBuild().shouldSucceed(); assertThat(build.getConsole(), containsString("Triggering a new build of %s", main.name)); Build automaticallyStartedBuild = main.build(1); automaticallyStartedBuild.waitUntilFinished(); assertThat(automaticallyStartedBuild.getConsole(), containsString("Started by upstream project \"%s\"", trigger.name)); }</code><technical_language>edit? public <T> T configure(Callable<T> body), noticed this sneaked in... Anyway, if need signature please stick name configure</technical_language>

Target:
public void should_use_upstream_trigger() { FreeStyleJob main = jenkins.jobs.create(FreeStyleJob.class); FreeStyleJob trigger = jenkins.jobs.create(FreeStyleJob.class); main.configure(() -> { UpstreamJobTrigger configuration = main.addTrigger(UpstreamJobTrigger.class); configuration.setUpstreamProjects(trigger.name); }); Build build = trigger.scheduleBuild().shouldSucceed(); assertThat(build.getConsole(), containsString("Triggering a new build of %s", main.name)); Build automaticallyStartedBuild = main.build(1); automaticallyStartedBuild.waitUntilFinished(); assertThat(automaticallyStartedBuild.getConsole(), containsString("Started by upstream project \"%s\"", trigger.name)); }
Source:
<code>public LookupElement[] calculateLookupItems(ExpressionContext context) { LookupElement[] lookupItems; int offset = context.getStartOffset(); Project project = context.getProject(); PsiDocumentManager.getInstance(project).commitAllDocuments(); assert context.getEditor() != null; PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument()); assert file != null; PsiElement elementAt = file.findElementAt(offset); GoParameters parameters = PsiTreeUtil.getParentOfType(elementAt, GoParameters.class); Set<LookupElement> set = new LinkedHashSet<LookupElement>(); if (parameters == null) { for (String name : myNames) { set.add(LookupElementBuilder.create(name)); } lookupItems = set.toArray(new LookupElement[set.size()]); return lookupItems; } GoParamDefinition parameter = PsiTreeUtil.getParentOfType(elementAt, GoParamDefinition.class); Set<String> parameterNames = new HashSet<String>(); for (GoParameterDeclaration paramDecl : parameters.getParameterDeclarationList()) { for (GoParamDefinition paramDef : paramDecl.getParamDefinitionList()) { if (parameter == paramDef) continue; parameterNames.add(paramDef.getName()); } } for (String name : myNames) { <START> if (parameterNames.contains(name)) { <END> int j = 1; while (parameterNames.contains(name + j)) j++; name += j; } set.add(LookupElementBuilder.create(name)); } lookupItems = set.toArray(new LookupElement[set.size()]); return lookupItems; }</code><technical_language>please investigate com.intellij.util.text.UniqueNameGenerator</technical_language>

Target:
public LookupElement[] calculateLookupItems(ExpressionContext context) { int offset = context.getStartOffset(); Project project = context.getProject(); PsiDocumentManager.getInstance(project).commitAllDocuments(); assert context.getEditor() != null; PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument()); assert file != null; PsiElement elementAt = file.findElementAt(offset); Set<String> parameterNames = new HashSet<String>(); GoParameters parameters = PsiTreeUtil.getParentOfType(elementAt, GoParameters.class); if (parameters != null) { GoParamDefinition parameter = PsiTreeUtil.getParentOfType(elementAt, GoParamDefinition.class); for (GoParameterDeclaration paramDecl : parameters.getParameterDeclarationList()) { for (GoParamDefinition paramDef : paramDecl.getParamDefinitionList()) { if (parameter == paramDef) continue; parameterNames.add(paramDef.getName()); } } } Set<LookupElement> set = new LinkedHashSet<LookupElement>(); for (String name : myNames) { String newName = UniqueNameGenerator.generateUniqueName(name, new Condition<String>() { @Override public boolean value(String s) { return !parameterNames.contains(s); } }); set.add(LookupElementBuilder.create(newName)); } return set.toArray(new LookupElement[set.size()]); }
Source:
<code>public final void setExtendedExpiresOn(final Date extendedExpiresOn) { <START> mExtendedExpiresOn = (Date) extendedExpiresOn.clone(); <END> }</code><technical_language>If want create a new date, i do new Date(extendedExpirsOn.getTime()). Also, curious, change set for Date this</technical_language>

Target:
public final void setExtendedExpiresOn(final Date extendedExpiresOn) { mExtendedExpiresOn = Utility.getImmutableDateObject(extendedExpiresOn); }
Source:
<code>public void warmup() throws InterruptedException { Random random = new Random(); values = new byte[valueCount][]; for (int k = 0; k < values.length; k++) { int delta = maxSize - minSize; int length = delta == 0 ? minSize : minSize + random.nextInt(maxSize - minSize); values[k] = generateByteArray(random, length); } MapStreamer<Integer, Object> streamer = MapStreamerFactory.getInstance(map); for (int key : keys) { <START> streamer.pushEntry(key, values[random.nextInt(values.length)]); <END> } streamer.await(); }</code><technical_language>values is random. do of choosing values this? int index = 0; MapStreamer<Integer, Object> streamer = MapStreamerFactory.getInstance(map); for (int key : keys) { streamer.pushEntry(key, values[++index % valueCount]); }</technical_language>

Target:
public void warmup() throws InterruptedException { Random random = new Random(); values = new byte[valueCount][]; for (int k = 0; k < values.length; k++) { int delta = maxSize - minSize; int length = delta == 0 ? minSize : minSize + random.nextInt(delta); values[k] = generateByteArray(random, length); } MapStreamer<Integer, Object> streamer = MapStreamerFactory.getInstance(map); for (int key : keys) { streamer.pushEntry(key, values[random.nextInt(values.length)]); } streamer.await(); }
Source:
<code><START> protected void firstListenerAdded() { <END> if (getRealm().isCurrent()) { startListeningInternal(); } else { getRealm().asyncExec(() -> { if (hasListeners && !isListening) { startListeningInternal(); } }); } hasListeners = true; super.firstListenerAdded(); }</code><technical_language>final</technical_language>

Target:
protected final void firstListenerAdded() { if (getRealm().isCurrent()) { startListeningInternal(); } else { getRealm().asyncExec(() -> { if (hasListeners && !isListening) { startListeningInternal(); } }); } hasListeners = true; super.firstListenerAdded(); }
Source:
<code>public void play(AudioStream audioStream, String sinkId, PercentType volume) { if (audioStream == null) { throw new NullPointerException("Audio stream cannot be played as it is null."); } AudioSink sink = getSink(sinkId); if (sink != null) { <START> PercentType oldVolume = getVolume(sinkId); <END> if (volume != null) { setVolume(volume, sinkId); } if (sink.getSupportedStreams().stream().anyMatch(clazz -> clazz.isInstance(audioStream))) { try { sink.process(audioStream); } catch (UnsupportedAudioFormatException | UnsupportedAudioStreamException e) { logger.warn("Error playing '{}': {}", audioStream, e.getMessage(), e); } } else { logger.warn("Failed playing audio stream '{}' as audio doesn't support it.", audioStream); } if (oldVolume != null) { setVolume(oldVolume, sinkId); } } else { logger.warn("Failed playing audio stream '{}' as no audio sink was found.", audioStream); } }</code><technical_language>handle volume if process stream. I suggest move "volume" stuff if below</technical_language>

Target:
public void play(AudioStream audioStream, String sinkId, PercentType volume) { Objects.requireNonNull(audioStream, "Audio stream cannot be played as it is null."); AudioSink sink = getSink(sinkId); if (sink != null && sink.getSupportedStreams().stream().anyMatch(clazz -> clazz.isInstance(audioStream))) { PercentType oldVolume = getVolume(sinkId); if (volume != null) { setVolume(volume, sinkId); } try { sink.process(audioStream); } catch (UnsupportedAudioFormatException | UnsupportedAudioStreamException e) { logger.warn("Error playing '{}': {}", audioStream, e.getMessage(), e); } finally { if (oldVolume != null) { setVolume(oldVolume, sinkId); } } } else { logger.warn( "Failed playing audio stream '{}' as no audio sink was found or audio sink doesn't support the stream.", audioStream); } }
Source:
<code>public void deleteEntry(@RequestParam String entryId) { Entry entry = entryService.getEntryById(entryId); if (UserServiceImpl.hasRole(0)) { entryService.deleteEntry(entry.getId()); smtpMailSender.sendToParticipants(entry, "Trainings", emailMessages.deleteEntry(entry)); } else { entry.getTraining().setStatus(TrainingStatus.DRAFTED); trainingService.updateTraining(entry.getTraining()); EntryDTO entryDTO = new EntryDTO(entry); entryDTO.setEventDescription("Trainer wants to cancel lecture at " + entry.getBeginTime().toString() + <START> " on training \"" + entry.getTraining().getName() + "\"."); <END> trainingEventService.addEvent(new TrainingEvent(entryDTO)); } }</code><technical_language>please externalize this message</technical_language>

Target:
public void deleteEntry(@RequestParam String entryId) { Entry entry = entryService.getEntryById(entryId); if (UserUtil.hasRole(0)) { entryService.deleteEntry(entry.getId()); smtpMailSender.sendToUsers(trainingService.getTrainingById(entry.getTraining().getId()).getParticipants(), "Trainings", emailMessages.deleteEntry(entry)); } else { entry.getTraining().setStatus(TrainingStatus.DRAFTED); trainingService.updateTraining(entry.getTraining()); EntryDTO entryDTO = new EntryDTO(entry); entryDTO.setEventDescription(emailMessages.deleteEntryToAdmin(entry)); trainingEventService.addEvent(new TrainingEvent(entryDTO)); smtpMailSender.sendToUsers(userService.getUsersByRole(UserRole.ADMIN), "Changes in training", emailMessages.deleteEntryToAdmin(entry)); } }
Source:
<code>public boolean equals(Object obj) { if (obj instanceof GitModelCommit) { GitModelCommit objCommit = (GitModelCommit) obj; RevCommit objBaseCommit = objCommit.getBaseCommit(); <START> return objBaseCommit == null ? baseCommit == null : objBaseCommit <END> .equals(baseCommit) && objCommit.getRemoteCommit().equals(remoteCommit) && objCommit.getLocation().equals(getLocation()); } return false; }</code><technical_language>This off. If other model's base commit is 'null', check if a base commit is 'null'? locations and/or remote commits of models differ other, no? location, remote commit, base commit consideration in hashCode() implementation factored implementation of equals(Object)</technical_language>

Target:
public boolean equals(Object obj) { if (obj instanceof GitModelCommit) { GitModelCommit objCommit = (GitModelCommit) obj; boolean equalsBaseCommit; RevCommit objBaseCommit = objCommit.getBaseCommit(); if (objBaseCommit != null) equalsBaseCommit = objBaseCommit.equals(baseCommit); else equalsBaseCommit = baseCommit == null; return equalsBaseCommit && objCommit.getRemoteCommit().equals(remoteCommit) && objCommit.getLocation().equals(getLocation()); } return false; }
Source:
<code>public boolean validateConcurStandardAccountingExtractDetailLineWithObjectCodeOverride(ConcurStandardAccountingExtractDetailLine line, ConcurStandardAccountingExtractBatchReportData reportData, String overriddenObjectCode, String overriddenSubObjectCode) { boolean valid = validateConcurStandardAccountingExtractDetailLineBase(line, reportData); <START> valid = validateAccountingLineWithObjectCodeOverrides(line, reportData, overriddenSubObjectCode, null) && valid; <END> return valid; }</code><technical_language>Based new method signature, arg object code fourth sub-object code</technical_language>

Target:
public boolean validateConcurStandardAccountingExtractDetailLineWithObjectCodeOverride(ConcurStandardAccountingExtractDetailLine line, ConcurStandardAccountingExtractBatchReportData reportData, String overriddenObjectCode, String overriddenSubObjectCode) { boolean valid = validateConcurStandardAccountingExtractDetailLineBase(line, reportData); valid = validateAccountingLineWithObjectCodeOverrides(line, reportData, overriddenObjectCode, overriddenSubObjectCode) && valid; return valid; }
Source:
<code>String getMessagesFromMap(final Map<String, String> keyValues) { <START> ObjectNode node = new ObjectMapper().createObjectNode(); <END> for (Map.Entry<String, String> entry : keyValues.entrySet()) { node.put(entry.getKey(), entry.getValue()); } return node.size() > 0 ? node.toString() : null; }</code><technical_language>create ObjectMapper invocation, instead of ObjectMapper field initialized (package-private) constructor</technical_language>

Target:
String getMessagesFromMap(final Map<String, String> keyValues) { ObjectNode node = objectMapper.createObjectNode(); for (Map.Entry<String, String> entry : keyValues.entrySet()) { node.put(entry.getKey(), entry.getValue()); } return node.size() > 0 ? node.toString() : null; }
Source:
<code>public Object getImage(Object object) { final UMLDiff umlDiff = (UMLDiff)object; Object image = null; if (umlDiff.getDiscriminant() instanceof Element) { image = getImage(getRootAdapterFactory(), umlDiff.getDiscriminant()); } else { image = super.getImage(object); } if (overlayProvider != null && image != null) { Object diffImage = overlayProvider.getComposedImage(umlDiff, image); <START> return ((UMLDiffItemProvider)delegate()).getOverlayImage(object, diffImage); <END> } else { return image; } }</code><technical_language>retrieved image, if is "null", overlayed longer needs "overlayImage". Remove call "UMLDiffItemProvider.getOverlayImage". method removed UMLDiffItemProvider altogether</technical_language>

Target:
public Object getImage(Object object) { final UMLDiff umlDiff = (UMLDiff)object; Object image = null; if (umlDiff.getDiscriminant() instanceof Element) { image = getImage(getRootAdapterFactory(), umlDiff.getDiscriminant()); } else { image = super.getImage(object); } if (overlayProvider != null && image != null) { image = overlayProvider.getComposedImage(umlDiff, image); } return image; }
Source:
<code>public void testInvalidDeferredUntilNotSpecified() throws Exception { LocationBackingForm venue = aLocationBackingForm().withId(1L).build(); Date deferredUntil = new Date(new Date().getTime() -(1000 *60 * 60 * 24)); DeferralBackingForm deferralBackingForm = aDeferralBackingForm() .withDeferralReason(aDeferralReasonBackingForm().withId(DEFERRAL_REASON_ID).build()) .withVenue(venue) .withDeferredDonor(aDonorBackingForm().withId(DEFERRED_DONOR_ID).build()) .withDeferredUntil(deferredUntil) .withDeferralDate(new Date()) .build(); mockFormFields(); when(locationRepository.verifyLocationExists(1L)).thenReturn(true); when(donorRepository.verifyDonorExists(DEFERRED_DONOR_ID)).thenReturn(true); when(deferralReasonRepository.verifyDeferralReasonExists(DEFERRAL_REASON_ID)).thenReturn(true); Errors errors = new MapBindingResult(new HashMap<String, String>(), "deferral"); deferralBackingFormValidator.validate(deferralBackingForm, errors); Assert.assertEquals("Errors exist", 1, errors.getErrorCount()); Assert.assertNotNull("Error on deferredUntil", errors.getFieldError("deferredUntil")); <START> Assert.assertEquals("Error on deferral date",0, deferralBackingForm.getDeferredUntil().compareTo(deferralBackingForm.getDeferredUntil())); <END> }</code><technical_language>@tumijacob is this asserting</technical_language>

Target:
public void testInvalidDeferredUntilNotSpecified() throws Exception { LocationBackingForm venue = aLocationBackingForm().withId(1L).build(); DeferralBackingForm deferralBackingForm = aDeferralBackingForm() .withDeferralReason(aDeferralReasonBackingForm().withId(DEFERRAL_REASON_ID).build()) .withVenue(venue) .withDeferredDonor(aDonorBackingForm().withId(DEFERRED_DONOR_ID).build()) .withDeferralDate(new Date()) .build(); mockFormFields(); when(locationRepository.verifyLocationExists(1L)).thenReturn(true); when(donorRepository.verifyDonorExists(DEFERRED_DONOR_ID)).thenReturn(true); when(deferralReasonRepository.verifyDeferralReasonExists(DEFERRAL_REASON_ID)).thenReturn(true); Errors errors = new MapBindingResult(new HashMap<String, String>(), "deferral"); deferralBackingFormValidator.validate(deferralBackingForm, errors); Assert.assertEquals("Errors exist", 1, errors.getErrorCount()); Assert.assertNotNull("Error on deferredUntil", errors.getFieldError("deferredUntil")); }
Source:
<code>private boolean isPlatformKeybindingBug517068Fixed() { Bundle bundle = Platform.getBundle("org.eclipse.e4.ui.bindings"); Version currentVersion = bundle.getVersion(); <START> Version fixVersion = new Version(0, 12, 100); <END> return currentVersion.compareTo(fixVersion) >= 0; }</code><technical_language>Bug 517068 is targeting 0.12.1. 0.12.100 right now, backported 0.12.1</technical_language>

Target:
private boolean isPlatformKeybindingBug517068Fixed() { Bundle bundle = Platform.getBundle("org.eclipse.e4.ui.bindings"); Version currentVersion = bundle.getVersion(); Version fixVersion = new Version(0, 12, 1); return currentVersion.compareTo(fixVersion) >= 0; }
Source:
<code>public int compare(DiagnosticDescriptor o1, DiagnosticDescriptor o2) { String sourceFileName1 = o1.getSourceFileName() != null ? o1.getSourceFileName() : ""; String sourceFileName2 = o2.getSourceFileName() != null ? o2.getSourceFileName() : ""; int result = sourceFileName1.compareTo( sourceFileName2 ); if ( result != 0 ) { return result; } <START> if ( o1.getLine() != null && o2.getLine() != null ) { <END> result = o1.getLine().compareTo( o2.getLine() ); if ( result != 0 ) { return result; } } return o1.getKind().compareTo( o2.getKind() ); }</code><technical_language>This is messager is null, right? output a line</technical_language>

Target:
public int compare(DiagnosticDescriptor o1, DiagnosticDescriptor o2) { String sourceFileName1 = o1.getSourceFileName() != null ? o1.getSourceFileName() : ""; String sourceFileName2 = o2.getSourceFileName() != null ? o2.getSourceFileName() : ""; int result = sourceFileName1.compareTo( sourceFileName2 ); if ( result != 0 ) { return result; } result = o1.getLine().compareTo( o2.getLine() ); if ( result != 0 ) { return result; } return o1.getKind().compareTo( o2.getKind() ); }
Source:
<code>VoltMessage asVoltMessage() { byte signatureBytes = signature.getBytes(Constants.UTF8ENCODING); <START> ByteBuffer buf = ByteBuffer.allocate(20 + signatureBytes.length); <END> buf.put((byte)ExportManager.RELEASE_BUFFER); buf.putInt(partitionId); buf.putInt(signatureBytes.length); buf.put(signatureBytes); buf.putLong(uso); buf.putInt(tuplesSent); return new BinaryPayloadMessage(new byte[0], buf.array()); }</code><technical_language>21 instead of 20</technical_language>

Target:
VoltMessage asVoltMessage() { byte signatureBytes = signature.getBytes(Constants.UTF8ENCODING); ByteBuffer buf = ByteBuffer.allocate(21 + signatureBytes.length); buf.put((byte)ExportManager.RELEASE_BUFFER); buf.putInt(partitionId); buf.putInt(signatureBytes.length); buf.put(signatureBytes); buf.putLong(uso); buf.putInt(tuplesSent); return new BinaryPayloadMessage(new byte[0], buf.array()); }
Source:
<code>private void suggestEnableAnnotations(Project project, NotificationGroup group) { <START> String annotationProcessorsConfigName = new AnnotationProcessorsConfigurable(project).getDisplayName(); <END> Notification notification = group.createNotification(LombokBundle.message("config.warn.annotation-processing.disabled.title"), LombokBundle.message("config.warn.annotation-processing.disabled.message", project.getName()), NotificationType.ERROR, (not, e) -> { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { enableAnnotations(project); } }); Notifications.Bus.notify(notification, project); }</code><technical_language>This variable obsolete, is anywhere</technical_language>

Target:
private void suggestEnableAnnotations(Project project, NotificationGroup group) { Notification notification = group.createNotification(LombokBundle.message("config.warn.annotation-processing.disabled.title"), LombokBundle.message("config.warn.annotation-processing.disabled.message", project.getName()), NotificationType.ERROR, (not, e) -> { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { enableAnnotations(project); not.expire(); } }); Notifications.Bus.notify(notification, project); }
Source:
<code>DefaultBlockWorker(BlockMasterClientPool blockMasterClientPool, FileSystemMasterClient fileSystemMasterClient, Sessions sessions, BlockStore blockStore, UfsManager ufsManager) { <START> super(ExecutorServiceFactories.fixedThreadPool("block-worker-executor", 4)); <END> mBlockMasterClientPool = blockMasterClientPool; mBlockMasterClient = mBlockMasterClientPool.acquire(); mFileSystemMasterClient = fileSystemMasterClient; mHeartbeatReporter = new BlockHeartbeatReporter(); mMetricsReporter = new BlockMetricsReporter(); mSessions = sessions; mBlockStore = blockStore; mWorkerId = new AtomicReference<>(-1L); mBlockStore.registerBlockStoreEventListener(mHeartbeatReporter); mBlockStore.registerBlockStoreEventListener(mMetricsReporter); mUfsManager = ufsManager; mUnderFileSystemBlockStore = new UnderFileSystemBlockStore(mBlockStore, ufsManager); Metrics.registerGauges(this); }</code><technical_language>is this heartbeat thread else</technical_language>

Target:
DefaultBlockWorker(BlockMasterClientPool blockMasterClientPool, FileSystemMasterClient fileSystemMasterClient, Sessions sessions, BlockStore blockStore, UfsManager ufsManager) { super(ExecutorServiceFactories.fixedThreadPool("block-worker-executor", 5)); mResourceCloser = Closer.create(); mBlockMasterClientPool = mResourceCloser.register(blockMasterClientPool); mFileSystemMasterClient = mResourceCloser.register(fileSystemMasterClient); mHeartbeatReporter = new BlockHeartbeatReporter(); mMetricsReporter = new BlockMetricsReporter(); mSessions = sessions; mBlockStore = blockStore; mWorkerId = new AtomicReference<>(-1L); mBlockStore.registerBlockStoreEventListener(mHeartbeatReporter); mBlockStore.registerBlockStoreEventListener(mMetricsReporter); mUfsManager = ufsManager; mUnderFileSystemBlockStore = new UnderFileSystemBlockStore(mBlockStore, ufsManager); Metrics.registerGauges(this); }
Source:
<code>private ExecutableElement getOverriddenMethod(ExecutableElement currentMethod, TypeElement typeElement) { if ( typeElement == null ) { return null; } for ( Element element : elementUtils.getAllMembers( typeElement ) ) { if ( !element.getKind().equals( ElementKind.METHOD ) ) { continue; } <START> if ( elementUtils.overrides( currentMethod, (ExecutableElement) element, getEnclosingTypeElement( currentMethod ) ) ) { <END> return (ExecutableElement) element; } } return null; }</code><technical_language>get enclosing element loop ? this operation is expensive ? like: TypeElement methodEnclosingType = getEnclosingTypeElement( currentMethod ); for (...){ .... if ( elementUtils.overrides( currentMethod, (ExecutableElement) element, methodEnclosingType ) ) {</technical_language>

Target:
private ExecutableElement getOverriddenMethod(ExecutableElement currentMethod, TypeElement typeElement) { if ( typeElement == null ) { return null; } TypeElement enclosingTypeElement = getEnclosingTypeElement( currentMethod ); for ( Element element : elementUtils.getAllMembers( typeElement ) ) { if ( !element.getKind().equals( ElementKind.METHOD ) ) { continue; } if ( elementUtils.overrides( currentMethod, (ExecutableElement) element, enclosingTypeElement ) ) { return (ExecutableElement) element; } } return null; }
Source:
<code>protected void executeCommand() { VmHandler.LockVm(getVm().getDynamicData(), getCompensationContext()); freeLock(); <START> getDisksBasedOnImage(); <END> if (disksImages.isEmpty()) { endSuccessfullySynchronous(); } else { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { MoveOrCopyAllImageGroups(); return null; } }); if (!getReturnValue().getTaskIdList().isEmpty()) { setSucceeded(true); } } }</code><technical_language>in this case I this method wrapped a getSnappableDisks method (which return a list of DiskImages) a hasSnappableDisks method internally right perform call + isEmpty check. clear care is snappable disks diskimages</technical_language>

Target:
protected void executeCommand() { VmHandler.LockVm(getVm().getDynamicData(), getCompensationContext()); freeLock(); if (!hasSnappableDisks()) { endSuccessfullySynchronous(); } else { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { MoveOrCopyAllImageGroups(); return null; } }); if (!getReturnValue().getTaskIdList().isEmpty()) { setSucceeded(true); } } }
Source:
<code>protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { return false; } IStatus status1 = totalsModule.schedule(); IStatus status2 = eventTypesModule.schedule(); if (!(status1.isOK() && status2.isOK())) { <START> cancelSubAnalyses(); <END> return false; } totalsModule.waitForInitialization(); eventTypesModule.waitForInitialization(); ITmfStateSystem totalsSS = totalsModule.getStateSystem(); ITmfStateSystem eventTypesSS = eventTypesModule.getStateSystem(); if (totalsSS == null || eventTypesSS == null) { throw new IllegalStateException(); } fStatistics = new TmfStateStatistics(totalsSS, eventTypesSS); fInitialized.countDown(); if (!(totalsModule.waitForCompletion(monitor) && eventTypesModule.waitForCompletion(monitor))) { return false; } return true; }</code><technical_language>countDown</technical_language>

Target:
protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { fInitialized.countDown(); return false; } IStatus status1 = totalsModule.schedule(); IStatus status2 = eventTypesModule.schedule(); if (!(status1.isOK() && status2.isOK())) { cancelSubAnalyses(); fInitialized.countDown(); return false; } totalsModule.waitForInitialization(); eventTypesModule.waitForInitialization(); ITmfStateSystem totalsSS = totalsModule.getStateSystem(); ITmfStateSystem eventTypesSS = eventTypesModule.getStateSystem(); if (totalsSS == null || eventTypesSS == null) { fInitialized.countDown(); return false; } fStatistics = new TmfStateStatistics(totalsSS, eventTypesSS); fInitialized.countDown(); if (!(totalsModule.waitForCompletion(monitor) && eventTypesModule.waitForCompletion(monitor))) { return false; } return true; }
Source:
<code>void setChangeInfo(ChangeInfo info) { GitwebLink gw = Gerrit.getGitwebLink(); <START> if (gw == null) { <END> project.setInnerText(info.project()); return; } JsArray<RevisionInfo> revisions = info.revisions().values(); for (int i = 0; i < revisions.length(); i++) { if (revisions.get(i)._number() == patchSetId.get()) { String c = revisions.get(i).name(); SafeHtml.setInnerHTML(filePath, formatPath(path, info.project(), c)); SafeHtml.setInnerHTML(project, new SafeHtmlBuilder() .openAnchor() .setAttribute("href", gw.toFile(info.project(), c, "")) .setAttribute("title", gw.getLinkName()) .append(info.project()) .closeAnchor()); break; } } }</code><technical_language>if gw != null setup attributes else setInnerText</technical_language>

Target:
void setChangeInfo(ChangeInfo info) { GitwebLink gw = Gerrit.getGitwebLink(); if (gw != null) { JsArray<RevisionInfo> revisions = info.revisions().values(); for (int i = 0; i < revisions.length(); i++) { if (revisions.get(i)._number() == patchSetId.get()) { String c = revisions.get(i).name(); SafeHtml.setInnerHTML(filePath, formatPath(path, info.project(), c)); SafeHtml.setInnerHTML(project, new SafeHtmlBuilder() .openAnchor() .setAttribute("href", gw.toFile(info.project(), c, "")) .setAttribute("title", gw.getLinkName()) .append(info.project()) .closeAnchor()); return; } } } project.setInnerText(info.project()); }
Source:
<code>public NewEpisodesNotification(Long feedId) { Feed feed = DBReader.getFeed(feedId); FeedPreferences prefs = feed.getPreferences(); if (!prefs.getKeepUpdated() || !prefs.getShowEpisodeNotification()) { dontShowNotification = true; lastEpisodeID = null; return; } <START> List<FeedItem> feedItems = DBReader.getFeedItemList(feed); <END> Long newestEpisodeId = null; if (!feedItems.isEmpty()) { newestEpisodeId = feedItems.get(0).getId(); } dontShowNotification = false; lastEpisodeID = newestEpisodeId; }</code><technical_language>PodDbAdapter.getFeedCounters here? If setting argument of method, code load number of new items for a specific feed instead of loading feed items. I this is slightly I wrote earlier way, more efficient ;)</technical_language>

Target:
public NewEpisodesNotification(Long feedId) { Feed feed = DBReader.getFeed(feedId); FeedPreferences prefs = feed.getPreferences(); if (!prefs.getKeepUpdated() || !prefs.getShowEpisodeNotification()) { shouldShowNotification = false; lastEpisodeCount = -1; return; } lastEpisodeCount = getNewEpisodeCount(feedId); shouldShowNotification = true; }
Source:
<code>private void reportMetrics(final EventTypeMetrics eventTypeMetrics, final String eventsAsString, final JSONArray eventsAsJsonObjects) { final int numberOfEventsInBatch = eventsAsJsonObjects.length(); eventTypeMetrics.getEventsPerBatchHistogram().update(numberOfEventsInBatch); <START> eventTypeMetrics.getAverageEventSizeInBytesHistogram().update(eventsAsString.length() / numberOfEventsInBatch); <END> }</code><technical_language>numberOfEventsInBatch 0</technical_language>

Target:
private void reportMetrics(final EventTypeMetrics eventTypeMetrics, final String eventsAsString, final JSONArray eventsAsJsonObjects) { final int numberOfEventsInBatch = eventsAsJsonObjects.length(); eventTypeMetrics.getEventsPerBatchHistogram().update(numberOfEventsInBatch); final int averageApproximateEventSize = numberOfEventsInBatch > 0 ? eventsAsString.length() / numberOfEventsInBatch : 0; eventTypeMetrics.getAverageEventSizeInBytesHistogram().update(averageApproximateEventSize); }