auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SpProcedureTask:"); sb.append(" TXN ID: ").append(TxnEgo.txnIdToString(getTxnId())); sb.append(" SP HANDLE ID: ").append(TxnEgo.txnIdToString(getSpHandle())); sb.append(" ON HSID: ").append(CoreUtils.hsIdToString(m_initiator.getHSId())); if (m_initiator instanceof InitiatorMailbox) { InitiatorMailbox imbx = (InitiatorMailbox) m_initiator; <START> sb.append(" TRUNC: ").append(TxnEgo.txnIdToString(imbx.getRepairLog().getTruncationHandle())); <END> sb.append(" FROM: ").append(CoreUtils.hsIdToString(imbx.getRepairLog().getTruncationOrigin())); } return sb.toString(); }</code><technical_language>This is truncation handle for task. get truncation handle **txnState.m_initiationMsg**</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SpProcedureTask:"); sb.append(" TXN ID: ").append(TxnEgo.txnIdToString(getTxnId())); sb.append(" SP HANDLE ID: ").append(TxnEgo.txnIdToString(getSpHandle())); sb.append(" ON HSID: ").append(CoreUtils.hsIdToString(m_initiator.getHSId())); if (m_txnState != null) { SpTransactionState txnState = (SpTransactionState)m_txnState; if (txnState.m_initiationMsg != null) { sb.append(" TRUNC HANDLE: ").append(TxnEgo.txnIdToString(txnState.m_initiationMsg.getTruncationHandle())); } } if (m_initiator instanceof InitiatorMailbox) { InitiatorMailbox imbx = (InitiatorMailbox) m_initiator; sb.append(" LAST TRUNC: ").append(TxnEgo.txnIdToString(imbx.getRepairLog().getTruncationHandle())); sb.append(" FROM: ").append(CoreUtils.hsIdToString(imbx.getRepairLog().getTruncationOrigin())); } return sb.toString(); }
Source:
<code>public Integer resolve(ITmfEvent event) { @SuppressWarnings("null") <START> @NonNull Integer cpu = Integer.parseInt(fAspect.resolve(event)); <END> return cpu; }</code><technical_language>this user input (external XML file), assume field numerical values. handle case String is parseable Int return empty string. Ints.tryParse perhaps? ;)</technical_language>

Target:
public Integer resolve(ITmfEvent event) { Integer cpu = Ints.tryParse(fAspect.resolve(event)); if (cpu == null) { return TmfCpuAspect.CPU_UNAVAILABLE; } return cpu; }
Source:
<code>public void process(Exchange exchange) throws Exception { JobParameters jobParameters = prepareJobParameters(exchange.getIn().getHeaders()); String messageJobName = jobParameters.getString(SpringBatchComponent.DYNAMIC_JOBNAME); Job job2run = this.job; if (messageJobName != null) { Job dynamicJob = CamelContextHelper.mandatoryLookup(getEndpoint().getCamelContext(), messageJobName, Job.class); job2run = dynamicJob; if (job2run == null) { exchange.setException(new CamelExchangeException("Found header " + SpringBatchComponent.DYNAMIC_JOBNAME + " with value " +messageJobName + " but could not find a Job in camel context", exchange)); return; } } <START> if (job2run == null) { <END> exchange.setException( new CamelExchangeException("jobName was not specified in the endpoint construction " + " and header "+ SpringBatchComponent.DYNAMIC_JOBNAME + " could not be found", exchange)); return; } JobExecution jobExecution = jobLauncher.run(job2run, jobParameters); exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders()); exchange.getOut().setBody(jobExecution); }</code><technical_language>This check is rednudant, this.job is null</technical_language>

Target:
public void process(Exchange exchange) throws Exception { JobParameters jobParameters = prepareJobParameters(exchange.getIn().getHeaders()); String messageJobName = jobParameters.getString(SpringBatchComponent.JOB_NAME); Job job2run = this.job; if (messageJobName != null) { job2run = CamelContextHelper.mandatoryLookup(getEndpoint().getCamelContext(), messageJobName, Job.class); } if (job2run == null) { exchange.setException(new CamelExchangeException("jobName was not specified in the endpoint construction " + " and header " + SpringBatchComponent.JOB_NAME + " could not be found", exchange)); return; } JobExecution jobExecution = jobLauncher.run(job2run, jobParameters); exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders()); exchange.getOut().setBody(jobExecution); }
Source:
<code>public void update(Guid vdsId, Map<String, Object> values) { int entryCount = values!=null ? values.size() : 0; String[] pluginTypes = new String[entryCount]; String[] bindingIds = new String[entryCount]; <START> if (values!=null) { <END> int i=0; for (Map.Entry<String, Object> pair: values.entrySet()) { pluginTypes[i] = pair.getKey(); bindingIds[i] = (String) pair.getValue(); } } MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("vds_id", vdsId) .addValue("plugin_types", createArrayOf("text", pluginTypes)) .addValue("provider_binding_host_ids" , createArrayOf("text", bindingIds)); getCallsHandler().executeModification("UpdateHostProviderBinding", parameterSource); }</code><technical_language>redundant</technical_language>

Target:
public void update(Guid vdsId, Map<String, Object> values) { int entryCount = values!=null ? values.size() : 0; String[] pluginTypes = new String[entryCount]; String[] bindingIds = new String[entryCount]; if (values!=null) { int i=0; for (Map.Entry<String, Object> pair: values.entrySet()) { pluginTypes[i] = pair.getKey(); bindingIds[i] = (String) pair.getValue(); i++; } } MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("vds_id", vdsId) .addValue("plugin_types", createArrayOf("text", pluginTypes)) .addValue("provider_binding_host_ids" , createArrayOf("text", bindingIds)); getCallsHandler().executeModification("UpdateHostProviderBinding", parameterSource); }
Source:
<code>default short readShort() throws IOException { <START> final byte[] buf = new byte[2]; <END> final int read = read(buf, 0, 2); if (read < 2) throw new EOFException(); return Bytes.toShort(buf, isLittleEndian()); }</code><technical_language>This destroy performance. allocate a new byte array short read. instance field buffer of sufficient size avoid issue</technical_language>

Target:
default short readShort() throws IOException { final byte[] buf = conversionBuffer(); final int read = read(buf, 0, 2); if (read < 2) throw new EOFException(); return Bytes.toShort(buf, isLittleEndian()); }
Source:
<code>private static void writeFsLayout(Path rootDir, Configuration conf) throws IOException { LOG.info("BOOTSTRAP: creating hbase:meta region"); FileSystem fs = rootDir.getFileSystem(conf); Path tableDir = CommonFSUtils.getTableDir(rootDir, TableName.META_TABLE_NAME); <START> if (fs.exists(tableDir)) { <END> LOG.info("Meta table directory exists, continue..."); } FSTableDescriptors.tryUpdateMetaTableDescriptor(conf, fs, rootDir, builder -> builder.setRegionReplication( conf.getInt(HConstants.META_REPLICAS_NUM, HConstants.DEFAULT_META_REPLICA_NUM))); TableDescriptor metaDescriptor = new FSTableDescriptors(conf).get(TableName.META_TABLE_NAME); HRegion .createHRegion(RegionInfoBuilder.FIRST_META_REGIONINFO, rootDir, conf, metaDescriptor, null) .close(); }</code><technical_language>This is another issue other unknown RS issue. In cluster recreate cloud case, zk data is META region location. for HM, this is a cluster bootstrap part of init meta FS. HBASE-24471 added this extra code of deleting existing META table FS path. is done considering a partial created meta table part of some previous failed bootstrap cc @Apache9 this issue is of zk data in new cluster. Unknown server issue is of loss of WAL (to precise master proc wal)</technical_language>

Target:
private static void writeFsLayout(Path rootDir, Configuration conf) throws IOException { LOG.info("BOOTSTRAP: creating hbase:meta region"); FileSystem fs = rootDir.getFileSystem(conf); Path tableDir = CommonFSUtils.getTableDir(rootDir, TableName.META_TABLE_NAME); boolean removeMeta = conf.getBoolean(HConstants.REMOVE_META_ON_RESTART, HConstants.DEFAULT_REMOVE_META_ON_RESTART); if (removeMeta && fs.exists(tableDir) && !fs.delete(tableDir, true)) { LOG.warn("Can not delete partial created meta table, continue..."); } FSTableDescriptors.tryUpdateMetaTableDescriptor(conf, fs, rootDir, builder -> builder.setRegionReplication( conf.getInt(HConstants.META_REPLICAS_NUM, HConstants.DEFAULT_META_REPLICA_NUM))); TableDescriptor metaDescriptor = new FSTableDescriptors(conf).get(TableName.META_TABLE_NAME); HRegion .createHRegion(RegionInfoBuilder.FIRST_META_REGIONINFO, rootDir, conf, metaDescriptor, null) .close(); }
Source:
<code>public void mergeResolutionCompleted(Comparison comparison) { EList<MatchResource> matchResources = comparison.getMatchedResources(); <START> final List<IResource> resources = new LinkedList<IResource>(); <END> for (MatchResource matchResource : matchResources) { URI matchUri = matchResource.getLeft().getURI(); Set<URI> dependencyUris = dependencies.of(matchUri, matchResource.getLeft().getResourceSet() .getURIConverter()); for (URI uri : dependencyUris) { IResource resource = getResourceFromURI(uri); resources.add(resource); } } Display.getDefault().asyncExec(new Runnable() { public void run() { promptUser(resources.toArray(new IResource[0])); } }); }</code><technical_language>is need for a LinkedList here, a plain ArrayList</technical_language>

Target:
public void mergeResolutionCompleted(Comparison comparison) { EList<MatchResource> matchResources = comparison.getMatchedResources(); final List<IResource> resources = new LinkedList<IResource>(); for (MatchResource matchResource : matchResources) { URI matchUri = matchResource.getLeft().getURI(); Set<URI> dependencyUris = dependencies.of(matchUri, matchResource.getLeft().getResourceSet() .getURIConverter()); for (URI uri : dependencyUris) { IResource resource = getResourceFromURI(uri); resources.add(resource); } } Display.getDefault().asyncExec(new Runnable() { public void run() { promptUser(resources.toArray(new IResource[resources.size()])); } }); }
Source:
<code>public static AdColonyAdSize adColonyAdSizeFromAdMobAdSize(Context context, AdSize adSize) { ArrayList<AdSize> potentials = new ArrayList<>(3); potentials.add(0, AdSize.BANNER); potentials.add(1, AdSize.LEADERBOARD); potentials.add(2, AdSize.MEDIUM_RECTANGLE); potentials.add(3, AdSize.WIDE_SKYSCRAPER); AdSize closestSize = AdColonyAdapterUtils.findClosestSize(context, adSize, potentials); if (AdSize.BANNER.equals(closestSize)) { return AdColonyAdSize.BANNER; } else if (AdSize.MEDIUM_RECTANGLE.equals(closestSize)) { return AdColonyAdSize.MEDIUM_RECTANGLE; } else if (AdSize.LEADERBOARD.equals(closestSize)) { return AdColonyAdSize.LEADERBOARD; } else if (AdSize.WIDE_SKYSCRAPER.equals(closestSize)) { return AdColonyAdSize.SKYSCRAPER; } else { <START> return new AdColonyAdSize(adSize.getWidth(),adSize.getHeight()); <END> } }</code><technical_language>adSize is returned here, is a random size is supported admob returns null</technical_language>

Target:
public static AdColonyAdSize adColonyAdSizeFromAdMobAdSize(Context context, AdSize adSize) { ArrayList<AdSize> potentials = new ArrayList<>(3); potentials.add(0, AdSize.BANNER); potentials.add(1, AdSize.LEADERBOARD); potentials.add(2, AdSize.MEDIUM_RECTANGLE); potentials.add(3, AdSize.WIDE_SKYSCRAPER); AdSize closestSize = AdColonyAdapterUtils.findClosestSize(context, adSize, potentials); if (AdSize.BANNER.equals(closestSize)) { return AdColonyAdSize.BANNER; } else if (AdSize.MEDIUM_RECTANGLE.equals(closestSize)) { return AdColonyAdSize.MEDIUM_RECTANGLE; } else if (AdSize.LEADERBOARD.equals(closestSize)) { return AdColonyAdSize.LEADERBOARD; } else if (AdSize.WIDE_SKYSCRAPER.equals(closestSize)) { return AdColonyAdSize.SKYSCRAPER; } else { return null; } }
Source:
<code>public Collection<com.datatorrent.api.Partitioner.Partition<AbstractJdbcPollInputOperator<T>>> definePartitions( Collection<Partition<AbstractJdbcPollInputOperator<T>>> partitions, PartitioningContext context) { List<Partition<AbstractJdbcPollInputOperator<T>>> newPartitions = new ArrayList<Partition<AbstractJdbcPollInputOperator<T>>>( getPartitionCount()); HashMap<Integer, KeyValPair<Integer, Integer>> partitionToRangeMap = null; try { store.connect(); intializeDSLContext(); partitionToRangeMap = getPartitionedQueryRangeMap(getPartitionCount()); } catch (SQLException e) { LOG.error("Exception in initializing the partition range", e); throw new RuntimeException(e); } finally { store.disconnect(); } KryoCloneUtils<AbstractJdbcPollInputOperator<T>> cloneUtils = KryoCloneUtils.createCloneUtils(this); for (int i = 0; i <= getPartitionCount(); i++) { AbstractJdbcPollInputOperator<T> jdbcPoller = cloneUtils.getClone(); if (i < getPartitionCount()) { jdbcPoller.rangeQueryPair = partitionToRangeMap.get(i); <START> jdbcPoller.lastEmittedRecord = partitionToRangeMap.get(i).getKey(); <END> } else { int partitionKey = partitionToRangeMap.get(i - 1).getValue(); jdbcPoller.rangeQueryPair = new KeyValPair<Integer, Integer>(partitionKey, null); jdbcPoller.lastEmittedRecord = partitionKey; jdbcPoller.isPollerPartition = true; } newPartitions.add(new DefaultPartition<AbstractJdbcPollInputOperator<T>>(jdbcPoller)); } return newPartitions; }</code><technical_language>Set jdbcPoller.isPollerPartition = false here</technical_language>

Target:
public Collection<com.datatorrent.api.Partitioner.Partition<AbstractJdbcPollInputOperator<T>>> definePartitions( Collection<Partition<AbstractJdbcPollInputOperator<T>>> partitions, PartitioningContext context) { List<Partition<AbstractJdbcPollInputOperator<T>>> newPartitions = new ArrayList<Partition<AbstractJdbcPollInputOperator<T>>>( getPartitionCount()); HashMap<Integer, KeyValPair<Integer, Integer>> partitionToRangeMap = null; try { store.connect(); intializeDSLContext(); partitionToRangeMap = getPartitionedQueryRangeMap(getPartitionCount()); } catch (SQLException e) { LOG.error("Exception in initializing the partition range", e); throw new RuntimeException(e); } finally { store.disconnect(); } KryoCloneUtils<AbstractJdbcPollInputOperator<T>> cloneUtils = KryoCloneUtils.createCloneUtils(this); for (int i = 0; i <= getPartitionCount(); i++) { AbstractJdbcPollInputOperator<T> jdbcPoller = cloneUtils.getClone(); if (i < getPartitionCount()) { jdbcPoller.rangeQueryPair = partitionToRangeMap.get(i); jdbcPoller.lastEmittedRow = partitionToRangeMap.get(i).getKey(); jdbcPoller.isPollerPartition = false; } else { int partitionKey = partitionToRangeMap.get(i - 1).getValue(); jdbcPoller.rangeQueryPair = new KeyValPair<Integer, Integer>(partitionKey, null); jdbcPoller.lastEmittedRow = partitionKey; jdbcPoller.isPollerPartition = true; } newPartitions.add(new DefaultPartition<AbstractJdbcPollInputOperator<T>>(jdbcPoller)); } return newPartitions; }
Source:
<code>int adjustValue(long value, int offsetIndex) { <START> if (inDictionaryStream != null) { <END> if (!inDictionaryFlags[offsetIndex]) { value += stripeDictionarySize; } } return toIntExact(value); }</code><technical_language>private - this change, test method simplified int remove toIntExact call private boolean test(int dictionaryPosition) { ... }</technical_language>

Target:
private int adjustValue(long value, int offsetIndex) { if (inDictionaryStream != null && !inDictionaryFlags[offsetIndex]) { return toIntExact(value + stripeDictionarySize); } return toIntExact(value); }
Source:
<code>public void testStoreAndLoadWithRolloutTrigger() throws InterruptedException { String srvStateInXML = client.configMaps().inNamespace(testNamespace) .withName(TEST_KIE_SERVER_ID).get().getData().get(KieServerStateCloudRepository.CFG_MAP_DATA_KEY); KieServerState kieServerState = (KieServerState) xs.fromXML(srvStateInXML); repo.store(TEST_KIE_SERVER_ID, kieServerState); <START> assertNotNull(client.configMaps().inNamespace(testNamespace) <END> .withName(TEST_KIE_SERVER_ID) .get() .getMetadata() .getAnnotations() .containsKey(KieServerStateCloudRepository.ROLLOUT_REQUIRED)); }</code><technical_language>I suppose "assertTrue" here</technical_language>

Target:
public void testStoreAndLoadWithRolloutTrigger() throws InterruptedException { String srvStateInXML = client.configMaps().inNamespace(testNamespace) .withName(TEST_KIE_SERVER_ID).get().getData().get(KieServerStateCloudRepository.CFG_MAP_DATA_KEY); KieServerState kieServerState = (KieServerState) xs.fromXML(srvStateInXML); repo.store(TEST_KIE_SERVER_ID, kieServerState); assertTrue(client.configMaps().inNamespace(testNamespace) .withName(TEST_KIE_SERVER_ID) .get() .getMetadata() .getAnnotations() .containsKey(KieServerStateCloudRepository.ROLLOUT_REQUIRED)); }
Source:
<code>public void findCollections() throws Exception { getClient().perform(get("/api/config/submissiondefinitions/traditional/collections")) <START> .andExpect(status().isForbidden()); <END> String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/config/submissiondefinitions/traditional/collections")) .andExpect(status().isNoContent()); }</code><technical_language>isUnauthorized 403</technical_language>

Target:
public void findCollections() throws Exception { getClient().perform(get("/api/config/submissiondefinitions/traditional/collections")) .andExpect(status().isUnauthorized()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/config/submissiondefinitions/traditional/collections")) .andExpect(status().isNoContent()); }
Source:
<code>private boolean validateArgumentTypes(JsonToken tokenType, String expectedType) { if (expectedType != null && expectedType.equalsIgnoreCase(tokenType.toString())) { return true; } else if (tokenType == JsonToken.NULL) { return true; } else if (tokenType == JsonToken.NUMBER) { if (expectedType != null && (expectedType.equals("int") || expectedType.equals("long") || expectedType.equals("double") || expectedType.equals("float") || expectedType.equals("decimal") <START> || expectedType.equals("byte") || expectedType.equals("short"))) { <END> return true; } } else if (tokenType == JsonToken.STRING) { if (expectedType != null && (expectedType.equals("string") || expectedType.equals("date") || expectedType.equals("time") || expectedType.equals("datetime") || expectedType.equals("base64Binary"))) { return true; } } return false; }</code><technical_language>do check **"int".equals(expectedType)** . avoid null check beginning</technical_language>

Target:
private boolean validateArgumentTypes(JsonToken tokenType, String expectedType) { if (expectedType != null && expectedType.equalsIgnoreCase(tokenType.toString())) { return true; } else if (tokenType == JsonToken.NULL) { return true; } else if (tokenType == JsonToken.NUMBER) { if ("int".equals(expectedType) || "long".equals(expectedType) || "double".equals(expectedType) || "float".equals(expectedType) || "decimal".equals(expectedType) || "byte".equals(expectedType) || "short".equals(expectedType)) { return true; } } else if (tokenType == JsonToken.STRING) { if ("string".equals(expectedType) || "date".equals(expectedType) || "time".equals(expectedType) || "datetime".equals(expectedType) || "base64Binary".equals(expectedType)) { return true; } } return false; }
Source:
<code>public void afterTaskCompletedEvent(TaskEvent event) { Task task = event.getTask(); long processInstanceId = task.getTaskData().getProcessInstanceId(); if (processInstanceId <= 0) { return; } RuntimeManager manager = getManager(task); if (manager == null) { throw new RuntimeException("No RuntimeManager registered with identifier: " + task.getTaskData().getDeploymentId()); } RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId)); KieSession session = runtime.getKieSession(); if (session != null) { logger.debug(">> I've recieved an event for a known session (" + task.getTaskData().getProcessSessionId()+")"); processTaskState(task); } else { logger.error("EE: I've recieved an event but the session is not known by this handler ( "+task.getTaskData().getProcessSessionId()+")"); } <START> processTaskState(task); <END> }</code><technical_language>This is called line 111, do need call here</technical_language>

Target:
public void afterTaskCompletedEvent(TaskEvent event) { Task task = event.getTask(); long processInstanceId = task.getTaskData().getProcessInstanceId(); if (processInstanceId <= 0) { return; } RuntimeManager manager = getManager(task); if (manager == null) { throw new RuntimeException("No RuntimeManager registered with identifier: " + task.getTaskData().getDeploymentId()); } RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId)); KieSession session = runtime.getKieSession(); if (session != null) { logger.debug(">> I've recieved an event for a known session (" + task.getTaskData().getProcessSessionId()+")"); processTaskState(task); } else { logger.error("EE: I've recieved an event but the session is not known by this handler ( "+task.getTaskData().getProcessSessionId()+")"); } }
Source:
<code>protected List<ILinkEvent> getLinkList(long startTime, long endTime, long resolution, IProgressMonitor monitor) { <START> return new ArrayList<>(); <END> }</code><technical_language>Collections.EMPTY_LIST</technical_language>

Target:
protected List<ILinkEvent> getLinkList(long startTime, long endTime, long resolution, IProgressMonitor monitor) { return Collections.EMPTY_LIST; }
Source:
<code>protected void init() throws IOException { _selector = Selector.open(); Task task = null; try { _clientConnection = SocketChannel.open(); s_logger.info("Connecting to " + _host + ":" + _port); final InetSocketAddress peerAddr = new InetSocketAddress(_host, _port); _clientConnection.connect(peerAddr); _clientConnection.configureBlocking(false); final SSLContext sslContext = Link.initSSLContext(true); SSLEngine sslEngine = sslContext.createSSLEngine(_host, _port); sslEngine.setUseClientMode(true); sslEngine.setEnabledProtocols(SSLUtils.getSupportedProtocols(sslEngine.getEnabledProtocols())); sslEngine.beginHandshake(); if (!Link.doHandshake(_clientConnection, sslEngine)) { s_logger.error("SSL Handshake failed!"); _selector.close(); <START> throw new IOException("SSL Handshake failed!"); <END> } s_logger.info("SSL: Handshake done"); s_logger.info("Connected to " + _host + ":" + _port); final Link link = new Link(peerAddr, this); link.setSSLEngine(sslEngine); final SelectionKey key = _clientConnection.register(_selector, SelectionKey.OP_READ); link.setKey(key); key.attach(link); task = _factory.create(Task.Type.CONNECT, link, null); } catch (final GeneralSecurityException e) { _selector.close(); throw new IOException("Failed to initialise security", e); } catch (final IOException e) { _selector.close(); throw e; } _executor.submit(task); }</code><technical_language>Please include _host _port in error message assist operational debugging</technical_language>

Target:
protected void init() throws IOException { _selector = Selector.open(); Task task = null; try { _clientConnection = SocketChannel.open(); s_logger.info("Connecting to " + _host + ":" + _port); final InetSocketAddress peerAddr = new InetSocketAddress(_host, _port); _clientConnection.connect(peerAddr); _clientConnection.configureBlocking(false); final SSLContext sslContext = Link.initSSLContext(true); SSLEngine sslEngine = sslContext.createSSLEngine(_host, _port); sslEngine.setUseClientMode(true); sslEngine.setEnabledProtocols(SSLUtils.getSupportedProtocols(sslEngine.getEnabledProtocols())); sslEngine.beginHandshake(); if (!Link.doHandshake(_clientConnection, sslEngine, true)) { s_logger.error("SSL Handshake failed while connecting to host: " + _host + " port: " + _port); _selector.close(); throw new IOException("SSL Handshake failed while connecting to host: " + _host + " port: " + _port); } s_logger.info("SSL: Handshake done"); s_logger.info("Connected to " + _host + ":" + _port); final Link link = new Link(peerAddr, this); link.setSSLEngine(sslEngine); final SelectionKey key = _clientConnection.register(_selector, SelectionKey.OP_READ); link.setKey(key); key.attach(link); task = _factory.create(Task.Type.CONNECT, link, null); } catch (final GeneralSecurityException e) { _selector.close(); throw new IOException("Failed to initialise security", e); } catch (final IOException e) { _selector.close(); throw e; } _executor.submit(task); }
Source:
<code>private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { <START> if (continuesMessageSubscriber.get() != null && continuesMessageSubscriber.get().isDisposed()) { <END> logger.error("[{}]: Can not receive messaged because client is closed.", asyncClient.getEntityPath()); return; } if (continuesMessageSubscriber.get() == null) { ContinuesMessageSubscriber messageSubscriber = asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(new ContinuesMessageSubscriber(maximumMessageCount, emitter)); if (!continuesMessageSubscriber.compareAndSet(null, messageSubscriber)) { messageSubscriber.dispose(); } logger.info("[{}]: Started ContinuesMessageSubscriber message subscriber for entity.", asyncClient.getEntityPath()); } else { continuesMessageSubscriber.get().request(maximumMessageCount, emitter); } }</code><technical_language>null checks sets subscriber null retrieve a time</technical_language>

Target:
private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } }
Source:
<code>public synchronized void add(PrestoWarning warning) { requireNonNull(warning, "warning is null"); if (size < config.getMaxWarnings() && (warningCodeCounts.containsKey(warning.getWarningCode().getCode()) ? warningCodeCounts.size() <= config.getMaxDistinctWarningCodes() : warningCodeCounts.size() < config.getMaxDistinctWarningCodes())) { int warningCodeCount = warningCodeCounts.getOrDefault(warning.getWarningCode().getCode(), 0); <START> if (warningCodeCount < config.getMaxWarningsPerWarningCode()) { <END> warnings.add(warning); warningCodeCounts.put(warning.getWarningCode().getCode(), ++warningCodeCount); size++; } } }</code><technical_language>"max warnings code", "max distinct warning codes", etc? This overly complicated. start with, warnings single-occurrence. is, report unique warning once</technical_language>

Target:
public synchronized void add(PrestoWarning warning) { requireNonNull(warning, "warning is null"); if (warnings.size() < config.getMaxWarnings()) { warnings.putIfAbsent(warning.getWarningCode(), warning); } }
Source:
<code>public static Clan fromDto(com.faforever.client.api.dto.Clan dto) { Clan clan = new Clan(); <START> clan.setId(Integer.parseInt(dto.getId())); <END> clan.setName(dto.getName()); clan.setDescription(dto.getDescription()); clan.setFounder(Player.fromDto(dto.getFounder())); clan.setLeader(Player.fromDto(dto.getLeader())); clan.setCreateTime(dto.getCreateTime().toInstant()); clan.setTag(dto.getTag()); clan.setTagColor(dto.getTagColor()); clan.setWebsiteUrl(dto.getWebsiteUrl()); clan.membersProperty().setAll(dto.getMemberships().stream() .map(membership -> Player.fromDto(membership.getPlayer())) .collect(Collectors.toList())); return clan; }</code><technical_language>prevent making this clan bean's ID String well? Otherwise, this is a gamble</technical_language>

Target:
public static Clan fromDto(com.faforever.client.api.dto.Clan dto) { Clan clan = new Clan(); clan.setId(dto.getId()); clan.setName(dto.getName()); clan.setDescription(dto.getDescription()); clan.setFounder(Player.fromDto(dto.getFounder())); clan.setLeader(Player.fromDto(dto.getLeader())); clan.setCreateTime(dto.getCreateTime().toInstant()); clan.setTag(dto.getTag()); clan.setTagColor(dto.getTagColor()); clan.setWebsiteUrl(dto.getWebsiteUrl()); clan.membersProperty().setAll(dto.getMemberships().stream() .map(membership -> Player.fromDto(membership.getPlayer())) .collect(Collectors.toList())); return clan; }
Source:
<code>public ScheduledFuture scheduleTask() { return scheduler.scheduleWithFixedDelay(() -> { try { LOG.info("Checking for job model version upgrade"); String blobJMV = blob.getJobModelVersion(); <START> LOG.info("Blob JMV: {}", blobJMV); <END> String blobBarrierState = blob.getBarrierState(); String currentJMV = currentJMVersion.get(); LOG.info("currentJMV: {}", currentJMV); String expectedBarrierState = BarrierState.START.toString() + " " + blobJMV; List<String> processorList = blob.getLiveProcessorList(); if (processorList != null && processorList.contains(processorId) && !currentJMV.equals(blobJMV) && blobBarrierState.equals(expectedBarrierState) && !versionUpgradeDetected.get()) { listener.onStateChange(); } } catch (Exception e) { errorHandler.accept("Exception in Job Model Version Upgrade Scheduler. Stopping the processor..."); } }, JMV_UPGRADE_DELAY_SEC, JMV_UPGRADE_DELAY_SEC, TimeUnit.SECONDS); }</code><technical_language>nit: log line more descriptive - *JobModel version blob is {}*</technical_language>

Target:
public ScheduledFuture scheduleTask() { return scheduler.scheduleWithFixedDelay(() -> { try { LOG.info("Checking for job model version upgrade"); String blobJMV = blob.getJobModelVersion(); LOG.info("Job Model Version seen on the blob: {}", blobJMV); String blobBarrierState = blob.getBarrierState(); String currentJMV = currentJMVersion.get(); LOG.info("Current Job Model Version that the job coordinator is working on: {}", currentJMV); String expectedBarrierState = BarrierState.START.toString() + " " + blobJMV; List<String> processorList = blob.getLiveProcessorList(); if (processorList != null && processorList.contains(processorId) && !currentJMV.equals(blobJMV) && blobBarrierState.equals(expectedBarrierState) && !versionUpgradeDetected.get()) { listener.onStateChange(); } } catch (Exception e) { errorHandler.accept("Exception in Job Model Version Upgrade Scheduler. Stopping the processor..."); } }, JMV_UPGRADE_DELAY_SEC, JMV_UPGRADE_DELAY_SEC, TimeUnit.SECONDS); }
Source:
<code><START> public synchronized void onConfigurationChange(Configuration newConf) { <END> initReconfigurable(newConf); if (scheduler instanceof ConfigurationObserver) { ((ConfigurationObserver)scheduler).onConfigurationChange(newConf); } System.setProperty("hadoop.policy.file", "hbase-policy.xml"); this.authManager.refresh(newConf, new HBasePolicyProvider()); LOG.info("Refreshed hbase-policy.xml successfully"); ProxyUsers.refreshSuperUserGroupsConfiguration(newConf); LOG.info("Refreshed super and proxy users successfully"); }</code><technical_language>If want this change, master, branch-2 right</technical_language>

Target:
public void onConfigurationChange(Configuration newConf) { initReconfigurable(newConf); if (scheduler instanceof ConfigurationObserver) { ((ConfigurationObserver)scheduler).onConfigurationChange(newConf); } if (authorize) { refreshAuthManager(newConf, new HBasePolicyProvider()); } }
Source:
<code>public void testCourseStartingDateBeforeExpiry() { final String expectedOutput = "Starting December 5"; final String expiry = "2018-12-30T00:00:00+05:00"; final String start = "2018-12-05T00:00:00+05:00"; <START> final String end = "2019-12-01T00:00:00+05:00"; <END> final String output = CourseCardUtils.getFormattedDate(context, today, expiry, start, end, StartType.TIMESTAMP, null); assertEquals(expectedOutput, output); }</code><technical_language>For code clarity move this end date in setup, common in test cases</technical_language>

Target:
public void testCourseStartingDateBeforeExpiry() { final String expectedOutput = "Starting December 5"; final String expiry = "2018-12-30T00:00:00+05:00"; final String start = "2018-12-05T00:00:00+05:00"; final String output = CourseCardUtils.getFormattedDate(context, today, expiry, start, end, StartType.TIMESTAMP, null); assertEquals(expectedOutput, output); }
Source:
<code>public Long getMinLockedInVersionId(String client) { log.warn("Client attempted to getMinLockedInVersionId() on a non-transactional lock service!" + " If you are using async timelock, this suggests that one of your AtlasDB clients still" + " expects synchronous lock (i.e. is on a version of AtlasDB prior to 0.49.0). Please check" + " that all AtlasDB clients are using AtlasDB >= 0.49.0." <START> + " This check may be disabled by explicitly setting 'useAsyncSafetyCheck' to false in" <END> + " your timelock server configuration, but note that this may cause *DATA CORRUPTION* if" + " performing a rolling upgrade of an AtlasDB client to >= 0.49.0.", UnsafeArg.of("client", client)); throw new BadRequestException("getMinLockedInVersionId() not supported on non-transactional lock" + " service. Please consult the server logs for more detail."); }</code><technical_language>This name is out of sync config - remove deployments ask themselves</technical_language>

Target:
public Long getMinLockedInVersionId(String client) { log.warn("Client attempted to getMinLockedInVersionId() on a non-transactional lock service!" + " If you are using async timelock, this suggests that one of your AtlasDB clients still" + " expects synchronous lock (i.e. is on a version of AtlasDB prior to 0.49.0). Please check" + " that all AtlasDB clients are using AtlasDB >= 0.49.0.", UnsafeArg.of("client", client)); throw new BadRequestException("getMinLockedInVersionId() not supported on non-transactional lock" + " service. Please consult the server logs for more detail."); }
Source:
<code>public Matrix4d[] getNcsOperators(boolean orthonormalBasis) { if(orthonormalBasis) { return ncsOperators; } if(ncsOperators==null || ncsOperators.length == 0) { return null; } Matrix4d[] ncsOperatorsCrystal = new Matrix4d[ncsOperators.length]; for(int i=0;i<ncsOperators.length;i++) { <START> ncsOperatorsCrystal[i] = cell.transfToCrystal(ncsOperators[i]); <END> } return ncsOperatorsCrystal; }</code><technical_language>cell potentially null in some edge cases. I cases exist ncs operators structure is crystallographic (and a cell). in case of incomplete file cell null</technical_language>

Target:
public Matrix4d[] getNcsOperators(boolean orthonormalBasis) { if(orthonormalBasis) { return ncsOperators; } if(ncsOperators==null || ncsOperators.length == 0) { return null; } if(cell==null) { throw new IllegalArgumentException("Cannot transform to the crystal basis if there is no cell."); } Matrix4d[] ncsOperatorsCrystal = new Matrix4d[ncsOperators.length]; for(int i=0;i<ncsOperators.length;i++) { ncsOperatorsCrystal[i] = cell.transfToCrystal(ncsOperators[i]); } return ncsOperatorsCrystal; }
Source:
<code>public String getTournament(Model model, HttpSession session) { Member member = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); member = memberDao.getMemberById(member.getId()); if (member == null || member.getContext() != UserType.ADMIN) { <START> System.out.println("shouldn't be here"); <END> System.out.println(member.getContext()); return "redirect:/denied"; } Set<Team> teams = member.getTeams(); model.addAttribute("teams", teams); TournamentDao tournamentDao = new TournamentDao(); List<Tournament> tournaments = tournamentDao.getLastXTournaments(5); model.addAttribute("tournaments", tournaments); return "admin"; }</code><technical_language>2 Log statements</technical_language>

Target:
public String getTournament(Model model, HttpSession session) { Member member = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); member = memberDao.getMemberById(member.getId()); if (member == null || member.getContext() != UserType.ADMIN) { return "redirect:/denied"; } Set<Team> teams = member.getTeams(); model.addAttribute("teams", teams); TournamentDao tournamentDao = new TournamentDao(); List<Tournament> tournaments = tournamentDao.getLastXTournaments(5); model.addAttribute("tournaments", tournaments); return "admin"; }
Source:
<code>protected FilterNode rewrite(Context context, FilterNode node, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { PlanNode source = node.getSource(); <START> ImmutableMap<VariableReferenceExpression, RowExpression> <END> dereferencesMap = expressions.inverse().entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); Assignments assignments = Assignments.builder().putAll(identityAssignmentsAsSymbolReferences(source.getOutputVariables())).putAll(dereferencesMap).build(); ProjectNode projectNode = new ProjectNode(context.getIdAllocator().getNextId(), source, assignments); RowExpression filter = castToRowExpression(ExpressionTreeRewriter.rewriteWith(new DereferenceReplacer(expressions), castToExpression(node.getPredicate()))); return new FilterNode( context.getIdAllocator().getNextId(), projectNode, filter); }</code><technical_language>ImmutableMap -> Map - formatting Map<VariableReferenceExpression, RowExpression> dereferencesMap = expressions.inverse().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); Assignments assignments = Assignments.builder() .putAll(identityAssignmentsAsSymbolReferences(source.getOutputVariables())) .putAll(dereferencesMap) .build();</technical_language>

Target:
protected FilterNode rewrite(Context context, FilterNode node, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { PlanNode source = node.getSource(); Map<VariableReferenceExpression, RowExpression> dereferencesMap = expressions.inverse().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); Assignments assignments = Assignments.builder() .putAll(identityAssignmentsAsSymbolReferences(source.getOutputVariables())) .putAll(dereferencesMap) .build(); ProjectNode projectNode = new ProjectNode(context.getIdAllocator().getNextId(), source, assignments); return new FilterNode( context.getIdAllocator().getNextId(), projectNode, replaceDereferences(node.getPredicate(), expressions)); }
Source:
<code>private Map<ByteArray, PersistableNetworkPayload> getMapForDataResponse(String requestersVersion) { Map<ByteArray, PersistableNetworkPayload> map = new HashMap<>(); appendOnlyDataStoreService.getServices() .forEach(service -> { Map<ByteArray, PersistableNetworkPayload> serviceMap; if (service instanceof HistoricalDataStoreService) { var historicalDataStoreService = (HistoricalDataStoreService<? extends PersistableNetworkPayloadStore>) service; serviceMap = historicalDataStoreService.getMapSinceVersion(requestersVersion); <START> map.putAll(serviceMap); } else { serviceMap = service.getMap(); map.putAll(serviceMap); } <END> log.info("We added entries from to be filtered by excluded keys", serviceMap.size(), service.getClass().getSimpleName()); }); return map; }</code><technical_language>suggestion } else { serviceMap = service.getMap(); } map.putAll(serviceMap);</technical_language>

Target:
private Map<ByteArray, PersistableNetworkPayload> getMapForDataResponse(String requestersVersion) { Map<ByteArray, PersistableNetworkPayload> map = new HashMap<>(); appendOnlyDataStoreService.getServices() .forEach(service -> { Map<ByteArray, PersistableNetworkPayload> serviceMap; if (service instanceof HistoricalDataStoreService) { var historicalDataStoreService = (HistoricalDataStoreService<? extends PersistableNetworkPayloadStore>) service; serviceMap = historicalDataStoreService.getMapSinceVersion(requestersVersion); } else { serviceMap = service.getMap(); } map.putAll(serviceMap); log.info("We added entries from to be filtered by excluded keys", serviceMap.size(), service.getClass().getSimpleName()); }); return map; }
Source:
<code>public void createProject() throws ProjectCreationFailedException { final StringBuilder err = validateParameters(); if (err.length() == 0) { try { <START> nameKey = new Project.NameKey(createProjectArgs.getProjectName()); <END> final String head = createProjectArgs.isPermissionsOnly() ? GitRepositoryManager.REF_CONFIG : createProjectArgs .getBranch(); final Repository repo = repoManager.createRepository(nameKey); try { rq.replicateNewProject(nameKey, head); final RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!createProjectArgs.isPermissionsOnly() && createProjectArgs.isCreateEmptyCommit()) { createEmptyCommit(repo, nameKey, createProjectArgs.getBranch()); } } finally { repo.close(); } } catch (RepositoryCaseMismatchException ee) { throw new ProjectCreationFailedException("Cannot create \"" + nameKey + "\" because the name is already occupied by another project. " + "The other project has the same name, only spelled in " + "a different case.", ee); } catch (RepositoryNotFoundException e) { throw new ProjectCreationFailedException("Repository not exists", e); } catch (IOException e) { throw new ProjectCreationFailedException("IO error", e); } catch (ConfigInvalidException e) { throw new ProjectCreationFailedException("Configuration error", e); } catch (IllegalStateException e) { try { Repository repo = repoManager.openRepository(nameKey); try { if (repo.getObjectDatabase().exists()) { throw new ProjectCreationFailedException("Project \"" + nameKey + "\" exists", e); } } finally { repo.close(); } } catch (RepositoryNotFoundException er) { throw new ProjectCreationFailedException("Cannot create \"" + nameKey + "\"", er); } } } else { throw new ProjectCreationFailedException("validation error:" + err); } }</code><technical_language>[optional] createProjectArgs.getProjectName() return a Project.NameKey a String</technical_language>

Target:
public void createProject() throws ProjectCreationFailedException { validateParameters(); try { nameKey = createProjectArgs.getProject(); final String head = createProjectArgs.permissionsOnly ? GitRepositoryManager.REF_CONFIG : createProjectArgs.branch; final Repository repo = repoManager.createRepository(nameKey); try { rq.replicateNewProject(nameKey, head); final RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!createProjectArgs.permissionsOnly && createProjectArgs.createEmptyCommit) { createEmptyCommit(repo, nameKey, createProjectArgs.branch); } } finally { repo.close(); } } catch (IllegalStateException e) { handleRepositoryExistsException(nameKey, e); } catch (RepositoryCaseMismatchException ee) { handleRepositoryExistsException(ee.getNameOfExistingProject(), ee); } catch (RepositoryNotFoundException e) { throw new ProjectCreationFailedException("Repository not exists", e); } catch (IOException e) { throw new ProjectCreationFailedException("IO error", e); } catch (ConfigInvalidException e) { throw new ProjectCreationFailedException("Configuration error", e); } }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { List<TmfEventTableColumn> columns = getColumns(event.getApplicationContext()); long start = <START> getStart(event.getApplicationContext()); <END> long end = getEnd(event.getApplicationContext()); ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); ITmfFilter filter = TmfTraceManager.getInstance().getCurrentTraceContext().getFilter(); if (trace != null) { Job job = new CopyToClipboardJob(trace, filter, columns, start, end); job.schedule(); } return null; }</code><technical_language>extract var? getApplicationContext is called3 times</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { List<TmfEventTableColumn> columns = getColumns(event.getApplicationContext()); Long start = getStart(event.getApplicationContext()); Long end = getEnd(event.getApplicationContext()); ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); ITmfFilter filter = TmfTraceManager.getInstance().getCurrentTraceContext().getFilter(); if (trace != null && columns != null && start != null && end != null) { Job job = new CopyToClipboardJob(trace, filter, columns, start, end); job.schedule(); } return null; }
Source:
<code>public void testDefaultProperties() { Map<String, String> defaultProperties = ap.getDefaultProperties(); Assert.assertEquals(7, defaultProperties.size()); Map<String, String> defaultPropertiesValidationMap = new HashMap<String, String>(); <START> defaultPropertiesValidationMap.put("dt.test.1", "package-default"); <END> defaultPropertiesValidationMap.put("dt.test.2", "package-default"); defaultPropertiesValidationMap.put("dt.test.3", "package-default"); defaultPropertiesValidationMap.put("dt.test.4", "package-default"); defaultPropertiesValidationMap.put("dt.test.5", "package-default"); defaultPropertiesValidationMap.put("dt.test.6", "package-default"); defaultPropertiesValidationMap.put("dt.operator.testModule.prop.testInput", "default-value-1"); for (String key : ap.getDefaultProperties().keySet()) { Assert.assertEquals(defaultPropertiesValidationMap.get(key), defaultProperties.get(key)); } }</code><technical_language>do assert putting key-val map</technical_language>

Target:
public void testDefaultProperties() { Map<String, AppPackage.PropertyInfo> defaultProperties = ap.getDefaultProperties(); Assert.assertEquals(8, defaultProperties.size()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.1").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.2").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.3").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.4").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.5").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.6").getValue()); Assert.assertEquals("default-value-1", defaultProperties.get("dt.operator.testModule.prop.testInput").getValue()); Assert.assertEquals("default-value-1", defaultProperties.get("dt.operator.stdout.prop.testInput").getValue()); }
Source:
<code>public void extractAgent() throws Exception { agentJar = new File(tmpDir.getRoot(), "old-agent.jar"); <START> FileUtils.copyURLToFile(getClass().getResource("/old-remoting/remoting-minimal-supported.jar"), agentJar); <END> }</code><technical_language>BTW a stylistic matter is safest OldRemotingAgentTest.class in place of getClass(). (Unless test suite is final in case equivalent.)</technical_language>

Target:
public void extractAgent() throws Exception { agentJar = new File(tmpDir.getRoot(), "old-agent.jar"); FileUtils.copyURLToFile(OldRemotingAgentTest.class.getResource("/old-remoting/remoting-minimal-supported.jar"), agentJar); }
Source:
<code>public void testNonEmptyInputs(boolean... inputSequence) { <START> List<Object> booleanList = new ArrayList<>(); <END> for (boolean b : inputSequence) { booleanList.add(b); } assertCount(booleanList, 0, distinctCount(booleanList)); }</code><technical_language>nit: List<Boolean> booleanList = Booleans.asList(inputSequence);</technical_language>

Target:
public void testNonEmptyInputs(boolean... inputSequence) { List<Boolean> values = Booleans.asList(inputSequence); assertCount(values, 0, distinctCount(values)); }
Source:
<code>private PeekingIterator<JsonNode> configureSplitObj(Iterator<JsonNode> nodeItr){ <START> if (!nodeItr.hasNext()) { <END> throw new MarkLogicIOException("No header found."); } PeekingIterator<JsonNode> peekingIterator = new PeekingIterator<JsonNode>(nodeItr); csvHeaderNode = peekingIterator.getFirst(); Iterator<String> headerValue = csvHeaderNode.fieldNames(); this.headers = new ObjectMapper().createArrayNode(); while (headerValue.hasNext()) { headers.add(headerValue.next()); } return peekingIterator; }</code><technical_language>defend NPE, test nodeItr == null || !nodeItr.hasNext()</technical_language>

Target:
private PeekingIterator<JsonNode> configureSplitObj(Iterator<JsonNode> nodeItr){ if (nodeItr == null || !nodeItr.hasNext()) { throw new MarkLogicIOException("No header found."); } PeekingIterator<JsonNode> peekingIterator = new PeekingIterator<JsonNode>(nodeItr); Iterator<String> headerValue = peekingIterator.getFirst().fieldNames(); this.headers = new ObjectMapper().createArrayNode(); while (headerValue.hasNext()) { headers.add(headerValue.next()); } return peekingIterator; }