auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private String constructEntityIdsAsCSV(Set<String> entityIds) throws UnsupportedEncodingException { if (entityIds.size() == 0) { return ""; } Set<String> ids = Sets.newHashSet(); for (String id : entityIds) { ids.add("\"" + id + "\""); } Joiner join = Joiner.on(","); <START> return join.join(ids); <END> }</code><technical_language>nit: need statements</technical_language>

Target:
private String constructEntityIdsAsCSV(Set<String> entityIds) throws UnsupportedEncodingException { if (CollectionUtils.isEmpty(entityIds)) { return ""; } Set<String> ids = Sets.newHashSet(); for (String id : entityIds) { ids.add("\"" + id + "\""); } return Joiner.on(",").join(ids); }
Source:
<code>private void storeConsolesInternal(VmConsoles consoles, boolean isPool) { ConsoleProtocol selectedProtocol = consoles.getSelectedProcotol(); ConsoleContext context = consoles.getConsoleContext(); String id = isPool <START> ? consoles.getVm().getVmPoolId().toString() <END> : consoles.getVm().getId().toString(); KeyMaker keyMaker = new KeyMaker(id, isPool, context); clientStorage.setLocalItem(keyMaker.make(SELECTED_PROTOCOL), selectedProtocol.toString()); if (selectedProtocol == ConsoleProtocol.SPICE) { storeSpiceData(consoles, keyMaker); } else if (selectedProtocol == ConsoleProtocol.VNC) { storeVncData(consoles, keyMaker); } else if (selectedProtocol == ConsoleProtocol.RDP) { storeRdpData(consoles, keyMaker); } }</code><technical_language>get name</technical_language>

Target:
private void storeConsolesInternal(VmConsoles consoles, boolean isPool) { ConsoleProtocol selectedProtocol = consoles.getSelectedProcotol(); ConsoleContext context = consoles.getConsoleContext(); String id = consoles.getEntityId().toString(); KeyMaker keyMaker = new KeyMaker(id, isPool, context); clientStorage.setLocalItem(keyMaker.make(SELECTED_PROTOCOL), selectedProtocol.toString()); if (selectedProtocol == ConsoleProtocol.SPICE) { storeSpiceData(consoles, keyMaker); } else if (selectedProtocol == ConsoleProtocol.VNC) { storeVncData(consoles, keyMaker); } else if (selectedProtocol == ConsoleProtocol.RDP) { storeRdpData(consoles, keyMaker); } }
Source:
<code>public void containerExists() throws InterruptedException { if(System.getProperty("os.name").contains("indows")) throw new SkipException("not yet implemented"); <START> else <END> super.containerExists(); }</code><technical_language>call a helper method: java private static void skipIfWindows() { if (System.getProperty("os.name").contains("indows")) { throw new SkipException("not implemented"); } }</technical_language>

Target:
public void containerExists() throws InterruptedException { super.containerExists(); }
Source:
<code>public static Set<IPluginModelBase> parsePlugins(ILaunchConfiguration configuration, String attribute) throws CoreException { HashSet<IPluginModelBase> set = new HashSet<>(); Map<String, IPluginModelBase> unmatchedEntries = new HashMap<>(); <START> List<String> entries = configuration.getAttribute(attribute, Collections.emptyList()); <END> for (String token : entries) { int index = token.indexOf('@'); if (index < 0) { token = token.concat("@default:default"); index = token.indexOf('@'); } String idVersion = token.substring(0, index); int versionIndex = token.indexOf(BundleLauncherHelper.VERSION_SEPARATOR); String id = (versionIndex > 0) ? idVersion.substring(0, versionIndex) : idVersion; String version = (versionIndex > 0) ? idVersion.substring(versionIndex + 1) : null; ModelEntry entry = PluginRegistry.findEntry(id); if (entry != null) { IPluginModelBase matchingModels[] = attribute.equals(IPDELauncherConstants.SELECTED_TARGET_BUNDLES) ? entry.getExternalModels() : entry.getWorkspaceModels(); for (IPluginModelBase matchingModel : matchingModels) { if (matchingModel.isEnabled()) { if (version == null || matchingModel.getPluginBase().getVersion().equals(version)) { set.add(matchingModel); } else if (matchingModels.length == 1) { if (unmatchedEntries.remove(id) == null) { unmatchedEntries.put(id, matchingModel); } } } } } } set.addAll(unmatchedEntries.values()); return set; }</code><technical_language>change Set</technical_language>

Target:
public static Set<IPluginModelBase> parsePlugins(ILaunchConfiguration configuration, String attribute) throws CoreException { HashSet<IPluginModelBase> set = new HashSet<>(); Map<String, IPluginModelBase> unmatchedEntries = new HashMap<>(); Set<String> entries = configuration.getAttribute(attribute, Collections.emptySet()); for (String token : entries) { int index = token.indexOf('@'); if (index < 0) { token = token.concat("@default:default"); index = token.indexOf('@'); } String idVersion = token.substring(0, index); int versionIndex = token.indexOf(BundleLauncherHelper.VERSION_SEPARATOR); String id = (versionIndex > 0) ? idVersion.substring(0, versionIndex) : idVersion; String version = (versionIndex > 0) ? idVersion.substring(versionIndex + 1) : null; ModelEntry entry = PluginRegistry.findEntry(id); if (entry != null) { IPluginModelBase matchingModels[] = attribute.equals(IPDELauncherConstants.SELECTED_TARGET_BUNDLES) ? entry.getExternalModels() : entry.getWorkspaceModels(); for (IPluginModelBase matchingModel : matchingModels) { if (matchingModel.isEnabled()) { if (version == null || matchingModel.getPluginBase().getVersion().equals(version)) { set.add(matchingModel); } else if (matchingModels.length == 1) { if (unmatchedEntries.remove(id) == null) { unmatchedEntries.put(id, matchingModel); } } } } } } set.addAll(unmatchedEntries.values()); return set; }
Source:
<code><START> public void testPushReplicationFilterContinuesFromCorrectPlace() throws Exception { <END> prepareTwoDocumentsInLocalDB(); ReplicatorBuilder.Push push = this.getPushBuilder(); push.filter(new PushFilter() { @Override public boolean shouldReplicateDocument(DocumentRevision revision) { return false; } }); Replicator replicator = push.build(); replicator.start(); while (replicator.getState() != Replicator.State.COMPLETE && replicator.getState() != Replicator.State.ERROR) { Thread.sleep(50); } Assert.assertEquals(Replicator.State.COMPLETE, replicator.getState()); Assert.assertEquals(0, couchClient.getDbInfo().getDocCount()); replicator = this.getPushBuilder().build(); replicator.start(); while (replicator.getState() != Replicator.State.COMPLETE && replicator.getState() != Replicator.State.ERROR) { Thread.sleep(50); } Assert.assertEquals(Replicator.State.COMPLETE, replicator.getState()); Assert.assertEquals(0, couchClient.getDbInfo().getDocCount()); }</code><technical_language>do asserts saved sequence replication for tests? useful</technical_language>

Target:
public void testPushReplicationFilterContinuesFromCorrectPlace() throws Exception { prepareTwoDocumentsInLocalDB(); ReplicatorBuilder.Push push = this.getPushBuilder(); push.filter(new PushFilter() { @Override public boolean shouldReplicateDocument(DocumentRevision revision) { return false; } }); Replicator replicator = push.build(); replicator.start(); while (replicator.getState() != Replicator.State.COMPLETE && replicator.getState() != Replicator.State.ERROR) { Thread.sleep(50); } Assert.assertEquals(Replicator.State.COMPLETE, replicator.getState()); Assert.assertEquals(0, couchClient.getDbInfo().getDocCount()); replicator = this.getPushBuilder().build(); replicator.start(); while (replicator.getState() != Replicator.State.COMPLETE && replicator.getState() != Replicator.State.ERROR) { Thread.sleep(50); } Assert.assertEquals(Replicator.State.COMPLETE, replicator.getState()); Assert.assertEquals(0, couchClient.getDbInfo().getDocCount()); assertLastSequence(replicator); }
Source:
<code>public void doSetup() { this.registry = new DefaultSubscriptionRegistry(); this.destinations = IntStream.range(0, this.numberOfDestinations) .mapToObj(i -> "/some/destination/" + i) .toArray(String[]::new); this.sessionIds = IntStream.range(0, this.numberOfSessions) .mapToObj(i -> "sessionId_" + i) <START> .toArray(String[]::new); <END> for (String sessionId : this.sessionIds) { registerSubscriptions(sessionId, this.subscriptionsPerSession); } }</code><technical_language>some pattern destinations</technical_language>

Target:
public void doSetup() { this.findMessage = MessageBuilder.createMessage("", SimpMessageHeaderAccessor.create().getMessageHeaders()); this.uniqueIdGenerator = new AtomicInteger(); this.registry = new DefaultSubscriptionRegistry(); this.registry.setCacheLimit(this.cacheSizeLimit); this.registry.setSelectorHeaderName("selectorHeaders".equals(this.specialization) ? "someSelector" : null); this.destinationIds = IntStream.range(0, this.destinations) .mapToObj(i -> "/some/destination/" + i) .toArray(String[]::new); this.sessionIds = IntStream.range(0, this.sessions) .mapToObj(i -> "sessionId_" + i) .toArray(String[]::new); for (String sessionId : this.sessionIds) { for (String destinationId : this.destinationIds) { registerSubscriptions(sessionId, destinationId); } } }
Source:
<code>public boolean replaceNode(final Node oldOne, final @Nonnull Node newOne) throws IOException { if (oldOne == nodes.get(oldOne.getNodeName())) { Queue.withLock(new Runnable() { public void run() { Nodes.this.nodes.remove(oldOne.getNodeName()); Nodes.this.nodes.put(newOne.getNodeName(), newOne); jenkins.updateComputerList(); jenkins.trimLabels(); } }); updateNode(newOne); NodeListener.fireOnUpdated(oldOne, newOne); <START> Util.deleteRecursive(new File(getNodesDir(), oldOne.getNodeName())); <END> return true; } else { return false; } }</code><technical_language>Do need check new nodes distinct names? If I reading this right, this unconditionally, in normal case of changing node configuration _without_ renaming deleting configuration disk-so a restart node disappeared</technical_language>

Target:
public boolean replaceNode(final Node oldOne, final @Nonnull Node newOne) throws IOException { if (oldOne == nodes.get(oldOne.getNodeName())) { Queue.withLock(new Runnable() { public void run() { Nodes.this.nodes.remove(oldOne.getNodeName()); Nodes.this.nodes.put(newOne.getNodeName(), newOne); jenkins.updateComputerList(); jenkins.trimLabels(); } }); updateNode(newOne); if (!newOne.getNodeName().equals(oldOne.getNodeName())) { Util.deleteRecursive(new File(getNodesDir(), oldOne.getNodeName())); } NodeListener.fireOnUpdated(oldOne, newOne); return true; } else { return false; } }
Source:
<code>protected void makeUninstallButton() { actionButton.classList.remove("btn-primary"); actionButton.classList.add("btn-danger"); <START> actionButton.textContent = "Uninstall"; <END> }</code><technical_language>Missing i18n</technical_language>

Target:
protected void makeUninstallButton() { actionButton.classList.remove("btn-primary"); actionButton.classList.add("btn-danger"); actionButton.textContent = constants.UninstallServiceTask(); }
Source:
<code>public void shouldCleanUpBroadcasterUponDestory(){ DefaultBroadcasterFactory broadcasterFactory = new DefaultBroadcasterFactory(SimpleBroadcaster.class, "NEVER", config); Broadcaster b1 = broadcasterFactory.lookup("/LEAK/EXISTS", true); b1.destroy(); <START> Assert.assertNull(broadcasterFactory.lookup("/LEAJ/EXISTS")); <END> }</code><technical_language>test in for Broadcaster :-)</technical_language>

Target:
public void shouldCleanUpBroadcasterUponDestory(){ Broadcaster b1 = config.getBroadcasterFactory().lookup("/LEAK/EXISTS", true); b1.destroy(); Assert.assertNull(config.getBroadcasterFactory().lookup("/LEAK/EXISTS")); }
Source:
<code>public AbstractClassVisitor() { <START> super(Opcodes.ASM7); <END> }</code><technical_language>edu.umd.cs.findbugs.classfile.engine.asm.FindBugsASM.ASM_VERSION, prevent this happening in future</technical_language>

Target:
public AbstractClassVisitor() { super(FindBugsASM.ASM_VERSION); }
Source:
<code>public ReverseDebugPreferencePage() { super( GRID ); IPreferenceStore store = CDebugUIPlugin.getDefault().getPreferenceStore(); setPreferenceStore( store ); <START> setDescription( "Reverse Debug Settings" ); END> }</code><technical_language>string needs translatable in a messages.properties file</technical_language>

Target:
public ReverseDebugPreferencePage() { super( GRID ); IPreferenceStore store = CDebugUIPlugin.getDefault().getPreferenceStore(); setPreferenceStore( store ); setDescription( Messages.ReverseDebugPreferencePage_1 ); }
Source:
<code>public static String getLocalPackageName(@NotNull String importPath) { <START> return makePackageNameValid(PathUtil.getFileName(importPath)); <END> }</code><technical_language>inline method</technical_language>

Target:
public static String getLocalPackageName(@NotNull String importPath) { final String illegalChars = "[-!\"#$%&'()*,:;<=>?[\\]^{|}\uFFFD]"; StringBuilder name = new StringBuilder(PathUtil.getFileName(importPath)); for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); if (Character.isWhitespace(ch) || illegalChars.indexOf(ch) != -1) { name.setCharAt(i, '_'); } } return name.toString(); }
Source:
<code>public void visitFunctionDeclaration(FunctionDeclarationTree tree) { super.visitFunctionDeclaration(tree); <START> checkFunction(tree); <END> }</code><technical_language>@ivandalbosco need change order if rely visitor for finding "try"</technical_language>

Target:
public void visitFunctionDeclaration(FunctionDeclarationTree tree) { checkFunction(tree); super.visitFunctionDeclaration(tree); }
Source:
<code>private TransactionManager getTransactionManager() { try { return com.arjuna.ats.jta.TransactionManager.transactionManager(new InitialContext()); } catch (NamingException ne) { <START> throw new IllegalStateException("Not possible to find transaction manager"); <END> } }</code><technical_language>exception added new exception throw. message reason failed (ie ne.getMessage())</technical_language>

Target:
private TransactionManager getTransactionManager() { try { return com.arjuna.ats.jta.TransactionManager.transactionManager(new InitialContext()); } catch (NamingException ne) { throw new IllegalStateException("Not possible to find transaction manager, " + "failed to initialize intial context. Cause: " + ne.getMessage(), ne); } }
Source:
<code>public ValidationResult validate(Object value) { assert value == null || value instanceof String : "This validation must be run on a String!"; String mask = (String) value; boolean isValidFormat = isPrefixSupported ? MaskValidator.getInstance().isMaskFormatValid(mask) : MaskValidator.getInstance() .isMaskValidFormatPrefixFree(mask); <START> boolean isValidValue = <END> isPrefixSupported ? MaskValidator.getInstance().isMaskValid(mask) : MaskValidator.getInstance() .isMaskValidPrefixFree(mask); if (!isValidFormat) { return failWith(getSubnetBadFormatMessage()); } else if (!isValidValue) { return failWith(getInvalidNetmaskMessage()); } return new ValidationResult(); }</code><technical_language>call this in case format is valid. drop format validation in validation. Moreover, need call this if format is a valid netmask, if a valid prefix</technical_language>

Target:
public ValidationResult validate(Object value) { assert value == null || value instanceof String : "This validation must be run on a String!"; String mask = (String) value; boolean isValidFormat = isPrefixSupported ? MaskValidator.getInstance().isMaskFormatValid(mask) : MaskValidator.getInstance() .isNetmaskFormatValid(mask); boolean isValidValue = isValidFormat ? (isPrefixSupported ? MaskValidator.getInstance().isMaskValid(mask) : MaskValidator.getInstance() .isNetmaskValid(mask)) : false; if (!isValidFormat) { return failWith(getSubnetBadFormatMessage()); } else if (!isValidValue) { return failWith(getInvalidNetmaskMessage()); } return new ValidationResult(); }
Source:
<code><START> public void setWriteBufferSize(int bufferSize) { <END> this.writeBufferSize = bufferSize; }</code><technical_language>public</technical_language>

Target:
void setWriteBufferSize(int bufferSize) { this.writeBufferSize = bufferSize; }
Source:
<code>protected void parse() throws ProtocolException { boolean witSupported = (protocolVersion >= NetworkParameters.ProtocolVersion.WITNESS_VERSION.getBitcoinProtocolVersion()) && (transactionOptions & TransactionOptions.WITNESS) != 0; cursor = offset; version = readUint32(); optimalEncodingMessageSize = 4; readInputs(); byte flags = 0; <START> if(inputs.size() == 0 && witSupported) { <END> flags = readBytes(1)[0]; optimalEncodingMessageSize += 1; if(flags != 0) { readInputs(); readOutputs(); } else { outputs = new ArrayList<TransactionOutput>(0); } } else { readOutputs(); } if(((flags & 1) != 0) && witSupported) { flags ^= 1; readWitness(); } if(flags != 0) { throw new ProtocolException("Unknown transaction optional data"); } lockTime = readUint32(); optimalEncodingMessageSize += 4; length = cursor - offset; }</code><technical_language>space '('</technical_language>

Target:
protected void parse() throws ProtocolException { boolean witSupported = (protocolVersion >= NetworkParameters.ProtocolVersion.WITNESS_VERSION.getBitcoinProtocolVersion()) && (transactionOptions & TransactionOptions.WITNESS) != 0; cursor = offset; version = readUint32(); optimalEncodingMessageSize = 4; readInputs(); byte flags = 0; if (inputs.size() == 0 && witSupported) { flags = readBytes(1)[0]; optimalEncodingMessageSize += 1; if (flags != 0) { readInputs(); readOutputs(); } else { outputs = new ArrayList<TransactionOutput>(0); } } else { readOutputs(); } if (((flags & 1) != 0) && witSupported) { flags ^= 1; readWitness(); } if (flags != 0) { throw new ProtocolException("Unknown transaction optional data"); } lockTime = readUint32(); optimalEncodingMessageSize += 4; length = cursor - offset; witnesses = witnesses == null ? new ArrayList<TransactionWitness>() : witnesses; }
Source:
<code>public List<ChePlugin> execute() throws InfrastructureException { Span tracingSpan = startTracingPhase(); BrokerStatusListener brokerStatusListener = new BrokerStatusListener(workspaceId, pluginsValidator, brokersResult); try { LOG.debug("Subscribing broker events listener for workspace '{}'", workspaceId); eventService.subscribe(brokerStatusListener, BrokerEvent.class); <START> finishSpanIfExists(tracingSpan); <END> return nextPhase.execute(); } finally { eventService.unsubscribe(brokerStatusListener); } }</code><technical_language>Subscribing is listening is not. actual listening is traced here. remove this tracing</technical_language>

Target:
public List<ChePlugin> execute() throws InfrastructureException { BrokerStatusListener brokerStatusListener = new BrokerStatusListener(workspaceId, pluginsValidator, brokersResult); try { LOG.debug("Subscribing broker events listener for workspace '{}'", workspaceId); eventService.subscribe(brokerStatusListener, BrokerEvent.class); return nextPhase.execute(); } finally { eventService.unsubscribe(brokerStatusListener); } }
Source:
<code>protected void checkNotInEventLoop() { if (!CHECK_IO_DEADLOCKS) return; for (EventExecutor executor : cluster.manager.connectionFactory.eventLoopGroup) { if (executor.inEventLoop()) { <START> throw new IllegalStateException( <END> "Detected a synchronous Session call (execute() or prepare()) on an I/O thread, " + "this is a bug and can cause deadlocks or unpredictable behavior. " + "Make sure your Future callbacks only use async calls, or schedule them on a " + "different executor."); } } }</code><technical_language>supposed log a warning first, turn exception next major release? turn system property stg IO_DEADLOCK_CHECK_MODE values NONE, WARN, FAIL</technical_language>

Target:
protected void checkNotInEventLoop() { if (!CHECK_IO_DEADLOCKS) return; for (EventExecutor executor : cluster.manager.connectionFactory.eventLoopGroup) { if (executor.inEventLoop()) { throw new IllegalStateException( "Detected a synchronous Session call (execute() or prepare()) on an I/O thread, " + "this can cause deadlocks or unpredictable behavior. " + "Make sure your Future callbacks only use async calls, or schedule them on a " + "different executor."); } } }
Source:
<code>private void assertKnownHostFileWritable() throws IOException { if( !knownHosts.canWrite() ) { throw new IOException( format( <START> "Failed to write certificates to file %s as you have no write permissions to it. " + <END> "Try configuring the Neo4j driver to use a file system location you do have write permissions to.", knownHosts.getAbsolutePath() ) ); } }</code><technical_language>appreciate if add a \n sentence in messages, for CertificateException</technical_language>

Target:
private void assertKnownHostFileWritable() throws IOException { if( !knownHosts.canWrite() ) { throw new IOException( format( "Failed to write certificates to file %s as you have no write permissions to it.\n" + "Try configuring the Neo4j driver to use a file system location you do have write permissions to.", knownHosts.getAbsolutePath() ) ); } }
Source:
<code>public void commit(WrappedTinkerGraph graph, InventoryBackend.Transaction t) { graph.commit(); <START> unlock(t); <END> }</code><technical_language>java try { graph.commit(); } finally { unlock(t); } .. if I start a transaction forget call commit/rollback (or I forgot place finally clause exception is thrown). get deadlock, right? some timeout logic is overkill for TinkerGraph, get for free Titan</technical_language>

Target:
public void commit(WrappedTinkerGraph graph, InventoryBackend.Transaction t) { try { graph.commit(); } finally { unlock(t); } }
Source:
<code>static Socket createSocketUtil(final String host, final int port, final String bindAddress, final int timeout) { Socket socket = null; <START> if (timeout == 0) { <END> try { socket = bindAddress == null ? new Socket(host, port) : new Socket(InetAddress.getByName(host), port, InetAddress.getByName(bindAddress), 0); return socket; } catch (Exception e) { String message = e.toString(); if (e instanceof Throwable) { throw new RuntimeCamelException(message, (Throwable)e); } throw new RuntimeCamelException(message); } } final Socket[] sockp = new Socket[1]; final Exception[] ee = new Exception[1]; String message = ""; Thread tmp = new Thread(new Runnable() { public void run() { sockp[0] = null; try { sockp[0] = bindAddress == null ? new Socket(host, port) : new Socket(InetAddress.getByName(host), port, InetAddress.getByName(bindAddress), 0); } catch (Exception e) { ee[0] = e; if (sockp[0] != null && sockp[0].isConnected()) { try { sockp[0].close(); } catch (Exception eee) { } } sockp[0] = null; } } }); tmp.setName("Opening Socket " + host); tmp.start(); try { tmp.join(timeout); message = "timeout: "; } catch (java.lang.InterruptedException eee) { } if (sockp[0] != null && sockp[0].isConnected()) { socket = sockp[0]; } else { message += "socket is not established"; if (ee[0] != null) { message = ee[0].toString(); } tmp.interrupt(); tmp = null; throw new RuntimeCamelException(message, ee[0]); } return socket; }</code><technical_language>do is good class method default access modifers</technical_language>

Target:
static Socket createSocketUtil(final String host, final int port, final String bindAddress, final int timeout) { Socket socket = null; if (timeout == 0) { try { socket = new Socket(InetAddress.getByName(host), port, InetAddress.getByName(bindAddress), 0); return socket; } catch (Exception e) { String message = e.toString(); if (e instanceof Throwable) { throw new RuntimeCamelException(message, (Throwable)e); } throw new RuntimeCamelException(message); } } final Socket[] sockp = new Socket[1]; final Exception[] ee = new Exception[1]; String message = ""; Thread tmp = new Thread(new Runnable() { public void run() { sockp[0] = null; try { sockp[0] = new Socket(InetAddress.getByName(host), port, InetAddress.getByName(bindAddress), 0); } catch (Exception e) { ee[0] = e; if (sockp[0] != null && sockp[0].isConnected()) { try { sockp[0].close(); } catch (Exception eee) { } } sockp[0] = null; } } }); tmp.setName("Opening Socket " + host); tmp.start(); try { tmp.join(timeout); message = "timeout: "; } catch (java.lang.InterruptedException eee) { } if (sockp[0] != null && sockp[0].isConnected()) { socket = sockp[0]; } else { message += "socket is not established"; if (ee[0] != null) { message = ee[0].toString(); } tmp.interrupt(); tmp = null; throw new RuntimeCamelException(message, ee[0]); } return socket; }
Source:
<code>public void ack(final long uso, boolean runEveryWhere) { if (m_runEveryWhere && !m_isMaster && runEveryWhere) { m_lastAckUSO = uso; m_replicaMastershipRequested = true; if (!m_replicaRunning) { m_isMaster = false; m_replicaRunning = acceptMastership(); if (m_replicaRunning) { exportLog.info("Export generation " + getGeneration() + " accepting mastership for " + getTableName() + " partition " + getPartitionId() + " as replica"); } } return; } RunnableWithES runnable = new RunnableWithES("ack") { @Override public void run() { try { if (!getLocalExecutorService().isShutdown() && !m_mastershipAccepted.get()) { ackImpl(uso); <START> } <END> } catch (Exception e) { exportLog.error("Error acking export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error acking export buffer", true, e); } } }; stashOrSubmitTask(runnable, true, false); }</code><technical_language>good me</technical_language>

Target:
public void ack(final long uso, boolean runEveryWhere) { if (m_runEveryWhere && !m_isMaster && runEveryWhere) { m_lastAckUSO = uso; m_replicaMastershipRequested = true; if (!m_replicaRunning) { m_isMaster = false; m_replicaRunning = acceptMastership(); if (m_replicaRunning) { exportLog.info("Export generation " + getGeneration() + " accepting mastership for " + getTableName() + " partition " + getPartitionId() + " as replica"); } } return; } exportLog.error("Ack every " + m_runEveryWhere + " isM " + m_isMaster + " accept " + m_mastershipAccepted.get() + " runeverywhere " + runEveryWhere); RunnableWithES runnable = new RunnableWithES("ack") { @Override public void run() { try { if (!getLocalExecutorService().isShutdown() && !m_mastershipAccepted.get()) { ackImpl(uso); } } catch (Exception e) { exportLog.error("Error acking export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error acking export buffer", true, e); } } }; stashOrSubmitTask(runnable, true, false); }
Source:
<code>public void sendResult(MutableObjectIterator<E> result) { <START> if (iteratorFuture.isDone()) { <END> throw new IllegalStateException("Result already done"); } iteratorFuture.complete(result); }</code><technical_language>I this changes in MergeIterator, SpillingThread, NormalizedKeySorter in a separate cleanup/refactoring commit</technical_language>

Target:
public void sendResult(MutableObjectIterator<E> result) { iteratorFuture.complete(result); }
Source:
<code>public void getApplicationByCandidateIdShouldReturnThreeElementListOfApplicationDTOWhenCandidateIdExists() { List<ApplicationEntity> applicationEntities = Arrays.asList(applicationEntity, applicationEntity, applicationEntity); List<CandidateApplicationDTO> candidateApplicationDTOs = Arrays.asList(dummyCandidateApplicationDTO, dummyCandidateApplicationDTO, <START> dummyCandidateApplicationDTO); <END> given(candidateRepository.findOne(CANDIDATE_ID)).willReturn(candidateEntity); given(applicationsRepository.findByCandidateEntity(candidateEntity, DEFAULT_PAGE_REQUEST)) .willReturn(new PageImpl<ApplicationEntity>(applicationEntities)); given(converterService.convert(applicationEntities, CandidateApplicationDTO.class)) .willReturn(candidateApplicationDTOs); PagingResponse<CandidateApplicationDTO> result = applicationsService .getApplicationsByCandidateId(CANDIDATE_ID, PAGE_NUMBER_ZERO, PAGE_SIZE_TEN); assertThat(result.getTotal(), is(3L)); assertThat(result.getRows(), equalTo(candidateApplicationDTOs)); }</code><technical_language>local variables final</technical_language>

Target:
public void getApplicationByCandidateIdShouldReturnThreeElementListOfApplicationDTOWhenCandidateIdExists() { final List<ApplicationEntity> applicationEntities = Arrays.asList(applicationEntity, applicationEntity, applicationEntity); final List<CandidateApplicationDTO> candidateApplicationDTOs = Arrays.asList(dummyCandidateApplicationDTO, dummyCandidateApplicationDTO, dummyCandidateApplicationDTO); given(candidateRepository.findOne(CANDIDATE_ID)).willReturn(candidateEntity); given(applicationsRepository.findByCandidateEntity(candidateEntity, DEFAULT_PAGE_REQUEST)) .willReturn(new PageImpl<ApplicationEntity>(applicationEntities)); given(converterService.convert(applicationEntities, CandidateApplicationDTO.class)) .willReturn(candidateApplicationDTOs); final PagingResponse<CandidateApplicationDTO> result = applicationsService .getApplicationsByCandidateId(CANDIDATE_ID, PAGE_NUMBER_ZERO, PAGE_SIZE_TEN); assertThat(result.getTotal(), is(3L)); assertThat(result.getRows(), equalTo(candidateApplicationDTOs)); }
Source:
<code><START> public ByteBuf resumeToken() { <END> return isResumeEnabled() ? SetupFrameFlyweight.resumeToken(setupFrame) : Unpooled.EMPTY_BUFFER; }</code><technical_language>this null instead? For metadata, null means present</technical_language>

Target:
public ByteBuf resumeToken() { return SetupFrameFlyweight.resumeToken(setupFrame); }
Source:
<code>public void setInternalJobState(int state) { try { final Field field = InternalJob.class.getDeclaredField("flags"); field.setAccessible(true); field.set(this, new Integer(state)); } catch (Exception e) { <START> e.printStackTrace(); <END> throw new RuntimeException(e); } }</code><technical_language>Debugging leftover</technical_language>

Target:
public void setInternalJobState(int state) { try { final Field field = InternalJob.class.getDeclaredField("flags"); field.setAccessible(true); field.set(this, new Integer(state)); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>private CompletableFuture<JobResult> submitJobAndWaitUntilRunning(JobGraph jobGraph) throws Exception { miniCluster.submitJob(jobGraph).get(); <START> CommonTestUtils.waitUntilJobManagerIsInitialized(() -> miniCluster.getJobStatus(jobGraph.getJobID()).get()); <END> final CompletableFuture<JobResult> jobResultFuture = miniCluster.requestJobResult(jobGraph.getJobID()); assertThat(jobResultFuture.isDone(), is(false)); CommonTestUtils.waitUntilCondition( jobIsRunning(() -> miniCluster.getExecutionGraph(jobGraph.getJobID())), Deadline.fromNow(TESTING_TIMEOUT), 50L); return jobResultFuture; }</code><technical_language>is this needed here</technical_language>

Target:
private CompletableFuture<JobResult> submitJobAndWaitUntilRunning(JobGraph jobGraph) throws Exception { miniCluster.submitJob(jobGraph).get(); final CompletableFuture<JobResult> jobResultFuture = miniCluster.requestJobResult(jobGraph.getJobID()); assertThat(jobResultFuture.isDone(), is(false)); CommonTestUtils.waitUntilCondition( jobIsRunning(() -> miniCluster.getExecutionGraph(jobGraph.getJobID())), Deadline.fromNow(TESTING_TIMEOUT), 50L); return jobResultFuture; }
Source:
<code>public void run() { log.info("Starting writer"); try { writerRegistry.register(this); running = true; while (!isCanceled()) { if (Thread.interrupted()) { throw new InterruptedException(); } <START> Collection<Metric> metrics = metricsQueue.poll(batchSize); <END> if (metrics.isEmpty() && lastWorkTime > 0 && maxIdleTime > 0 && System.currentTimeMillis() > lastWorkTime + maxIdleTime) { log.info("Shutting down writer due to dearth of work"); break; } if (metrics.isEmpty()) { log.debug("No work to do, so checking again."); continue; } OpenTsdbClient client = null; try { long processed = 0; client = clientPool.borrowObject(); int errs = clientPool.clearErrorCount(); if (errs > 0) { metricsQueue.incrementError(errs); } for (Metric m : metrics) { String message = convert(m); client.put(message); processed++; } metricsQueue.incrementProcessed(processed); client.flush(); } catch (Exception e) { log.warn("Caught unexpected exception processing messages", e); metricsQueue.addAll(metrics, true); if (client != null) { client.close(); } } finally { if (client != null) { try { clientPool.returnObject(client); } catch(Exception returnException) { log.warn("Failed to return TSDB client to connection pool", returnException); } } client = null; lastWorkTime = System.currentTimeMillis(); } } } catch(InterruptedException ie) { log.info("Exiting due to thread interrupt"); Thread.currentThread().interrupt(); } finally { running = false; writerRegistry.unregister(this); } }</code><technical_language>metricsQueue reference is interface</technical_language>

Target:
public void run() { log.info("Starting writer"); try { writerRegistry.register(this); running = true; runUntilCanceled(); } catch(InterruptedException ie) { log.info("Exiting due to thread interrupt"); Thread.currentThread().interrupt(); } finally { running = false; writerRegistry.unregister(this); } }
Source:
<code>public ChannelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { <START> LayoutInflater inflater = LayoutInflater.from(parent.getContext()); <END> return new ChannelViewHolder((ChannelView) inflater.inflate(R.layout.channel_item_layout, parent, false)); }</code><technical_language>pass layout inflater a param adapter</technical_language>

Target:
public ChannelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ChannelViewHolder((ChannelView) inflater.inflate(R.layout.channel_item_layout, parent, false)); }
Source:
<code>public final static AttachmentSizeFormatter getInstance() { try { <START> return new AttachmentSizeFormatter(); <END> } catch (ClassCastException e) { return new AttachmentSizeFormatter(Locale.ENGLISH); } }</code><technical_language>Locale.English? Based formats give effect other locales have</technical_language>

Target:
public final static AttachmentSizeFormatter getInstance() { return new AttachmentSizeFormatter(); }
Source:
<code>private byte[] getRemoteDeviceData(XBeeAPIPacket packet) { byte[] data = null; logger.trace("{}Received packet: {}.", toString(), packet); APIFrameType frameType = packet.getFrameType(); switch (frameType) { case AT_COMMAND_RESPONSE: ATCommandResponsePacket atResponse = (ATCommandResponsePacket)packet; if (atResponse.getFrameID() != frameID) return null; if (!atResponse.getCommand().equals(ND_COMMAND)) return null; if (atResponse.getCommandValue() == null || atResponse.getCommandValue().length == 0) { running = atResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received self reponse: {}.", toString(), packet); data = atResponse.getCommandValue(); break; <START> case REMOTE_AT_COMMAND_RESPONSE: <END> RemoteATCommandResponsePacket remoteAtResponse = (RemoteATCommandResponsePacket)packet; if (remoteAtResponse.getFrameID() != frameID) return null; if (!remoteAtResponse.getCommand().equals(ND_COMMAND)) return null; if (remoteAtResponse.getCommandValue() == null || remoteAtResponse.getCommandValue().length == 0) { running = remoteAtResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received remote reponse: {}.", toString(), packet); data = remoteAtResponse.getCommandValue(); break; default: break; } return data; }</code><technical_language>allowing for device discovery in remote devices? If this removed</technical_language>

Target:
private byte[] getRemoteDeviceData(XBeeAPIPacket packet) { byte[] data = null; logger.trace("{}Received packet: {}.", toString(), packet); APIFrameType frameType = packet.getFrameType(); switch (frameType) { case AT_COMMAND_RESPONSE: ATCommandResponsePacket atResponse = (ATCommandResponsePacket)packet; if (atResponse.getFrameID() != frameID) return null; if (!atResponse.getCommand().equals(ND_COMMAND)) return null; if (atResponse.getCommandValue() == null || atResponse.getCommandValue().length == 0) { running = atResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received self reponse: {}.", toString(), packet); data = atResponse.getCommandValue(); break; default: break; } return data; }
Source:
<code>private void persistGrillServiceState() throws IOException { <START> if (isRestartEnabled()) { <END> FileSystem fs = persistDir.getFileSystem(conf); LOG.info("Persisting server state in " + persistDir); for (GrillService service : grillServices) { LOG.info("Persisting state of service:" + service.getName()); Path serviceWritePath = new Path(persistDir, service.getName() + ".out"); ObjectOutputStream out = null; try { out = new ObjectOutputStream(fs.create(serviceWritePath)); service.writeExternal(out); } finally { if (out != null) { out.close(); } } Path servicePath = getServicePersistPath(service); fs.rename(serviceWritePath, servicePath); LOG.info("Persisted service " + service.getName() + " to " + servicePath); } } else { LOG.info("Server restart is not enabled. Not persisting the server state"); } }</code><technical_language>is configuration for persist recover. This change is combining both. Needs revert</technical_language>

Target:
private void persistGrillServiceState() throws IOException { if (conf.getBoolean(GrillConfConstants.GRILL_SERVER_RESTART_ENABLED, GrillConfConstants.DEFAULT_GRILL_SERVER_RESTART_ENABLED)) { FileSystem fs = persistDir.getFileSystem(conf); LOG.info("Persisting server state in " + persistDir); for (GrillService service : grillServices) { LOG.info("Persisting state of service:" + service.getName()); Path serviceWritePath = new Path(persistDir, service.getName() + ".out"); ObjectOutputStream out = null; try { out = new ObjectOutputStream(fs.create(serviceWritePath)); service.writeExternal(out); } finally { if (out != null) { out.close(); } } Path servicePath = getServicePersistPath(service); fs.rename(serviceWritePath, servicePath); LOG.info("Persisted service " + service.getName() + " to " + servicePath); } } else { LOG.info("Server restart is not enabled. Not persisting the server state"); } }
Source:
<code>void defaultChromeOptions() { Capabilities chromeOptions = factory.createCapabilities(config, browser, proxy, browserDownloadsFolder); Map<String, Object> prefsMap = getBrowserLaunchPrefs(ChromeOptions.CAPABILITY, chromeOptions); <START> assertThat(prefsMap).hasSizeGreaterThan(0); <END> assertThat(prefsMap).containsEntry("download.default_directory", new File(DOWNLOADS_FOLDER).getAbsolutePath()); }</code><technical_language>I a good change. name of test is defaultChromeOptions(), intent is test default options</technical_language>

Target:
void defaultChromeOptions() { Capabilities chromeOptions = factory.createCapabilities(config, browser, proxy, browserDownloadsFolder); Map<String, Object> prefsMap = getBrowserLaunchPrefs(ChromeOptions.CAPABILITY, chromeOptions); assertThat(prefsMap).hasSizeGreaterThanOrEqualTo(4); assertThat(prefsMap).containsEntry("credentials_enable_service", false); assertThat(prefsMap).containsEntry("plugins.always_open_pdf_externally", true); assertThat(prefsMap).containsEntry("profile.default_content_setting_values.automatic_downloads", 1); assertThat(prefsMap).containsEntry("download.default_directory", new File(DOWNLOADS_FOLDER).getAbsolutePath()); }
Source:
<code>public DefaultByteBufHolder(ByteBuf data) { ObjectUtil.checkNotNull(data, "data"); <START> this.data = data; <END> }</code><technical_language>nit: merge lines checkNotNull return argument</technical_language>

Target:
public DefaultByteBufHolder(ByteBuf data) { this.data = ObjectUtil.checkNotNull(data, "data"); }
Source:
<code>public void cleanupExistingArchivableStuff() { assertTimeoutPreemptively(ofSeconds(ARCHIVE_TIMEOUT), () -> <START> archiveService.archiveWorkflows(DateTime.now(), 10)); <END> }</code><technical_language>static import</technical_language>

Target:
public void cleanupExistingArchivableStuff() { assertTimeoutPreemptively(ARCHIVE_TIMEOUT, () -> archiveService.archiveWorkflows(now(), 10)); }
Source:
<code>public void testIndexSegmentation() throws Exception { IgniteCache<Object, Object> c1 = ignite(0).cache("org"); IgniteCache<Object, Object> c2 = ignite(0).cache("pers"); c1.put(1, new Organization("o1")); c1.put(2, new Organization("o2")); c2.put(1, new Person2(1, "o1")); c2.put(2, new Person2(2, "o2")); c2.put(3, new Person2(3, "o3")); String select0 = "select o.name n1, p.name n2 from \"pers\".Person2 p join \"org\".Organization o on p.name = o.name"; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { qryParallelism = 2; Ignite client = startGrid(4); <START> assertEquals(2, client.cache("pers").query(new SqlFieldsQuery(select0)).getAll().size()); <END> qryParallelism = 6; assertEquals(2, client.cache("pers").query(new SqlFieldsQuery(select0)).getAll().size()); return null; } }, IgniteCheckedException .class, "Query parallelism mismatch"); }</code><technical_language>Do need lines expected startGrid() fails</technical_language>

Target:
public void testIndexSegmentation() throws Exception { IgniteCache<Object, Object> c1 = ignite(0).cache("org"); IgniteCache<Object, Object> c2 = ignite(0).cache("pers"); c1.put(1, new Organization("o1")); c1.put(2, new Organization("o2")); c2.put(1, new Person2(1, "o1")); c2.put(2, new Person2(2, "o2")); c2.put(3, new Person2(3, "o3")); String select0 = "select o.name n1, p.name n2 from \"pers\".Person2 p join \"org\".Organization o on p.name = o.name"; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { qryParallelism = 2; Ignite client = startGrid(4); return null; } }, IgniteCheckedException .class, "Query parallelism mismatch"); }
Source:
<code>public void onDisconnect() { <START> logger.info("Disconnected from my.openHAB service"); <END> mIsConnected = false; }</code><technical_language>"pimp" log statement some more details (e.g. url, uuid)</technical_language>

Target:
public void onDisconnect() { logger.info("Disconnected from my.openHAB service (UUID = {}, base URL = {})", this.mUUID, this.mOHBaseUrl); mIsConnected = false; }
Source:
<code>public void enterVariableDeclaration(SwiftParser.VariableDeclarationContext ctx) { ParseTreeWalker walker = new ParseTreeWalker(); <START> if (ctx == null || ctx.patternInitializerList() == null) { <END> return; } for (SwiftParser.PatternInitializerContext context : ctx.patternInitializerList().patternInitializer()) { SwiftParser.PatternContext pattern = context.pattern(); listenerHelper.evaluatePattern(pattern, walker, new VariableDecListener(this.printer)); } }</code><technical_language>for ctx null is it? checking ctx.patternInitializerList() is null done line 175 well</technical_language>

Target:
public void enterVariableDeclaration(SwiftParser.VariableDeclarationContext ctx) { ParseTreeWalker walker = new ParseTreeWalker(); if (ctx.patternInitializerList() == null) { return; } for (SwiftParser.PatternInitializerContext context : ctx.patternInitializerList().patternInitializer()) { SwiftParser.PatternContext pattern = context.pattern(); listenerHelper.evaluatePattern(pattern, walker, new VariableDecListener(this.printer)); } }
Source:
<code>public void apply(OnlineCommandContext ctx) throws Exception { Operations ops = new Operations(ctx.client); if (socketBindingGroup == null) { socketBindingGroup = ctx.client.options().isDomain ? "full-sockets" : "standard-sockets"; } Address socketBindingAddress = Address.of("socket-binding-group", socketBindingGroup) .and("socket-binding", socketBindingName); <START> ops.removeIfExists(socketBindingAddress); <END> }</code><technical_language>this. existing Remove* commands in Creaper do ops.remove, letting command fail if resource exist. Do specific reason for ops.removeIfExists</technical_language>

Target:
public void apply(OnlineCommandContext ctx) throws Exception { Operations ops = new Operations(ctx.client); String bindingGroup = this.socketBindingGroup; if (bindingGroup == null) { bindingGroup = ctx.client.options().isDomain ? "full-sockets" : "standard-sockets"; } Address socketBindingAddress = Address.of("socket-binding-group", bindingGroup) .and("socket-binding", socketBindingName); ops.remove(socketBindingAddress); }
Source:
<code>public void testSizeCallbackIsNotCalledPreDrawIfNoDimensSetOnPreDraw() { SizeReadyCallback cb = mock(SizeReadyCallback.class); target.getSize(cb); PreDrawShadowViewTreeObserver shadowObserver = Robolectric.shadowOf_(view.getViewTreeObserver()); shadowObserver.fireOnPreDrawListeners(); verify(cb, never()).onSizeReady(anyInt(), anyInt()); <START> assertEquals(1, shadowObserver.getPreDrawListeners().size()); <END> }</code><technical_language>Another nit: assertThat(shadowObserver.getPreDrawListeners(), hasSIze(1)). <LINK_0> I it, a bunch of places assertTrue assertFalse hamcrest alternatives available. Assuming case, feel obligated fix of now</technical_language>

Target:
public void testSizeCallbackIsNotCalledPreDrawIfNoDimensSetOnPreDraw() { SizeReadyCallback cb = mock(SizeReadyCallback.class); target.getSize(cb); PreDrawShadowViewTreeObserver shadowObserver = Robolectric.shadowOf_(view.getViewTreeObserver()); shadowObserver.fireOnPreDrawListeners(); verify(cb, never()).onSizeReady(anyInt(), anyInt()); assertThat(shadowObserver.getPreDrawListeners(), hasSize(1)); }
Source:
<code>public LogReplicationEntry receive(LogReplicationEntry message) { rxMessageCounter++; rxMessageCount.setValue(rxMessageCounter); log.debug("Sink manager received while in {}", message.getMetadata().getMessageMetadataType(), rxState); if (message.getMetadata().getTopologyConfigId() != siteConfigID) { <START> log.trace("Sink manage with config id ignored msg id {}", siteConfigID, <END> message.getMetadata().getTopologyConfigId()); return null; } if (message.getMetadata().getMessageMetadataType().equals(MessageType.SNAPSHOT_START)) { processSnapshotStart(message); return null; } if (!receivedValidMessage(message)) { END ACK message and END message again, but the receiver has already transited to if (message.getMetadata().getMessageMetadataType() == SNAPSHOT_END) { LogReplicationEntryMetadata metadata = snapshotSinkBufferManager.makeAckMessage(message); if (metadata.getMessageMetadataType() == SNAPSHOT_END) { log.warn("Sink Manager in state and received message {}. Resending the ACK for SNAPSHOT_END.", rxState, message.getMetadata()); return new LogReplicationEntry(metadata, new byte[0]); } } log.warn("Sink Manager in state and received message {}. Dropping Message.", rxState, message.getMetadata()); return null; } if (rxState.equals(RxState.LOG_ENTRY_SYNC)) { return logEntrySinkBufferManager.processMsgAndBuffer(message); } else { return snapshotSinkBufferManager.processMsgAndBuffer(message); } }</code><technical_language>typo -> manage -> manager</technical_language>

Target:
public LogReplicationEntry receive(LogReplicationEntry message) { rxMessageCounter++; rxMessageCount.setValue(rxMessageCounter); log.debug("Sink manager received while in {}", message.getMetadata().getMessageMetadataType(), rxState); if (message.getMetadata().getTopologyConfigId() != topologyConfigId) { log.trace("Sink manager with config id ignored msg id {}", topologyConfigId, message.getMetadata().getTopologyConfigId()); return null; } if (message.getMetadata().getMessageMetadataType().equals(MessageType.SNAPSHOT_START)) { processSnapshotStart(message); return null; } if (!receivedValidMessage(message)) { END ACK message and END message again, but the receiver has already transited to if (message.getMetadata().getMessageMetadataType() == SNAPSHOT_END) { LogReplicationEntryMetadata metadata = snapshotSinkBufferManager.makeAckMessage(message); if (metadata.getMessageMetadataType() == SNAPSHOT_END) { log.warn("Sink Manager in state and received message {}. Resending the ACK for SNAPSHOT_END.", rxState, message.getMetadata()); return new LogReplicationEntry(metadata, new byte[0]); } } log.warn("Sink Manager in state and received message {}. Dropping Message.", rxState, message.getMetadata()); return null; } if (rxState.equals(RxState.LOG_ENTRY_SYNC)) { return logEntrySinkBufferManager.processMsgAndBuffer(message); } else { return snapshotSinkBufferManager.processMsgAndBuffer(message); } }
Source:
<code>public RewrittenAggregateProjections(boolean isValueAggregateQuery, Document document) { if (document == null) { throw new IllegalArgumentException("document cannot be null"); <START> } <END> if (isValueAggregateQuery) { this.payload = new Document(document.getPropertyBag()); } else { if (document.get("payload") instanceof ObjectNode) { this.payload = new Document((ObjectNode) document.get("payload")); } } }</code><technical_language>nit: space if</technical_language>

Target:
public RewrittenAggregateProjections(boolean isValueAggregateQuery, Document document) { if (document == null) { throw new IllegalArgumentException("document cannot be null"); } if (isValueAggregateQuery) { this.payload = new Document(document.getPropertyBag()); } else { if (!document.has(PAYLOAD_PROPERTY_NAME)) { throw new IllegalStateException("Underlying object does not have an 'payload' field."); } if (document.get(PAYLOAD_PROPERTY_NAME) instanceof ObjectNode) { this.payload = new Document((ObjectNode) document.get(PAYLOAD_PROPERTY_NAME)); } } }