auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void aspectSkippingOrphanArtifactsWithLocation() throws Exception { scratch.file("aspects/BUILD", ""); scratch.file( "aspects/print.bzl", "def _print_expanded_copts_impl(target, ctx):", " # Make sure the rule has a srcs attribute.", <START> " if hasattr(ctx.rule.attr, 'cmd'):", <END> " cmd = ctx.rule.attr.cmd", " print(\"{} -> {}\".format(cmd, ctx.expand_location(cmd, [])))", " return []", "", "print_expanded_copts = aspect(", " implementation = _print_expanded_copts_impl,", " attr_aspects = ['deps'],", ")"); scratch.file("simple/BUILD", "filegroup(", " name = \"files\",", " srcs = [\"afile\"],", ")", "", "genrule(", " name = \"concat_all_files\",", " srcs = [\":files\"],", " outs = [\"concatenated.txt\"],", " cmd = \"cat $(location :files) > $@\"", ")"); reporter.removeHandler(failFastHandler); AnalysisResult result = update(ImmutableList.of("aspects/print.bzl%print_expanded_copts"), " assertThat(result.hasError()).isFalse(); }</code><technical_language>nit: is this false</technical_language>

Target:
public void aspectSkippingOrphanArtifactsWithLocation() throws Exception { scratch.file( "simple/print.bzl", "def _print_expanded_location_impl(target, ctx):", " return struct(result=ctx.expand_location(ctx.rule.attr.cmd, []))", "", "print_expanded_location = aspect(", " implementation = _print_expanded_location_impl,", ")"); scratch.file("simple/BUILD", "filegroup(", " name = \"files\",", " srcs = [\"afile\"],", ")", "", "genrule(", " name = \"concat_all_files\",", " srcs = [\":files\"],", " outs = [\"concatenated.txt\"],", " cmd = \"$(location :files)\"", ")"); reporter.removeHandler(failFastHandler); AnalysisResult analysisResult = update(ImmutableList.of(" assertThat(analysisResult.hasError()).isFalse(); AspectValue value = Iterables.getOnlyElement(analysisResult.getAspects()); String result = (String) value.getConfiguredAspect().get("result"); assertThat(result).isEqualTo("simple/afile"); }
Source:
<code><START> private static <K, V> Cache.Entry<K, V> wrap(final K key, final OnHeapValueHolder<V> mappedValue) { <END> return wrap(new Map.Entry<K, OnHeapValueHolder<V>>() { @Override public K getKey() { return key; } @Override public OnHeapValueHolder<V> getValue() { return mappedValue; } @Override public OnHeapValueHolder<V> setValue(OnHeapValueHolder<V> value) { throw new UnsupportedOperationException(); } }); }</code><technical_language>This method a weird. I this new wrap() method takes (K, OnHeapValueHolder) return anonymous implementation of Cache.Entry. existing wrap() method takes Map.Entry call this pass entry key value</technical_language>

Target:
private static <K, V> Cache.Entry<K, V> wrap(final K key, final OnHeapValueHolder<V> mappedValue) { return new Cache.Entry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return mappedValue.value(); } @Override public long getCreationTime(TimeUnit unit) { return mappedValue.creationTime(unit); } @Override public long getLastAccessTime(TimeUnit unit) { return mappedValue.lastAccessTime(unit); } @Override public float getHitRate(TimeUnit unit) { return mappedValue.hitRate(unit); } }; }
Source:
<code>public void loadFileMetadata(File file) { boolean containsPackedVariable = false; GridDataset gridDs = null; try { <START> setNcksSubsetParameters(file.getAbsoluteFile().toString()); <END> setNcksExtraParameters(); this.timeUnlimited = time.isUnlimited(); } catch (Exception e) { logger.error(e.getMessage()); throw new GoGoDuckException(e.getMessage(), e); } try { if (goGoDuckConfig.getUnpackNetcdf(profile)) { this.containsPackedVariable = true; } else { String location = file.getAbsolutePath(); Set<NetcdfDataset.Enhance> enhanceMode = new HashSet<>(); enhanceMode.add(NetcdfDataset.Enhance.ScaleMissing); gridDs = GridDataset.open(location, enhanceMode); for (Variable var : gridDs.getNetcdfDataset().getVariables()) { VariableDS vds = new VariableDS(var.getGroup(), var, true); if (vds.hasScaleOffset()) { containsPackedVariable = true; break; } } this.containsPackedVariable = containsPackedVariable; } } catch (Exception e) { logger.error(e.getMessage()); throw new GoGoDuckException(e.getMessage(), e); } finally { try { if (gridDs != null) { gridDs.close(); } } catch (IOException e) { logger.error(e.getMessage()); throw new GoGoDuckException(e.getMessage(), e); } } }</code><technical_language>this is poorly named - a) probing file determine coordinate variables, b) constructing subsetting parameters passed ncks this reference time.isUnlimited confusing - I time get set</technical_language>

Target:
public void loadFileMetadata(File file) { boolean fileContainPackedVariables = false; GridDataset gridDs = null; try { setTimeLatLon(file.getAbsoluteFile().toString()); String location = file.getAbsolutePath(); Set<NetcdfDataset.Enhance> enhanceMode = new HashSet<>(); enhanceMode.add(NetcdfDataset.Enhance.ScaleMissing); gridDs = GridDataset.open(location, enhanceMode); for (Variable var : gridDs.getNetcdfDataset().getVariables()) { VariableDS vds = new VariableDS(var.getGroup(), var, true); if (vds.hasScaleOffset()) { fileContainPackedVariables = true; break; } } boolean unpackPackedVariables = goGoDuckConfig.getUnpack(profile); if (fileContainPackedVariables && unpackPackedVariables) { this.unpack = true; } else { this.unpack = false; } } catch (Exception e) { logger.error(e.getMessage()); throw new GoGoDuckException(e.getMessage(), e); } finally { close(gridDs, GridDataset.class); } }
Source:
<code>public void expandRow() { listGroupItemHeader.addClassName("list-view-pf-expand-active"); listGroupItemContainer.removeClassName("hidden"); <START> faAngleRight.addClassName("fa-angle-down"); <END> }</code><technical_language>I introduce constants for: "list-view-pf-expand-active", "hidden" "fa-angle-down"</technical_language>

Target:
public void expandRow() { listGroupItemHeader.addClassName(LIST_VIEW_PF_EXPAND_ACTIVE); listGroupItemContainer.removeClassName(HIDDEN); faAngleRight.addClassName(FA_ANGLE_DOWN); }
Source:
<code>public static int computeFetchSize(int initialSize) { int fetchSize = initialSize; if (fetchSize < 10) { fetchSize = 10; <START> } <END> fetchSize *= 20; if (fetchSize < 0 || fetchSize > RelationalConstants.MAX_FETCH_SIZE) { fetchSize = RelationalConstants.MAX_FETCH_SIZE; } return fetchSize; }</code><technical_language>do constants10 20 from? if final items in class meaningful names</technical_language>

Target:
public static int computeFetchSize(int initialSize) { int fetchSize = initialSize; if (fetchSize < MINIMUM_FETCH_SIZE) { fetchSize = MINIMUM_FETCH_SIZE; } fetchSize *= APPROXIMATE_NUMBER_OF_SUB_ITEMS; if (fetchSize < 0 || fetchSize > RelationalConstants.MAX_FETCH_SIZE) { fetchSize = RelationalConstants.MAX_FETCH_SIZE; } return fetchSize; }
Source:
<code>private PerAlleleCollection<Double> getHetGenotypeLogOdds(ReadLikelihoods<Allele> likelihoods, final boolean isNormal, final Strand strand) { final String sample = isNormal ? matchedNormalSampleName : tumorSampleName; <START> final OptionalDouble givenAltAlleleFraction = isNormal ? OptionalDouble.of(0.5) : NO_FIXED_TUMOR_ALT_FRACTION; <END> final PerAlleleCollection<Double> hetGenotypeLogLks = getHetGenotypeLogLikelihoods(likelihoods, sample, givenAltAlleleFraction, strand); final PerAlleleCollection<Double> lods = new PerAlleleCollection<>(PerAlleleCollection.Type.ALT_ONLY); final int flipLodFactor = isNormal ? -1 : 1; final List<Allele> altAlleles = likelihoods.alleles().stream().filter(Allele::isNonReference).collect(Collectors.toList()); lods.set(altAlleles, a -> flipLodFactor * (hetGenotypeLogLks.get(a) - hetGenotypeLogLks.getRef())); return lods; }</code><technical_language>Change OptionalDouble.of(0.5) GERMLINE_HET_ALT_FRACTION (currently unused) change NO_FIXED_TUMOR_ALT_FRACTION OptionalDouble.empty(). I prefer former</technical_language>

Target:
private PerAlleleCollection<Double> getHetGenotypeLogOdds(ReadLikelihoods<Allele> likelihoods, final boolean isNormal, final Strand strand) { final String sample = isNormal ? matchedNormalSampleName : tumorSampleName; final OptionalDouble givenAltAlleleFraction = isNormal ? GERMLINE_HET_ALT_FRACTION : NO_FIXED_TUMOR_ALT_FRACTION; final PerAlleleCollection<Double> hetGenotypeLogLks = getHetGenotypeLogLikelihoods(likelihoods, sample, givenAltAlleleFraction, strand); final PerAlleleCollection<Double> lods = new PerAlleleCollection<>(PerAlleleCollection.Type.ALT_ONLY); final int flipLodFactor = isNormal ? -1 : 1; final List<Allele> altAlleles = likelihoods.alleles().stream().filter(Allele::isNonReference).collect(Collectors.toList()); lods.set(altAlleles, a -> flipLodFactor * (hetGenotypeLogLks.get(a) - hetGenotypeLogLks.getRef())); return lods; }
Source:
<code>protected static void buildChain(FormDefinitionFieldData previous, List<FormDefinitionFieldData> elements, List<FormDefinitionFieldData> originalList) { if (elements.isEmpty() || previous == null) { return; } <START> FormDefinitionFieldData[] aux = elements.stream().filter(formElement -> previous.getName().equals(formElement.getAfterElement())).toArray(size -> new FormDefinitionFieldData[size]); <END> elements.removeAll(Arrays.asList(aux)); for (FormDefinitionFieldData element : aux) { originalList.add(originalList.indexOf(previous) + 1, element); buildChain(element, elements, originalList); } }</code><technical_language>touching this ... List array? creating list 2 lines I collect in place match</technical_language>

Target:
protected static void buildChain(FormDefinitionFieldData previous, List<FormDefinitionFieldData> elements, List<FormDefinitionFieldData> originalList) { if (elements.isEmpty() || previous == null) { return; } List<FormDefinitionFieldData> aux = elements.stream().filter(formElement -> previous.getName().equals(formElement.getAfterElement())).collect(Collectors.toList()); elements.removeAll(aux); for (FormDefinitionFieldData element : aux) { originalList.add(originalList.indexOf(previous) + 1, element); buildChain(element, elements, originalList); } }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } <START> if (tree.is(METHOD) || tree.is(CONSTRUCTOR)) { <END> MethodTree methodTree = (MethodTree) tree; Optional<ModifierKeywordTree> modifier = findModifier(methodTree.modifiers(), SYNCHRONIZED); synchronizedStack.push(modifier.isPresent() ? new Counter(1) : new Counter(0)); methodTree(tree); } }</code><technical_language>wrapped in invocation : is method multiple arity need for ||</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(METHOD, CONSTRUCTOR)) { MethodTree methodTree = (MethodTree) tree; int initialCounter = findModifier(methodTree.modifiers(), SYNCHRONIZED).map(m -> 1).orElse(0); synchronizedStack.push(new Counter(initialCounter)); findWaitOrNotifyInvocation(methodTree); } }
Source:
<code>private Map<String, DbParameterAccessor> readIntoParams(String objname, String query) throws SQLException { String procName; if (objname.contains(".")) { String[] schemaAndName = objname.split("[\\.]", 2); objname = "[" + schemaAndName[0] + "].[" + schemaAndName[1] + "]"; procName = schemaAndName[1]; } else { objname = "[" + NameNormaliser.normaliseName(objname) + "]"; procName = NameNormaliser.normaliseName(objname); } PreparedStatement dc = currentConnection.prepareStatement(query); dc.setString(1, NameNormaliser.normaliseName(objname)); Log.log("executing query"); ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) paramName = ""; String dataType = rs.getString(2); String direction = rs.getString(4); DbParameterAccessor.Direction paramDirection; if (paramName.trim().length() == 0) <START> paramDirection = DbParameterAccessor.Direction.RETURN_VALUE; <END> else paramDirection = getParameterDirection(direction); DbParameterAccessor dbp = new DbParameterAccessor(paramName, paramDirection, getSqlType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; }</code><technical_language>In case of RETURN_VALUE: - DbParameterAccessor created position == -1. - position counter incremented</technical_language>

Target:
private Map<String, DbParameterAccessor> readIntoParams(String objname, String query) throws SQLException { String procName; if (objname.contains(".")) { String[] schemaAndName = objname.split("[\\.]", 2); objname = "[" + schemaAndName[0] + "].[" + schemaAndName[1] + "]"; procName = schemaAndName[1]; } else { objname = "[" + NameNormaliser.normaliseName(objname) + "]"; procName = NameNormaliser.normaliseName(objname); } PreparedStatement dc = currentConnection.prepareStatement(query); dc.setString(1, NameNormaliser.normaliseName(objname)); Log.log("executing query"); ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) paramName = ""; String dataType = rs.getString(2); String direction = rs.getString(4); DbParameterAccessor.Direction paramDirection; int parameterPosition = position; if (paramName.trim().length() == 0) { paramDirection = DbParameterAccessor.Direction.RETURN_VALUE; parameterPosition = -1; } else { paramDirection = getParameterDirection(direction); ++position; } DbParameterAccessor dbp = new DbParameterAccessor(paramName, paramDirection, getSqlType(dataType), getJavaClass(dataType), parameterPosition); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; }
Source:
<code>public void testWatchService() { String name = UUID.randomUUID().toString(); String serviceId1 = createAutoDeregisterServiceId(); String serviceId2 = createAutoDeregisterServiceId(); List<Map<String, CatalogService>> result = new CopyOnWriteArrayList<>(); CountDownLatch finish = new CountDownLatch(1); ServiceCatalogCache cache = ServiceCatalogCache.newCache(client.catalogClient(), name); cache.addListener(serviceMap -> { result.add(serviceMap); <START> if (result.size() == 3) <END> finish.countDown(); }); cache.start(); client.agentClient().register(20001, 20, name, serviceId1); client.agentClient().register(20002, 20, name, serviceId2); Uninterruptibles.awaitUninterruptibly(finish, 1, TimeUnit.SECONDS); assertEquals(0, result.get(0).size()); assertEquals(1, result.get(1).size()); assertEquals(2, result.get(2).size()); assertTrue(result.get(1).containsKey(serviceId1)); assertFalse(result.get(1).containsKey(serviceId2)); assertTrue(result.get(2).containsKey(serviceId1)); assertTrue(result.get(2).containsKey(serviceId2)); assertEquals(serviceId1, result.get(1).get(serviceId1).getServiceId()); assertEquals(serviceId2, result.get(2).get(serviceId2).getServiceId()); }</code><technical_language>CountDownLatch(3)</technical_language>

Target:
public void testWatchService() { String name = UUID.randomUUID().toString(); String serviceId1 = createAutoDeregisterServiceId(); String serviceId2 = createAutoDeregisterServiceId(); List<Map<String, CatalogService>> result = new CopyOnWriteArrayList<>(); CountDownLatch finish = new CountDownLatch(3); ServiceCatalogCache cache = ServiceCatalogCache.newCache(client.catalogClient(), name); cache.addListener(serviceMap -> { result.add(serviceMap); finish.countDown(); }); cache.start(); client.agentClient().register(20001, 20, name, serviceId1); Synchroniser.pause(Duration.ofMillis(100)); client.agentClient().register(20002, 20, name, serviceId2); Uninterruptibles.awaitUninterruptibly(finish, 1, TimeUnit.SECONDS); assertEquals(0, result.get(0).size()); assertEquals(1, result.get(1).size()); assertEquals(2, result.get(2).size()); assertTrue(result.get(1).containsKey(serviceId1)); assertFalse(result.get(1).containsKey(serviceId2)); assertTrue(result.get(2).containsKey(serviceId1)); assertTrue(result.get(2).containsKey(serviceId2)); assertEquals(serviceId1, result.get(1).get(serviceId1).getServiceId()); assertEquals(serviceId2, result.get(2).get(serviceId2).getServiceId()); }
Source:
<code>private void runGodModeRoutine(boolean isPart) throws IOException { try { verifyHtml(OUTPUT_FILENAME, isPart); signalFailureToDetectException(); <START> } catch (IOException|AssertionError e) { <END> ignoreExpectedException(); } System.setProperty("godmode", "true"); verifyHtml(OUTPUT_FILENAME, isPart); System.clearProperty("godmode"); assertNull(System.getProperty("godmode")); verifyHtml(OUTPUT_FILENAME, isPart); String expectedOutputPage = FileHelper.readFile(TestProperties.TEST_PAGES_FOLDER + (isPart ? EXPECTED_PART_FILENAME : EXPECTED_FILENAME)); String actualOutputPage = FileHelper.readFile(OUTPUT_PATH); HtmlHelper.assertSameHtml(expectedOutputPage, actualOutputPage, isPart); }</code><technical_language>I this stronger, exception is expected ignore</technical_language>

Target:
private void runGodModeRoutine(boolean isPart) throws Exception { System.setProperty("godmode", "true"); verifyHtml(OUTPUT_FILENAME, isPart); System.clearProperty("godmode"); assertNull(System.getProperty("godmode")); verifyHtml(OUTPUT_FILENAME, isPart); String expectedOutputPage = FileHelper.readFile(isPart ? EXPECTED_PART_FILEPATH : EXPECTED_FILEPATH); String actualOutputPage = FileHelper.readFile(OUTPUT_FILEPATH); HtmlHelper.assertSameHtml(expectedOutputPage, actualOutputPage, isPart); }
Source:
<code>private boolean copyDataDirectoryIfChanged(String origDir, String destDir) throws IOException { if(destDir != null && destDir.length() > 0 && !origDir.equals(destDir)) { log.debug("Moving data from " + origDir + " to " + destDir); File currentDir = new File(origDir); File newDir = new File(destDir); <START> FileUtil.purge(newDir, true); END> FileUtil.copyDirectory(currentDir, newDir); return true; } return false; }</code><technical_language>want automatically purge target directory here? target directory empty fail if is not</technical_language>

Target:
private boolean copyDataDirectoryIfChanged(String origDir, String destDir) throws IOException { if(destDir != null && destDir.length() > 0 && !origDir.equals(destDir)) { log.debug("Moving data from " + origDir + " to " + destDir); File currentDir = new File(origDir); File newDir = new File(destDir); FileUtil.copyDirectory(currentDir, newDir); return true; } return false; }
Source:
<code>public List<FederatedSource> getFederatedSources() { ArrayList<FederatedSource> sources = new ArrayList<>(federatedSources); sources.addAll(oauthFederatedSources); <START> return sources; <END> }</code><technical_language>Is a purpose of FederatedSources OAuthSources living in separate variables? For instance: in this getter combine lists, wondering if combining lists plausible for class well</technical_language>

Target:
public List<FederatedSource> getFederatedSources() { return federatedSources; }
Source:
<code>public void run() { while (true) { try { Lease lease = leaseMaintainer.getCurrentLease(); <START> if (lease instanceof LeaseImpl) { <END> boolean validLease = lease.isValidAndContiguous(lease); if (!validLease) { connection.close(); } } timeSource.sleep(200L); } catch (IOException e) { LOGGER.error("Closing connection, due to lease expiry, caused an error", e); } catch (InterruptedException e) { Thread.interrupted(); break; } } }</code><technical_language>discussing @ChrisGreenaway, this condition inverted other Lease type in check</technical_language>

Target:
public void run() { while (true) { try { Lease lease = leaseMaintainer.getCurrentLease(); if (!(lease instanceof NullLease)) { boolean validLease = lease.isValidAndContiguous(lease); if (!validLease) { connection.close(); } } timeSource.sleep(200L); } catch (IOException e) { LOGGER.error("Closing connection, due to lease expiry, caused an error", e); } catch (InterruptedException e) { Thread.interrupted(); break; } } }
Source:
<code>public void setBeanProperty(final String propertyName) { String currBeanProperty = getBeanProperty(); if ((propertyName != null && currBeanProperty == null) <START> || (currBeanProperty != null && (propertyName == null || !currBeanProperty.equals(propertyName)))) { <END> getOrCreateComponentModel().setBeanProperty(propertyName); } }</code><technical_language>This style of if statement simplified !Objects.equals(currBeanProperty, propertyName). Replace this pattern is in other areas. good unit test of scenarios a new model is created created</technical_language>

Target:
public void setBeanProperty(final String propertyName) { String currBeanProperty = getBeanProperty(); if (!Objects.equals(propertyName, currBeanProperty)) { getOrCreateComponentModel().setBeanProperty(propertyName); } }
Source:
<code>private boolean saveGlusterHostUuid() { VdsGlusterDao vdsGlusterDao = DbFacade.getInstance().getVdsGlusterDao(); VdsGluster vdsGluster = vdsGlusterDao.getById(getVds().getId()); <START> if (vdsGluster == null) { <END> VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterHostUUID, new VdsIdVDSCommandParametersBase(getVds().getId())); if (returnValue.getSucceeded() && returnValue.getReturnValue() != null) { vdsGluster = new VdsGluster(); vdsGluster.setId(getVds().getId()); vdsGluster.setGlusterHostUuid(Guid.createGuidFromString((String) returnValue.getReturnValue())); vdsGlusterDao.save(vdsGluster); } else { return false; } } return true; }</code><technical_language>Please pay attention if runVdsCommand fail, exception thrown, returnValue.getSucceeded() false line 284 executed</technical_language>

Target:
private boolean saveGlusterHostUuid() { GlusterServerDao glusterServerDao = DbFacade.getInstance().getGlusterServerDao(); GlusterServer glusterServer = glusterServerDao.getByServerId(getVds().getId()); if (glusterServer == null) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterHostUUID, new VdsIdVDSCommandParametersBase(getVds().getId())); if (returnValue.getSucceeded() && returnValue.getReturnValue() != null) { glusterServer = new GlusterServer(); glusterServer.setId(getVds().getId()); glusterServer.setGlusterServerUuid(Guid.createGuidFromString((String) returnValue.getReturnValue())); glusterServerDao.save(glusterServer); } else { return false; } } return true; }
Source:
<code>void deprioritizeCase(final String caseName) throws AutoIngestManagerException { if (state != State.RUNNING) { return; } <START> List<AutoIngestJob> prioritizedJobs = new ArrayList<>(); <END> synchronized (jobsLock) { for (AutoIngestJob job : pendingJobs) { if (job.getManifest().getCaseName().equals(caseName)) { prioritizedJobs.add(job); } } if (!prioritizedJobs.isEmpty()) { for (AutoIngestJob job : prioritizedJobs) { int oldPriority = job.getPriority(); job.setPriority(DEFAULT_PRIORITY); try { this.updateCoordinationServiceManifestNode(job); } catch (CoordinationServiceException | InterruptedException ex) { job.setPriority(oldPriority); throw new AutoIngestManagerException("Error updating case priority", ex); } } } Collections.sort(pendingJobs, new AutoIngestJob.PriorityComparator()); } if (!prioritizedJobs.isEmpty()) { new Thread(() -> { eventPublisher.publishRemotely(new AutoIngestCaseDeprioritizedEvent(LOCAL_HOST_NAME, caseName)); }).start(); } }</code><technical_language>I feel naming this (and other similar objects in other methods) "jobsToDeprioritize" code clearer</technical_language>

Target:
void deprioritizeCase(final String caseName) throws AutoIngestManagerException { if (state != State.RUNNING) { return; } List<AutoIngestJob> jobsToDeprioritize = new ArrayList<>(); synchronized (jobsLock) { for (AutoIngestJob job : pendingJobs) { if (job.getManifest().getCaseName().equals(caseName)) { jobsToDeprioritize.add(job); } } if (!jobsToDeprioritize.isEmpty()) { for (AutoIngestJob job : jobsToDeprioritize) { int oldPriority = job.getPriority(); job.setPriority(DEFAULT_PRIORITY); try { this.updateCoordinationServiceManifestNode(job); } catch (CoordinationServiceException | InterruptedException ex) { job.setPriority(oldPriority); throw new AutoIngestManagerException("Error updating case priority", ex); } } } Collections.sort(pendingJobs, new AutoIngestJob.PriorityComparator()); } if (!jobsToDeprioritize.isEmpty()) { new Thread(() -> { eventPublisher.publishRemotely(new AutoIngestCasePrioritizedEvent(LOCAL_HOST_NAME, caseName)); }).start(); } }
Source:
<code>public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { final HttpServletResponse httpResponse = (HttpServletResponse) response; try { filterChain.doFilter(request, response); } catch (final ServletException e) { <START> final Throwable t = null == e.getCause() ? e : e.getCause(); <END> ErrorHolder currentMatch = null; for (final ErrorHolder errorHolder : this.errors) { if (errorHolder.exactMatch(t)) { currentMatch = errorHolder; break; } else if (errorHolder.inheritanceMatch(t)) { currentMatch = errorHolder; } } if (currentMatch != null) { httpResponse.sendRedirect(currentMatch.getUrl()); } else { httpResponse.sendRedirect(defaultErrorRedirectPage); } } }</code><technical_language>+1 for change. a convention, I write as: final Throwable rootCause = e.getCause(); final Throwable t = rootCause == null ? e : rootCause;</technical_language>

Target:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { final HttpServletResponse httpResponse = (HttpServletResponse) response; try { filterChain.doFilter(request, response); } catch (final ServletException e) { final Throwable rootCause = e.getCause() == null ? e : e.getCause(); ErrorHolder currentMatch = null; for (final ErrorHolder errorHolder : this.errors) { if (errorHolder.exactMatch(rootCause)) { currentMatch = errorHolder; break; } else if (errorHolder.inheritanceMatch(rootCause)) { currentMatch = errorHolder; } } if (currentMatch != null) { httpResponse.sendRedirect(currentMatch.getUrl()); } else { httpResponse.sendRedirect(defaultErrorRedirectPage); } } }
Source:
<code>public void close() throws Exception { super.close(); if (fetcher != null) { FunctionUtils.closeFunction(fetcher); } if (allResultFutures != null) { for (JoinedRowResultFuture rf : allResultFutures) { <START> if (rf != null) { <END> rf.close(); } } } }</code><technical_language>rf null</technical_language>

Target:
public void close() throws Exception { super.close(); if (fetcher != null) { FunctionUtils.closeFunction(fetcher); } if (allResultFutures != null) { for (JoinedRowResultFuture rf : allResultFutures) { rf.close(); } } }
Source:
<code>public CanvasViolationImpl build() { final CanvasViolationImpl result = new CanvasViolationImpl(ruleViolation.getMessage(), ruleViolation.getViolationType()); if (ruleViolation instanceof AbstractRuleViolation) { final String uuid = ((AbstractRuleViolation) ruleViolation).getUuid(); if (null != uuid) { result.setUuid(uuid); <START> ; <END> } } return result; }</code><technical_language>Floating ;</technical_language>

Target:
public CanvasViolationImpl build() { final CanvasViolationImpl result = new CanvasViolationImpl(ruleViolation.getMessage(), ruleViolation.getViolationType()); if (ruleViolation instanceof AbstractRuleViolation) { final String uuid = ((AbstractRuleViolation) ruleViolation).getUuid(); if (null != uuid) { result.setUuid(uuid); } } return result; }
Source:
<code>private String parseLogLevel(int level) { if (level == LogService.NONE) return "NONE"; if (level == LogService.ERROR) return "ERROR"; if (level == LogService.WARN) return "WARN"; if (level == LogService.INFO) return "INFO"; if (level == LogService.DEBUG) return "DEBUG"; if (level == LogService.TRACE) return "TRACE"; <START> return "WARN"; <END> }</code><technical_language>I suggest instead: java return "" + level; Defaulting WARN is misleading</technical_language>

Target:
private String parseLogLevel(int level) { if (level == LogService.NONE) return "NONE"; if (level == LogService.ERROR) return "ERROR"; if (level == LogService.WARN) return "WARN"; if (level == LogService.INFO) return "INFO"; if (level == LogService.DEBUG) return "DEBUG"; if (level == LogService.TRACE) return "TRACE"; return "" + level; }
Source:
<code>public void renameColumn(long columnIndex, String newName) { verifyColumnName(newName); if (getPrimaryKey() == columnIndex) { Table pkTable = getPrimaryKeyTable(); String className = tableNameToClassName(getName()); long rowIndex = pkTable.findFirstString(PRIMARY_KEY_CLASS_COLUMN_INDEX, className); if (rowIndex != NO_MATCH) { <START> pkTable.getUncheckedRow(rowIndex).setString(PRIMARY_KEY_FIELD_COLUMN_INDEX, newName); <END> } else { throw new IllegalStateException("PrimaryKey field is not properly recorded for " + className + "."); } } nativeRenameColumn(nativePtr, columnIndex, newName); }</code><technical_language>call setString table. need create unchecked row for it</technical_language>

Target:
public void renameColumn(long columnIndex, String newName) { verifyColumnName(newName); final String oldName = nativeGetColumnName(nativePtr, columnIndex); final long oldPkColumnIndex = getPrimaryKey(); nativeRenameColumn(nativePtr, columnIndex, newName); if (oldPkColumnIndex == columnIndex) { try { String className = tableNameToClassName(getName()); Table pkTable = getPrimaryKeyTable(); long pkRowIndex = pkTable.findFirstString(PRIMARY_KEY_CLASS_COLUMN_INDEX, className); if (pkRowIndex != NO_MATCH) { pkTable.setString(PRIMARY_KEY_FIELD_COLUMN_INDEX, pkRowIndex, newName); } else { throw new IllegalStateException("Non-existent PrimaryKey column cannot be renamed"); } } catch (Exception e) { nativeRenameColumn(nativePtr, columnIndex, oldName); throw e; } } }
Source:
<code>RequestBuilder createRequest(String engineAuthToken) { RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, restApiBaseUrl); if (engineAuthToken != null) { <START> builder.setHeader(ENGINE_AUTH_TOKEN_HEADER, engineAuthToken); <END> } builder.setHeader("Session-TTL", restApiSessionTimeout); String preferValue = "persistent-auth, csrf-protection"; if (engineAuthToken != null) { preferValue += ", new-auth"; } builder.setHeader("Prefer", preferValue); String sessionId = getSessionId(); if (sessionId != null) { builder.setHeader(SESSION_ID_HEADER, sessionId); } return builder; }</code><technical_language>Alon said, move this other if (engineAuthToken != null)</technical_language>

Target:
RequestBuilder createRequest(String engineAuthToken) { RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, restApiBaseUrl); builder.setHeader("Session-TTL", restApiSessionTimeout); String preferValue = "persistent-auth, csrf-protection"; if (engineAuthToken != null) { preferValue += ", new-auth"; builder.setHeader(ENGINE_AUTH_TOKEN_HEADER, engineAuthToken); } builder.setHeader("Prefer", preferValue); String sessionId = getSessionId(); if (sessionId != null) { builder.setHeader(SESSION_ID_HEADER, sessionId); } return builder; }
Source:
<code>private void loadMetadataResources(JobModel jobModel) { MetadataStore metadataStore = null; try { createCoordinatorStream(); MetadataStoreFactory metadataStoreFactory = Util.getObj(new JobConfig(config).getMetadataStoreFactory(), MetadataStoreFactory.class); metadataStore = metadataStoreFactory.getMetadataStore(SetConfig.TYPE, config, metrics.getMetricsRegistry()); metadataStore.init(); <START> MetadataResourceManager metadataResourceManager = <END> new MetadataResourceManager(metadataStore, jobModel, metrics.getMetricsRegistry()); metadataResourceManager.createResources(); CoordinatorStreamValueSerde jsonSerde = new CoordinatorStreamValueSerde(SetConfig.TYPE); for (Map.Entry<String, String> entry : config.entrySet()) { byte[] serializedValue = jsonSerde.toBytes(entry.getValue()); String configKey = CoordinatorStreamStore.serializeCoordinatorMessageKeyToJson(SetConfig.TYPE, entry.getKey()); metadataStore.put(configKey, serializedValue); } } finally { if (metadataStore != null) { LOG.info("Stopping the coordinator system producer."); metadataStore.close(); } } }</code><technical_language>Minor: ordering, this logic createCoordinatorStream? slightly coordinator stream is created right usage (e.g. if metadataResourceManager fails, skip create coord stream)</technical_language>

Target:
private void loadMetadataResources(JobModel jobModel) { MetadataStore metadataStore = null; try { createCoordinatorStream(); MetadataStoreFactory metadataStoreFactory = Util.getObj(new JobConfig(config).getMetadataStoreFactory(), MetadataStoreFactory.class); metadataStore = metadataStoreFactory.getMetadataStore(SetConfig.TYPE, config, metrics.getMetricsRegistry()); metadataStore.init(); MetadataResourceUtil metadataResourceUtil = new MetadataResourceUtil(jobModel, metrics.getMetricsRegistry()); metadataResourceUtil.createResources(); CoordinatorStreamValueSerde jsonSerde = new CoordinatorStreamValueSerde(SetConfig.TYPE); for (Map.Entry<String, String> entry : config.entrySet()) { byte[] serializedValue = jsonSerde.toBytes(entry.getValue()); String configKey = CoordinatorStreamStore.serializeCoordinatorMessageKeyToJson(SetConfig.TYPE, entry.getKey()); metadataStore.put(configKey, serializedValue); } } finally { if (metadataStore != null) { LOG.info("Stopping the coordinator system producer."); metadataStore.close(); } } }
Source:
<code>public String createComment(CoreSession session, Comment comment) { return CoreInstance.doPrivileged(session, s -> { DocumentModel commentModel = s.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); commentModel.setPropertyValue(COMMENT_AUTHOR, comment.getAuthor()); <START> commentModel.setPropertyValue(COMMENT_TEXT, comment.getText()); <END> commentModel.setPropertyValue(COMMENT_CREATION_DATE, comment.getCreationDate()); commentModel.setPropertyValue(COMMENT_MODIFICATION_DATE, comment.getModificationDate()); commentModel = s.createDocument(commentModel); return commentModel.getId(); }); }</code><technical_language>This new implementation, leverage current calling existing method some transformation</technical_language>

Target:
public String createComment(CoreSession session, Comment comment) throws IllegalArgumentException { DocumentRef commentRef = new IdRef(comment.getDocumentId()); if (!session.exists(commentRef)) { throw new IllegalArgumentException("The document " + comment.getDocumentId() + " does not exist."); } DocumentModel docToComment = session.getDocument(commentRef); return createComment(docToComment, comment.getText(), comment.getAuthor()).getId(); }
Source:
<code>public final Github github() { <START> throw new NotImplementedException("MkMarkdown#github()"); <END> }</code><technical_language>UnsupportedOperationException</technical_language>

Target:
public final Github github() { throw new UnsupportedOperationException("MkMarkdown#github()"); }
Source:
<code>public ExpressionTree ALTERNATIVE_CONDITIONAL_AND_EXPR() { return b.<ExpressionTree>nonterminal(Kind.ALTERNATIVE_CONDITIONAL_AND).is( f.binaryExpression( <START> ASSIGNMENT_OR_CONDITIONAL_EXPRESSION(), <END> b.zeroOrMore(f.newTuple( b.firstOf(b.token(PHPKeyword.AND)), ASSIGNMENT_OR_CONDITIONAL_EXPRESSION())))); }</code><technical_language>reverting this change fail</technical_language>

Target:
public ExpressionTree ALTERNATIVE_CONDITIONAL_AND_EXPR() { return b.<ExpressionTree>nonterminal(Kind.ALTERNATIVE_CONDITIONAL_AND).is( f.binaryExpression( CONDITIONAL_EXPR(), b.zeroOrMore(f.newTuple( b.firstOf(b.token(PHPKeyword.AND)), CONDITIONAL_EXPR())))); }
Source:
<code>public static List<String> readLines(InputStream in) throws IOException { <START> return readLines(in, Charset.forName(CHARSET_UTF8)); <END> }</code><technical_language>StandardCharsets.UTF_8</technical_language>

Target:
public static List<String> readLines(InputStream in) throws IOException { return readLines(in, StandardCharsets.UTF_8); }
Source:
<code>private boolean redefineVmCheckpoints() { List<VmCheckpoint> checkpoints = vmCheckpointDao.getAllForVm(getVmId()); if (checkpoints.isEmpty()) { log.info("No previous VM checkpoints found for VM '{}', skip <START> redefine VM <END> checkpoints", getVmId()); return true; } List definedCheckpointsIds = performVmCheckpointsOperation(VDSCommandType.ListVmCheckpoints, new VdsAndVmIDVDSParametersBase(getVdsId(), getVmId())); if (definedCheckpointsIds != null && definedCheckpointsIds.contains(getParameters().getVmBackup() .getFromCheckpointId())) { log.info("Checkpoints chain already defined for VM '{}'", getVmId()); return true; } for (VmCheckpoint checkpoint : checkpoints) { List redefinedCheckpointsIds = performVmCheckpointsOperation(VDSCommandType.RedefineVmCheckpoints, new VmCheckpointsVDSParameters(getVdsId(), getVmId(), List.of(checkpoint))); if (redefinedCheckpointsIds == null || redefinedCheckpointsIds.isEmpty()) { return false; } } return true; }</code><technical_language>redefining</technical_language>

Target:
private boolean redefineVmCheckpoints() { List<VmCheckpoint> checkpoints = vmCheckpointDao.getAllForVm(getVmId()); if (checkpoints.isEmpty()) { log.info("No previous VM checkpoints found for VM '{}', skip redefining VM checkpoints", getVmId()); return true; } List<Guid> definedCheckpointsIds = performVmCheckpointsOperation(VDSCommandType.ListVmCheckpoints, new VdsAndVmIDVDSParametersBase(getVdsId(), getVmId())); if (definedCheckpointsIds != null && definedCheckpointsIds.contains(getParameters().getVmBackup() .getFromCheckpointId())) { log.info("Checkpoints chain is already defined for VM '{}'", getVmId()); return true; } for (VmCheckpoint checkpoint : checkpoints) { List<Guid> redefinedCheckpointsIds = performVmCheckpointsOperation(VDSCommandType.RedefineVmCheckpoints, new VmCheckpointsVDSParameters(getVdsId(), getVmId(), List.of(checkpoint))); if (redefinedCheckpointsIds == null || redefinedCheckpointsIds.isEmpty()) { return false; } } return true; }
Source:
<code>public Map toMap() { final Map authMap = new TreeMap<>(); if (push != null) { authMap.put("push", push); } if (pull != null) { authMap.put("pull", pull); } if (StringUtils.isNotBlank(username)) { authMap.put(AuthConfig.AUTH_USERNAME, username); } if (StringUtils.isNotBlank(password)) { authMap.put(AuthConfig.AUTH_PASSWORD, password); } if (StringUtils.isNotBlank(authToken)) { authMap.put(AuthConfig.AUTH_AUTH, authToken); } if (StringUtils.isNotBlank(auth)) { authMap.put(AuthConfig.AUTH_AUTH, auth); } <START> <END> if (StringUtils.isNotBlank(email)) { authMap.put(AuthConfig.AUTH_EMAIL, email); } return authMap; }</code><technical_language>This do, I suggest throw a _configuration exception_ if auth & authToken set. This disruptive, yet: if both, worked part grateful configuration remove</technical_language>

Target:
public Map toMap() { final Map authMap = new TreeMap<>(); if (push != null) { authMap.put("push", push); } if (pull != null) { authMap.put("pull", pull); } if (StringUtils.isNotBlank(username)) { authMap.put(AuthConfig.AUTH_USERNAME, username); } if (StringUtils.isNotBlank(password)) { authMap.put(AuthConfig.AUTH_PASSWORD, password); } if (StringUtils.isNotBlank(authToken) && StringUtils.isNotBlank(auth)) { throw new IllegalStateException("For a registry configuration either 'auth' or 'authToken' (deprecated) can be specified but not both. Use only 'auth' and remove 'authToken' in the registry configuration"); } if (StringUtils.isNotBlank(authToken)) { authMap.put(AuthConfig.AUTH_AUTH, authToken); } if (StringUtils.isNotBlank(auth)) { authMap.put(AuthConfig.AUTH_AUTH, auth); } if (StringUtils.isNotBlank(email)) { authMap.put(AuthConfig.AUTH_EMAIL, email); } return authMap; }
Source:
<code>private static boolean implementsSerializable(@Nullable Type type) { if (type == null || type.isUnknown()) { return false; } if (type.isPrimitive()) { return true; } if (type.isArray()) { return implementsSerializable(((Type.ArrayType) type).elementType()); } if (type.isClass() || ((JavaType) type).isTagged(JavaType.TYPEVAR)) { <START> return type.erasure().isSubtypeOf(Serializable.class.getName()); <END> } return false; }</code><technical_language>This do contribution. I class name a String is clearer avoid import Serializable is required. remark for other arguments</technical_language>

Target:
private static boolean implementsSerializable(@Nullable Type type) { if (type == null || type.isUnknown()) { return false; } if (type.isPrimitive()) { return true; } if (type.isArray()) { return implementsSerializable(((Type.ArrayType) type).elementType()); } if (type.isClass() || ((JavaType) type).isTagged(JavaType.TYPEVAR)) { return type.erasure().isSubtypeOf("java.io.Serializable"); } return false; }
Source:
<code>boolean isDataSourcesTableStale() { if ((null == db) || (null == sleuthKitCase)) { return false; } try { Set<Long> knownDataSourceIds= db.getKnownDataSourceIds(); List<DataSource> dataSources = sleuthKitCase.getDataSources(); Set<Long> caseDataSourceIds = new HashSet<>(); dataSources.forEach((dataSource) -> { <START> caseDataSourceIds.add(dataSource.getId()); <END> }); return !(knownDataSourceIds.containsAll(caseDataSourceIds) && caseDataSourceIds.containsAll(knownDataSourceIds)); } catch (TskCoreException ex) { LOGGER.log(Level.SEVERE, "Image Gallery failed to check if datasources table is stale.", ex); return false; } }</code><technical_language>I do this Set<Long> caseDataSourceIds = dataSources.map(DataSource::getId).collect(Collectors.toSet()); is me</technical_language>

Target:
boolean isDataSourcesTableStale() { if ((null == getDatabase()) || (null == getSleuthKitCase())) { return false; } try { Set<Long> knownDataSourceIds= getDatabase().getDataSourceIds(); List<DataSource> dataSources = getSleuthKitCase().getDataSources(); Set<Long> caseDataSourceIds = new HashSet<>(); dataSources.forEach((dataSource) -> { caseDataSourceIds.add(dataSource.getId()); }); return !(knownDataSourceIds.containsAll(caseDataSourceIds) && caseDataSourceIds.containsAll(knownDataSourceIds)); } catch (TskCoreException ex) { LOGGER.log(Level.SEVERE, "Image Gallery failed to check if datasources table is stale.", ex); return false; } }
Source:
<code>public Expression createExpression(String expression) { ObjectHelper.notNull(expression, "expression"); String beanName = expression; String method = null; if (expression.contains("?method=")) { beanName = ObjectHelper.before(expression, "?"); method = ObjectHelper.after(expression, "?method="); } else { int idx = expression.indexOf('.'); if (idx > 0) { beanName = expression.substring(0, idx); method = expression.substring(idx + 1); } else { int doubleColonIndex = expression.indexOf("::"); if (doubleColonIndex > 0) { beanName = expression.substring(0, doubleColonIndex); method = expression.substring(doubleColonIndex + 2); } } } <START> <END> return new BeanExpression(beanName, method); }</code><technical_language>check for :: for . expressions my.own.Bean::function lead error</technical_language>

Target:
public Expression createExpression(String expression) { ObjectHelper.notNull(expression, "expression"); String beanName = expression; String method = null; if (expression.contains("?method=")) { beanName = ObjectHelper.before(expression, "?"); method = ObjectHelper.after(expression, "?method="); } else { int doubleColonIndex = expression.indexOf("::"); int beginOfParameterDeclaration = expression.indexOf("("); if (doubleColonIndex > 0 && (expression.indexOf("(") < 0 || doubleColonIndex < beginOfParameterDeclaration)) { beanName = expression.substring(0, doubleColonIndex); method = expression.substring(doubleColonIndex + 2); } else { int idx = expression.indexOf('.'); if (idx > 0) { beanName = expression.substring(0, idx); method = expression.substring(idx + 1); } } } return new BeanExpression(beanName, method); }
Source:
<code>@Test public void conversionProblemOutgoingAsync() throws InterruptedException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory() { @Override public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) { return new Converter<String, RequestBody>() { @Override public RequestBody convert(String value) throws IOException { throw new UnsupportedOperationException("I am broken!"); } }; } }) .build(); Service example = retrofit.create(Service.class); final AtomicReference<Throwable> failureRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); example.postString("Hi").enqueue(new Callback<String>() { @Override public void onResponse(Response<String> response, Retrofit retrofit) { throw new AssertionError(); } @Override public void onFailure(Throwable t) { failureRef.set(t); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); Throwable failure = failureRef.get(); assertThat(failure).hasMessage("Can not create call for Service.postString(String), HTTP method = POST, relative path template = /"); <START> assertThat(failure).hasCauseExactlyInstanceOf(UnsupportedOperationException.class); <END> assertThat(failure.getCause()).hasMessage("I am broken!"); }</code><technical_language>asserting getCause() below, put a normal .isInstanceOf in chain. Also, this is a damn ridiculously specific method for AssertJ have..</technical_language>

Target:
@Test public void conversionProblemOutgoingAsync() throws InterruptedException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory() { @Override public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) { return new Converter<String, RequestBody>() { @Override public RequestBody convert(String value) throws IOException { throw new UnsupportedOperationException("I am broken!"); } }; } }) .build(); Service example = retrofit.create(Service.class); final AtomicReference<Throwable> failureRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); example.postString("Hi").enqueue(new Callback<String>() { @Override public void onResponse(Response<String> response, Retrofit retrofit) { throw new AssertionError(); } @Override public void onFailure(Throwable t) { failureRef.set(t); latch.countDown(); } }); assertTrue(latch.await(2, SECONDS)); Throwable failure = failureRef.get(); assertThat(failure).hasMessage("Can not create call for Service.postString(String), HTTP method = POST, relative path template = /"); assertThat(failure.getCause()).hasMessage("I am broken!") .isInstanceOf(UnsupportedOperationException.class); }
Source:
<code>public void transform(StructuredRecord structuredRecord, Emitter<KeyValue<SolrInputField, SolrInputDocument>> emitter) throws Exception { String solrFieldName; SolrInputDocument document; SolrSearchSinkUtility.validateIdField(structuredRecord.getSchema(), config); SolrSearchSinkUtility.validateInputFieldsDataType(structuredRecord.getSchema()); if (structuredRecord.get(uniqueKey) == null) { return; } document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } solrClient.add(document); <START> solrClient.commit(); <END> emitter.emit(new KeyValue<>(document.getField(uniqueKey), document)); }</code><technical_language>this type of pattern is ok for realtime sink, for a batch sink. Batch sink a Hadoop output format SolrOutputFormat included in solr project. purpose of transform method is convert input key-values OutputFormat understands write</technical_language>

Target:
public void transform(StructuredRecord structuredRecord, Emitter<KeyValue<SolrInputField, SolrInputDocument>> emitter) throws Exception { String solrFieldName; SolrInputDocument document; config.verifySolrConfiguration(); config.validateIdField(structuredRecord.getSchema()); config.validateInputFieldsDataType(structuredRecord.getSchema()); if (structuredRecord.get(uniqueKey) == null) { return; } document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } solrClient.add(document); solrClient.commit(); emitter.emit(new KeyValue<>(document.getField(uniqueKey), document)); }