auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void preprocess(Container container) { try { ClassLoader parentCl = container.getParentClassLoader(); File homeDir = resolveHomeDirectory(); File bundles = new File(homeDir, "bundles"); File lib = new File(homeDir, "lib"); File deployerJar = FrameworkBootstrap.findFileStartingWidth(bundles, "nuxeo-runtime-deploy"); File commonJar = FrameworkBootstrap.findFileStartingWidth(bundles, "nuxeo-common"); if (deployerJar == null || commonJar == null) { System.out.println("Deployer and/or common JAR (nuxeo-runtime-deploy* | nuxeo-common*) not found in " + bundles); return; } <START> ArrayList<URL> urls = new ArrayList<URL>(); <END> File[] files = lib.listFiles(); if (files != null) { for (File f : files) { if (f.getPath().endsWith(".jar")) { urls.add(f.toURI().toURL()); } } } files = bundles.listFiles(); if (files != null) { for (File f : files) { if (f.getPath().endsWith(".jar")) { urls.add(f.toURI().toURL()); } } } urls.add(homeDir.toURI().toURL()); urls.add(new File(homeDir, "config").toURI().toURL()); try (URLClassLoader cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), parentCl)) { System.out.println("# Running Nuxeo Preprocessor ..."); Class<?> klass = cl.loadClass("org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor"); Method main = klass.getMethod("main", String[].class); main.invoke(null, new Object[] { new String[] { homeDir.getAbsolutePath() } }); System.out.println("# Preprocessing done."); } } catch (IOException | ReflectiveOperationException e) { throw new RuntimeException("Failed to handle event", e); } }</code><technical_language>replace type List</technical_language>

Target:
protected void preprocess(Container container) { try { ClassLoader parentCl = container.getParentClassLoader(); File homeDir = resolveHomeDirectory(); File bundles = new File(homeDir, "bundles"); File lib = new File(homeDir, "lib"); File deployerJar = FrameworkBootstrap.findFileStartingWidth(bundles, "nuxeo-runtime-deploy"); File commonJar = FrameworkBootstrap.findFileStartingWidth(bundles, "nuxeo-common"); if (deployerJar == null || commonJar == null) { System.out.println("Deployer and/or common JAR (nuxeo-runtime-deploy* | nuxeo-common*) not found in " + bundles); return; } List<URL> urls = new ArrayList<>(); try (Stream<Path> p1 = Files.list(lib.toPath()); Stream<Path> p2 = Files.list(bundles.toPath())) { Stream.concat(p1, p2).filter(p -> p.endsWith(".jar")).map(this::toURL).forEach(urls::add); } urls.add(homeDir.toURI().toURL()); urls.add(new File(homeDir, "config").toURI().toURL()); try (URLClassLoader cl = new URLClassLoader(urls.toArray(new URL[0]), parentCl)) { System.out.println("# Running Nuxeo Preprocessor ..."); Class<?> klass = cl.loadClass("org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor"); Method main = klass.getMethod("main", String[].class); main.invoke(null, new Object[] { new String[] { homeDir.getAbsolutePath() } }); System.out.println("# Preprocessing done."); } } catch (IOException | ReflectiveOperationException | IllegalStateException e) { throw new RuntimeException("Failed to handle event", e); } }
Source:
<code>public void onResponse(Map<String, Object> response) { try { infoReturn = new VDSInfoReturn(response); proceedProxyReturnValue(); <START> vdsBrokerObjectsBuilder.updateVDSStatisticsData(getVds(), infoReturn.info); <END> vdsBrokerObjectsBuilder.checkTimeDrift(getVds(), infoReturn.info); getParameters().getCallback().onResponse(Collections.singletonMap("result", getVDSReturnValue())); } catch (Exception ex) { getParameters().getCallback().onFailure(ex); } }</code><technical_language>more here, this is async command</technical_language>

Target:
public void onResponse(Map<String, Object> response) { try { infoReturn = new VDSInfoReturn(response); proceedProxyReturnValue(); vdsBrokerObjectsBuilder.updateVDSStatisticsData(getVds(), infoReturn.info); vdsBrokerObjectsBuilder.checkTimeDrift(getVds(), infoReturn.info); multipathHealthHandler.handleMultipathHealthReport(getVds(), infoReturn.info); getParameters().getCallback().onResponse(Collections.singletonMap("result", getVDSReturnValue())); } catch (Exception ex) { getParameters().getCallback().onFailure(ex); } }
Source:
<code>public void run() { while (true) { try { Status status = MongoDBRiverHelper.getRiverStatus(this.mongoDBRiver.esClient, this.definition.getRiverName()); if (status != this.context.getStatus()) { if (status == Status.RUNNING) { MongoDBRiver.logger.trace("About to start river: {}", this.definition.getRiverName()); <START> mongoDBRiver.internalStartRiver(); <END> } else if (status == Status.STOPPED) { MongoDBRiver.logger.info("About to stop river: {}", this.definition.getRiverName()); mongoDBRiver.internalStopRiver(); } } Thread.sleep(1000L); } catch (InterruptedException e) { MongoDBRiver.logger.debug("Status thread interrupted", e, (Object) null); Thread.currentThread().interrupt(); break; } } }</code><technical_language>this block StatusChecker stop river, right? need move out thread do in of earlier PRs</technical_language>

Target:
public void run() { while (true) { try { Status status = MongoDBRiverHelper.getRiverStatus(this.mongoDBRiver.esClient, this.definition.getRiverName()); if (status != this.context.getStatus()) { if (status == Status.RUNNING && this.context.getStatus() != Status.STARTING) { logger.trace("About to start river: {}", this.definition.getRiverName()); mongoDBRiver.internalStartRiver(); } else if (status == Status.STOPPED) { logger.info("About to stop river: {}", this.definition.getRiverName()); mongoDBRiver.internalStopRiver(); } } Thread.sleep(1000L); } catch (InterruptedException e) { logger.debug("Status thread interrupted", e, (Object) null); Thread.currentThread().interrupt(); break; } } }
Source:
<code>public String readableString() { StringBuilder poolsToStringBuilder = new StringBuilder(); <START> for (Map.Entry<ResourceType<?>, ResourcePool> poolEntry : pools.entrySet()) { <END> poolsToStringBuilder .append(poolEntry.getKey()) .append(": ") .append(poolEntry.getValue()) .append("\n "); } if(!pools.isEmpty()) { poolsToStringBuilder.delete(poolsToStringBuilder.length() -9, poolsToStringBuilder.length()); } return "pools : " + "\n " + poolsToStringBuilder.toString(); }</code><technical_language>I sort pools</technical_language>

Target:
public String readableString() { Map<ResourceType<?>, ResourcePool> sortedPools = new TreeMap<ResourceType<?>, ResourcePool>( new Comparator<ResourceType<?>>() { @Override public int compare(ResourceType<?> o1, ResourceType<?> o2) { return o2.getTierHeight() - o1.getTierHeight(); } } ); sortedPools.putAll(pools); StringBuilder poolsToStringBuilder = new StringBuilder(); for (Map.Entry<ResourceType<?>, ResourcePool> poolEntry : sortedPools.entrySet()) { poolsToStringBuilder .append(poolEntry.getKey()) .append(": ") .append("\n ") .append("size: ") .append(poolEntry.getValue() instanceof HumanReadable ? ((HumanReadable) poolEntry.getValue()).readableString() : poolEntry.getValue()) .append("\n ") .append("tierHeight: ") .append(poolEntry.getKey().getTierHeight()) .append("\n "); } if (poolsToStringBuilder.length() > 4) { poolsToStringBuilder.delete(poolsToStringBuilder.length() - 5, poolsToStringBuilder.length()); } return "pools: " + "\n " + poolsToStringBuilder.toString(); }
Source:
<code>public boolean hasOpenSession() { <START> boolean isOpen = fSessions.size() > 0; <END> if (isOpen) { for (Session session : fSessions) { isOpen &= session.isConnected(); } } if (!isOpen) { close(); } return isOpen; }</code><technical_language>rename variable "hasOpenSession"</technical_language>

Target:
public boolean hasOpenSession() { boolean hasOpenSession = fSessions.size() > 0; if (hasOpenSession) { for (Session session : fSessions) { hasOpenSession &= session.isConnected(); } } if (!hasOpenSession) { close(); } return hasOpenSession; }
Source:
<code>private PlanNodeStatsEstimate getGroupStats(GroupReference groupReference) { int group = groupReference.getGroupId(); <START> Memo memo = this.memo.orElseThrow(IllegalStateException::new); <END> Optional<PlanNodeStatsEstimate> stats = memo.getStats(group); if (stats.isPresent()) { return stats.get(); } PlanNodeStatsEstimate groupStats = statsCalculator.calculateStats(memo.getNode(group), this, lookup, session, types.get()); verify(!memo.getStats(group).isPresent(), "Group stats already set"); memo.storeStats(group, groupStats); return groupStats; }</code><technical_language>Please add a message</technical_language>

Target:
private PlanNodeStatsEstimate getGroupStats(GroupReference groupReference) { int group = groupReference.getGroupId(); Memo memo = this.memo.orElseThrow(() -> new IllegalStateException("CachingStatsProvider without memo cannot handle GroupReferences")); Optional<PlanNodeStatsEstimate> stats = memo.getStats(group); if (stats.isPresent()) { return stats.get(); } PlanNodeStatsEstimate groupStats = statsCalculator.calculateStats(memo.getNode(group), this, lookup, session, types.get()); verify(!memo.getStats(group).isPresent(), "Group stats already set"); memo.storeStats(group, groupStats); return groupStats; }
Source:
<code>public static Timestamp createExpiryTime(){ Calendar calender = Calendar.getInstance(); Timestamp currentTime = new java.sql.Timestamp(calender.getTime().getTime()); calender.setTime(currentTime); <START> Integer expiryTimeProperty = Integer.parseInt(PropertyUtil.get("oskari.email.link.expirytime")); <END> calender.add(Calendar.DAY_OF_MONTH, expiryTimeProperty); Timestamp expiryTime = new java.sql.Timestamp(calender.getTime().getTime()); return expiryTime; }</code><technical_language>int expireDays = PropertyUtil.getOptional("oskari.email.link.expirytime", 2) instead</technical_language>

Target:
public static Timestamp createExpiryTime(){ Calendar calender = Calendar.getInstance(); Timestamp currentTime = new java.sql.Timestamp(calender.getTime().getTime()); calender.setTime(currentTime); int expireDays = PropertyUtil.getOptional("oskari.email.link.expirytime", 2); calender.add(Calendar.DAY_OF_MONTH, expireDays); Timestamp expiryTime = new java.sql.Timestamp(calender.getTime().getTime()); return expiryTime; }
Source:
<code>public SharedZkClient(RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig, RealmAwareZkClient.RealmAwareZkClientConfig clientConfig, MetadataStoreRoutingData metadataStoreRoutingData) { if (connectionConfig == null) { throw new IllegalArgumentException("RealmAwareZkConnectionConfig cannot be null!"); } _zkRealmShardingKey = connectionConfig.getZkRealmShardingKey(); <START> String zkRealmAddress = null; zkRealmAddress = metadataStoreRoutingData.getMetadataStoreRealm(_zkRealmShardingKey); <END> HelixZkClient.ZkConnectionConfig zkConnectionConfig = new HelixZkClient.ZkConnectionConfig(zkRealmAddress) .setSessionTimeout(connectionConfig.getSessionTimeout()); HelixZkClient.ZkClientConfig zkClientConfig = new HelixZkClient.ZkClientConfig(); zkClientConfig.setZkSerializer(clientConfig.getZkSerializer()) .setConnectInitTimeout(clientConfig.getConnectInitTimeout()) .setOperationRetryTimeout(clientConfig.getOperationRetryTimeout()) .setMonitorInstanceName(clientConfig.getMonitorInstanceName()) .setMonitorKey(clientConfig.getMonitorKey()) .setMonitorType(clientConfig.getMonitorType()) .setMonitorRootPathOnly(clientConfig.isMonitorRootPathOnly()); _innerSharedZkClient = SharedZkClientFactory.getInstance() .buildZkClient(zkConnectionConfig, zkClientConfig); }</code><technical_language>assign declaring: line</technical_language>

Target:
public SharedZkClient(RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig, RealmAwareZkClient.RealmAwareZkClientConfig clientConfig, MetadataStoreRoutingData metadataStoreRoutingData) { if (connectionConfig == null) { throw new IllegalArgumentException("RealmAwareZkConnectionConfig cannot be null!"); } _zkRealmShardingKey = connectionConfig.getZkRealmShardingKey(); if (metadataStoreRoutingData == null) { throw new IllegalArgumentException("MetadataStoreRoutingData cannot be null!"); } _metadataStoreRoutingData = metadataStoreRoutingData; String zkRealmAddress = _metadataStoreRoutingData.getMetadataStoreRealm(_zkRealmShardingKey); if (zkRealmAddress == null || zkRealmAddress.isEmpty()) { throw new IllegalArgumentException( "ZK realm address for the given ZK realm sharding key is invalid! ZK realm address: " + zkRealmAddress + " ZK realm sharding key: " + _zkRealmShardingKey); } _zkRealmAddress = zkRealmAddress; HelixZkClient.ZkConnectionConfig zkConnectionConfig = new HelixZkClient.ZkConnectionConfig(zkRealmAddress) .setSessionTimeout(connectionConfig.getSessionTimeout()); HelixZkClient.ZkClientConfig zkClientConfig = new HelixZkClient.ZkClientConfig(); zkClientConfig.setZkSerializer(clientConfig.getZkSerializer()) .setConnectInitTimeout(clientConfig.getConnectInitTimeout()) .setOperationRetryTimeout(clientConfig.getOperationRetryTimeout()) .setMonitorInstanceName(clientConfig.getMonitorInstanceName()) .setMonitorKey(clientConfig.getMonitorKey()).setMonitorType(clientConfig.getMonitorType()) .setMonitorRootPathOnly(clientConfig.isMonitorRootPathOnly()); _innerSharedZkClient = SharedZkClientFactory.getInstance().buildZkClient(zkConnectionConfig, zkClientConfig); }
Source:
<code><START> public static boolean checkIfCrashRecoveryAndFinishActivity(final Activity context) { <END> if (isRecoveredFromCrash()) { CrashReporter.sendUnhandledCaughtException(); if (!(context instanceof MainMenuActivity)) { context.finish(); } else { sharedPreferences.edit().putBoolean(RECOVERED_FROM_CRASH, false).commit(); return true; } } return false; }</code><technical_language>remove static</technical_language>

Target:
private void checkIfCrashRecoveryAndFinishActivity(final Activity context) { if (isRecoveredFromCrash()) { CrashReporter.sendUnhandledCaughtException(); if (!(context instanceof MainMenuActivity)) { context.finish(); } else { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(RECOVERED_FROM_CRASH, false).commit(); } } }
Source:
<code>private XmlFile(XmlElement root, Map<String, XmlElement> refs) { this.root = ArgChecker.notNull(root, "root"); <START> this.refs = ImmutableMap.copyOf(ArgChecker.notNull(refs, "refs")); <END> }</code><technical_language>call notNull is redundant, ImmutableMap.copyOf blow if refs is null</technical_language>

Target:
private XmlFile(XmlElement root, Map<String, XmlElement> refs) { this.root = ArgChecker.notNull(root, "root"); this.refs = ImmutableMap.copyOf(refs); }
Source:
<code>public <T extends Collector> T register(CollectorRegistry registry) { if (registered.contains(registry)) { return (T) this; } else { registered.add(registry); return super.register(registry); <START> } <END> }</code><technical_language>thread-safe, of a wrapped ConcurrentHashMap. registered.contains() registered.add() collectively atomic</technical_language>

Target:
public <T extends Collector> T register(CollectorRegistry registry) { synchronized (registered) { if (registered.contains(registry)) { return (T) this; } else { registered.add(registry); return super.register(registry); } } }
Source:
<code>private void tryIntegerTypes(NumberSchema subject) { subject.validate(BigInteger.valueOf(123123123123123L)); subject.validate(BigDecimal.valueOf(123123123123123L)); subject.validate(new AtomicInteger(123)); <START> subject.validate(new AtomicLong(123L)); <END> }</code><technical_language>sense differentiate integral types (BigInteger, AtomicInteger AtomicLong), number types (BigDecimal). JSON schema "number" "integer" keywords, handles NumberSchema. BigDecimal is a number integer</technical_language>

Target:
private void tryIntegerTypes(NumberSchema subject) { subject.validate(BigInteger.valueOf(123123123123123L)); subject.validate(new AtomicInteger(123)); subject.validate(new AtomicLong(123L)); }
Source:
<code>private Task prepareCreateEncounterPostActionParameterTask() { TaskTriggerInformation triggerInformation = new TaskTriggerInformation("CREATE SettingsRecord", "data-services", MDS_CHANNEL_NAME, VERSION, TRIGGER_SUBJECT, TRIGGER_SUBJECT); <START> SortedSet<TaskConfigStep> taskConfigStepSortedSet = new TreeSet<>(); <END> TaskConfig taskConfig = new TaskConfig(); taskConfig.addAll(taskConfigStepSortedSet); ArrayList<TaskActionInformation> taskActions = new ArrayList(); taskActions.add(prepareCreateEncounterActionInformation()); taskActions.add(prepareCreatePatientForEncounterActionInformation("{{pa.0.uuid}}", "Jacob Lee")); Task task = new Task("OpenMRSEncounterPostActionParameterTestTask", triggerInformation, taskActions, taskConfig, true, true); getTaskService().save(task); return task; }</code><technical_language>do need this</technical_language>

Target:
private Task prepareCreateEncounterPostActionParameterTask() { TaskTriggerInformation triggerInformation = new TaskTriggerInformation("CREATE SettingsRecord", "data-services", MDS_CHANNEL_NAME, VERSION, TRIGGER_SUBJECT, TRIGGER_SUBJECT); ArrayList<TaskActionInformation> taskActions = new ArrayList(); taskActions.add(prepareCreateEncounterActionInformation()); taskActions.add(prepareCreatePatientActionInformation("{{pa.0.uuid}}", "Jacob Lee", false)); Task task = new Task("OpenMRSEncounterPostActionParameterTestTask", triggerInformation, taskActions, new TaskConfig(), true, true); getTaskService().save(task); return task; }
Source:
<code>public <START> SaveAllDirtyPartsAddon() <END> { saveJob = doCreateSaveJob(); runnable = new Runnable() { @Override public void run() { saveJob.schedule(); display.timerExec(WorkbenchPlugin.getDefault().getPreferenceStore() .getInt(IPreferenceConstants.SAVE_AUTOMATICALLY_INTERVAL) * 1000, this); } }; idleListener = new Listener() { @Override public void handleEvent(org.eclipse.swt.widgets.Event event) { if (display != null) { display.timerExec(WorkbenchPlugin.getDefault().getPreferenceStore() .getInt(IPreferenceConstants.SAVE_AUTOMATICALLY_INTERVAL) * 1000, runnable); } } }; }</code><technical_language>saveJob, runnable idleListener initialized in constructor while dirtyHandler is initialized a initial value? Please provide consistency</technical_language>

Target:
public SaveAllDirtyPartsAddon() { saveJob = new WorkbenchJob("Auto save parts") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { if (WorkbenchPlugin.getDefault().getPreferenceStore() .getBoolean(IPreferenceConstants.SAVE_AUTOMATICALLY)) { IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench != null) { IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); for (IWorkbenchWindow window : windows) { IWorkbenchPage p = window.getActivePage(); Display display = getWorkbenchDisplay(); if (p != null && !hasSubShellActive(display)) { p.saveAllEditors(false); } } } } return Status.OK_STATUS; } }; saveJobScheduler = new Runnable() { @Override public void run() { if (saveJob.getState() != Job.RUNNING) { saveJob.schedule(); } Display display = getWorkbenchDisplay(); if (display != null) { display.timerExec(WorkbenchPlugin.getDefault().getPreferenceStore() .getInt(IPreferenceConstants.SAVE_AUTOMATICALLY_INTERVAL) * 1000, this); } } }; idleListener = new Listener() { @Override public void handleEvent(org.eclipse.swt.widgets.Event event) { Display display = getWorkbenchDisplay(); if (display != null) { display.timerExec(WorkbenchPlugin.getDefault().getPreferenceStore() .getInt(IPreferenceConstants.SAVE_AUTOMATICALLY_INTERVAL) * 1000, saveJobScheduler); } } }; dirtyHandler = new EventHandler() { @Override public void handleEvent(Event event) { if (WorkbenchPlugin.getDefault().getPreferenceStore() .getBoolean(IPreferenceConstants.SAVE_AUTOMATICALLY)) { Object newValue = event.getProperty(UIEvents.EventTags.NEW_VALUE); if (!(newValue instanceof Boolean)) { return; } boolean dirty = (Boolean) newValue; if (!dirty) { return; } Display display = getWorkbenchDisplay(); display.addFilter(SWT.KeyUp, idleListener); display.addFilter(SWT.MouseUp, idleListener); } } }; }
Source:
<code>protected String buildItemKey(ConcurStandardAccountingExtractDetailLine saeLine) { String objectCodeForKey = saeLine.getJournalAccountCode(); if (Boolean.TRUE.equals(saeLine.getJournalAccountCodeOverridden())) { objectCodeForKey = buildFakeObjectCodeToLeaveDetailLineUnmerged(); } return new StringBuilder(INITIAL_BUILDER_SIZE) .append(makeEmptyIfBlank(saeLine.getChartOfAccountsCode())) <START> .append('|').append(makeEmptyIfBlank(saeLine.getAccountNumber())) <END> .append('|').append(StringUtils.defaultIfBlank(saeLine.getSubAccountNumber(), getDashSubAccountNumber())) .append('|').append(makeEmptyIfBlank(objectCodeForKey)) .append('|').append(StringUtils.defaultIfBlank(saeLine.getSubObjectCode(), getDashSubObjectCode())) .append('|').append(StringUtils.defaultIfBlank(saeLine.getProjectCode(), getDashProjectCode())) .append('|').append(makeEmptyIfBlank(saeLine.getOrgRefId())) .toString(); }</code><technical_language>a constant for pipe symbol</technical_language>

Target:
protected String buildItemKey(ConcurStandardAccountingExtractDetailLine saeLine) { String objectCodeForKey = saeLine.getJournalAccountCode(); if (Boolean.TRUE.equals(saeLine.getJournalAccountCodeOverridden())) { objectCodeForKey = buildFakeObjectCodeToLeaveDetailLineUnmerged(); } return new StringBuilder(INITIAL_BUILDER_SIZE) .append(makeEmptyIfBlank(saeLine.getChartOfAccountsCode())) .append(PIPE_CHAR).append(makeEmptyIfBlank(saeLine.getAccountNumber())) .append(PIPE_CHAR).append(StringUtils.defaultIfBlank(saeLine.getSubAccountNumber(), getDashSubAccountNumber())) .append(PIPE_CHAR).append(makeEmptyIfBlank(objectCodeForKey)) .append(PIPE_CHAR).append(StringUtils.defaultIfBlank(saeLine.getSubObjectCode(), getDashSubObjectCode())) .append(PIPE_CHAR).append(StringUtils.defaultIfBlank(saeLine.getProjectCode(), getDashProjectCode())) .append(PIPE_CHAR).append(makeEmptyIfBlank(saeLine.getOrgRefId())) .toString(); }
Source:
<code>private List<Change> submitWholeTopic(RevisionResource rsrc, IdentifiedUser caller, boolean force, String topic) throws ResourceConflictException, OrmException, IOException { Preconditions.checkNotNull(topic); final Timestamp timestamp = TimeUtil.nowTs(); ReviewDb db = dbProvider.get(); ChangeData cd = changeDataFactory.create(db, rsrc.getControl()); List<ChangeData> changesByTopic = queryProvider.get().byTopicOpen(topic); String problems = problemsForSubmittingChanges(changesByTopic, caller); if (problems != null) { throw new ResourceConflictException(problems); } Change change = rsrc.getChange(); ChangeUpdate update = updateFactory.create(rsrc.getControl(), timestamp); List<SubmitRecord> submitRecords = checkSubmitRule(cd, rsrc.getPatchSet(), force); update.submit(submitRecords); db.changes().beginTransaction(change.getId()); try { for (ChangeData c : changesByTopic) { RevisionResource <START> resource = <END> new RevisionResource(new ChangeResource( c.changeControl()), c.currentPatchSet()); BatchMetaDataUpdate batch = approve(resource, update, caller, timestamp); batch.write(update, new CommitBuilder()); submitToDatabase(db, c.getId(), timestamp); } db.commit(); } finally { db.rollback(); } List<Change.Id> ids = new ArrayList<>(changesByTopic.size()); List<Change> ret = new ArrayList<>(changesByTopic.size()); for (ChangeData c : changesByTopic) { ids.add(c.getId()); ret.add(c.change()); } indexer.indexAsync(ids).checkedGet(); return ret; }</code><technical_language>"resource" "rsrc" in scope, give this a name</technical_language>

Target:
private List<Change> submitWholeTopic(RevisionResource rsrc, IdentifiedUser caller, boolean force, String topic) throws ResourceConflictException, OrmException, IOException { Preconditions.checkNotNull(topic); final Timestamp timestamp = TimeUtil.nowTs(); ReviewDb db = dbProvider.get(); ChangeData cd = changeDataFactory.create(db, rsrc.getControl()); List<ChangeData> changesByTopic = queryProvider.get().byTopicOpen(topic); String problems = problemsForSubmittingChanges(changesByTopic, caller); if (problems != null) { throw new ResourceConflictException(problems); } Change change = rsrc.getChange(); ChangeUpdate update = updateFactory.create(rsrc.getControl(), timestamp); List<SubmitRecord> submitRecords = checkSubmitRule(cd, rsrc.getPatchSet(), force); update.submit(submitRecords); db.changes().beginTransaction(change.getId()); try { for (ChangeData c : changesByTopic) { BatchMetaDataUpdate batch = approve(c.currentPatchSet().getId(), c.changeControl(), update, caller, timestamp); batch.write(update, new CommitBuilder()); submitToDatabase(db, c.getId(), timestamp); } db.commit(); } finally { db.rollback(); } List<Change.Id> ids = new ArrayList<>(changesByTopic.size()); List<Change> ret = new ArrayList<>(changesByTopic.size()); for (ChangeData c : changesByTopic) { ids.add(c.getId()); ret.add(c.change()); } indexer.indexAsync(ids).checkedGet(); return ret; }
Source:
<code><START> public ServicePortAdapter(ServicePortAdapter port) { <END> this.name = port.getName(); this.port = port.getPort(); this.containerPort = "0".equals(port.getTargetPort()) ? String.valueOf(this.port) : port.getTargetPort(); this.protocol = port.getProtocol(); this.routePort = port.isRoutePort(); }</code><technical_language>java public ServicePortAdapter(ServicePortAdapter port) { this((IServicePort)port); this.routePort = port.isRoutePort(); } here. clear new constructor additionally</technical_language>

Target:
public ServicePortAdapter(ServicePortAdapter port) { this((IServicePort) port); this.routePort = port.isRoutePort(); }
Source:
<code><START> public synchronized boolean isOpen() { <END> return sub != null && conn.getState() == Constants.ConnState.CONNECTED; }</code><technical_language>drop synchronized this is brand new</technical_language>

Target:
public boolean isOpen() { return sub != null && conn.getState() == Constants.ConnState.CONNECTED; }
Source:
<code>private void attemptLogin() { unsubscribe(); authRepository.clearLoginCache(); subscribe(); <START> mEmailView.setError(null); <END> mPasswordView.setError(null); String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; if (TextUtils.isEmpty(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } if (TextUtils.isEmpty(email)) { mEmailView.setError(getString(R.string.error_field_required)); focusView = mEmailView; cancel = true; } else if (!isEmailValid(email)) { mEmailView.setError(getString(R.string.error_invalid_email)); focusView = mEmailView; cancel = true; } if (cancel) { focusView.requestFocus(); } else { hideKeyboard(); showProgress(true); isLoggingIn = true; authRepository.login(email, password); } }</code><technical_language>x: do setError()! [broken](<LINK_0> terrible</technical_language>

Target:
private void attemptLogin() { unsubscribe(); authRepository.clearLoginCache(); subscribe(); String email = emailView.getText().toString(); String password = passwordView.getText().toString(); View erroredView = validateLoginData(email, password); if (erroredView != null) { erroredView.requestFocus(); } else { hideKeyboard(); authRepository.login(email, password); } }
Source:
<code>public void testFetchWithRefInWantUnknownRef() throws Exception { thrown.expect(PackProtocolException.class); <START> thrown.expectMessage("Invalid ref name: refs/heads/branchC"); <END> PacketLineIn pckIn = buildPckIn(PacketLineIn.DELIM, "want e4980cdc48cfa1301493ca94eb70523f6788b819", "want-ref refs/heads/branchC", PacketLineIn.END); ProtocolV2Parser parser = new ProtocolV2Parser( ConfigBuilder.start().allowRefInWant().done()); RevCommit one = testRepo.commit().message("1").create(); RevCommit two = testRepo.commit().message("2").create(); testRepo.update("branchA", one); testRepo.update("branchB", two); parser.parseFetchRequest(pckIn, testRepo.getRepository().getRefDatabase()); }</code><technical_language>optional: This message great --- a valid ref name, a missing ref? avoid test prescriptive making matching exact (e.g. checking message contains ref name). Alternatively, a followup change improve message</technical_language>

Target:
public void testFetchWithRefInWantUnknownRef() throws Exception { thrown.expect(PackProtocolException.class); thrown.expectMessage(containsString("refs/heads/branchC")); PacketLineIn pckIn = formatAsPacketLine(PacketLineIn.DELIM, "want e4980cdc48cfa1301493ca94eb70523f6788b819", "want-ref refs/heads/branchC", PacketLineIn.END); ProtocolV2Parser parser = new ProtocolV2Parser( ConfigBuilder.start().allowRefInWant().done()); RevCommit one = testRepo.commit().message("1").create(); RevCommit two = testRepo.commit().message("2").create(); testRepo.update("branchA", one); testRepo.update("branchB", two); parser.parseFetchRequest(pckIn, testRepo.getRepository().getRefDatabase()); }
Source:
<code>public String evaluate(final Diagram source, final IParameterValueList2 parameterValues, final IFacetManager facetManager) throws DerivedTypedElementException { <START> ETypedElement sfParam = null; if (parameterValues != null) { sfParam = (ETypedElement) parameterValues .getParameterValueByName("eStructuralFeature").getValue(); } String result = null; if (sfParam == null) { final ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory( ComposedAdapterFactory.Descriptor.Registry.INSTANCE); adapterFactory.insertAdapterFactory(new InternationalizationNotationItemProviderAdapterFactory()); try { final IItemLabelProvider itemLabelProvider = (IItemLabelProvider) adapterFactory.adapt(source, IItemLabelProvider.class); if (itemLabelProvider instanceof ReflectiveItemProvider) { result = LabelQuery.getDefaultName(source); } else if (itemLabelProvider == null) { result = ModelUtils.getDefaultName(source); } else { result = itemLabelProvider.getText(source); } } finally { adapterFactory.dispose(); } } else { try { if (sfParam instanceof EAttribute && sfParam.getUpperBound() == 1) { final Object object = facetManager.getOrInvoke(source, sfParam, Object.class); final String objectLabel = getObjectLabel(object, facetManager); result = sfParam.getName() + " = " + objectLabel; } else { result = sfParam.getName(); } } catch (final Exception e) { throw new DerivedTypedElementException(e); } } <END> return result; }</code><technical_language>complex return a name... Diagram.getName()</technical_language>

Target:
public String evaluate(final Diagram source, final IParameterValueList2 parameterValues, final IFacetManager facetManager) throws DerivedTypedElementException { final String label = LabelInternationalization.getInstance().getDiagramLabel(source); return label == null || label.length() == 0 ? NotationEditPlugin.INSTANCE.getString("_UI_Diagram_type", true) : NotationEditPlugin.INSTANCE.getString("_UI_Diagram_type", true) + " " + label; }
Source:
<code><START> protected RelationshipRest createAndReturn(Context context, List<DSpaceObject> list) <END> throws AuthorizeException, SQLException, RepositoryMethodNotImplementedException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); Relationship relationship = new Relationship(); if (list.size() == 2 && list.get(0).getType() == Constants.ITEM && list.get(1).getType() == Constants.ITEM) { Item leftItem = (Item) list.get(0); Item rightItem = (Item) list.get(1); RelationshipType relationshipType = relationshipTypeService .find(context, Integer.parseInt(req.getParameter("relationshipType"))); EPerson ePerson = context.getCurrentUser(); if (authorizeService.authorizeActionBoolean(context, leftItem, Constants.WRITE) || authorizeService.authorizeActionBoolean(context, rightItem, Constants.WRITE)) { relationship.setLeftItem(leftItem); relationship.setRightItem(rightItem); relationship.setRelationshipType(relationshipType); relationship = relationshipService.create(context, relationship); return relationshipConverter.fromModel(relationship); } else { throw new AccessDeniedException("You do not have write rights on this relationship's items"); } } else { throw new UnprocessableEntityException("The given items in the request were not valid items"); } }</code><technical_language>I this is missing @Override</technical_language>

Target:
protected RelationshipRest createAndReturn(Context context, List<DSpaceObject> list) throws AuthorizeException, SQLException, RepositoryMethodNotImplementedException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); Relationship relationship = new Relationship(); if (list.size() == 2 && list.get(0).getType() == Constants.ITEM && list.get(1).getType() == Constants.ITEM) { Item leftItem = (Item) list.get(0); Item rightItem = (Item) list.get(1); RelationshipType relationshipType = relationshipTypeService .find(context, Integer.parseInt(req.getParameter("relationshipType"))); relationship.setLeftItem(leftItem); relationship.setRightItem(rightItem); relationship.setRelationshipType(relationshipType); try { relationship = relationshipService.create(context, relationship); } catch (AuthorizeException e) { throw new AccessDeniedException("You do not have write rights on this relationship's items"); } return relationshipConverter.fromModel(relationship); } else { throw new UnprocessableEntityException("The given items in the request were not valid items"); } }
Source:
<code>public TimeGraphFilterDialog(Shell parent) { super(parent); setResult(new ArrayList<>(0)); setStatusLineAboveButtons(true); setHelpAvailable(false); fExpandedElements = null; fAdditionalFilterButtonInfo = new <START> ArrayList<>(); <END> }</code><technical_language>Nice choice of list ;)</technical_language>

Target:
public TimeGraphFilterDialog(Shell parent) { super(parent); setResult(new ArrayList<>(0)); setStatusLineAboveButtons(true); setHelpAvailable(false); fExpandedElements = null; fCheckActiveProvider = null; fUncheckInactiveProvider = null; }
Source:
<code>public synchronized void play(String path, int seekTo, String title, TranscriptModel trModel, DownloadEntry video) { setScreenOnWhilePlaying(false); <START> <END> isPrepared = false; if ( !isScreenLandscape()) { exitFullScreen(); } clearAllErrors(); try { player.reset(); } catch (Exception e) { logger.error(e); } if(video!=null){ this.videoEntry = video; } if (trModel != null) { this.transcript = trModel; TranscriptManager tm = new TranscriptManager(getActivity()); tm.downloadTranscriptsForVideo(trModel); } try{ PrefManager pm = new PrefManager(getActivity(), PrefManager.Pref.LOGIN); languageSubtitle = pm.getString(PrefManager.Key.TRANSCRIPT_LANGUAGE); }catch(Exception e){ logger.error(e); } requestAudioFocus(); try { showProgress(); if (path == null || path.trim().length() == 0) { showVideoNotAvailable(); } else { hideVideoNotAvailable(); } this.transcript = trModel; player.setLMSUrl(video.lmsUrl); player.setVideoTitle(title); logger.debug("playing [seek=" + seekTo + "]: " + path); boolean enableShare = videoEntry != null && !TextUtils.isEmpty(videoEntry.getYoutubeVideoUrl()) && new FacebookProvider().isLoggedIn(); player.setShareEnabled(enableShare); player.setUriAndPlay(path, seekTo); } catch (Exception e) { logger.error(e); } }</code><technical_language>do here</technical_language>

Target:
public synchronized void play(String path, int seekTo, String title, TranscriptModel trModel, DownloadEntry video) { isPrepared = false; if ( !isScreenLandscape()) { exitFullScreen(); } clearAllErrors(); try { player.reset(); } catch (Exception e) { logger.error(e); } if(video!=null){ this.videoEntry = video; } if (trModel != null) { this.transcript = trModel; TranscriptManager tm = new TranscriptManager(getActivity()); tm.downloadTranscriptsForVideo(trModel); } try{ PrefManager pm = new PrefManager(getActivity(), PrefManager.Pref.LOGIN); languageSubtitle = pm.getString(PrefManager.Key.TRANSCRIPT_LANGUAGE); }catch(Exception e){ logger.error(e); } requestAudioFocus(); try { showProgress(); if (path == null || path.trim().length() == 0) { showVideoNotAvailable(); } else { hideVideoNotAvailable(); } this.transcript = trModel; player.setLMSUrl(video.lmsUrl); player.setVideoTitle(title); logger.debug("playing [seek=" + seekTo + "]: " + path); boolean enableShare = videoEntry != null && !TextUtils.isEmpty(videoEntry.getYoutubeVideoUrl()) && new FacebookProvider().isLoggedIn(); player.setShareEnabled(enableShare); player.setUriAndPlay(path, seekTo); } catch (Exception e) { logger.error(e); } }
Source:
<code>public TotpBean(KeycloakSession session, RealmModel realm, UserModel user, UriBuilder uriBuilder) { this.realm = realm; this.uriBuilder = uriBuilder; <START> this.enabled = ((OTPCredentialProvider)session.getProvider(CredentialProvider.class, "keycloak-otp")).isConfiguredFor(realm, user); <END> if (enabled) { otpCredentials = session.userCredentialManager().getStoredCredentialsByType(realm, user, OTPCredentialModel.TYPE); } else { otpCredentials = Collections.EMPTY_LIST; } this.totpSecret = HmacOTP.generateSecret(20); this.totpSecretEncoded = TotpUtils.encode(totpSecret); this.totpSecretQrCode = TotpUtils.qrCode(totpSecret, realm, user); }</code><technical_language>Is "this.enabled = session.userCredentialManager().isConfiguredFor(realm, user, OTPCredentialModel.TYPE);" ? of "userCredentialManager" instead of OTPProvider is preferred due case userStorage is - some details in <LINK_0></technical_language>

Target:
public TotpBean(KeycloakSession session, RealmModel realm, UserModel user, UriBuilder uriBuilder) { this.realm = realm; this.uriBuilder = uriBuilder; this.enabled = session.userCredentialManager().isConfiguredFor(realm, user, OTPCredentialModel.TYPE); if (enabled) { otpCredentials = session.userCredentialManager().getStoredCredentialsByType(realm, user, OTPCredentialModel.TYPE); } else { otpCredentials = Collections.EMPTY_LIST; } this.totpSecret = HmacOTP.generateSecret(20); this.totpSecretEncoded = TotpUtils.encode(totpSecret); this.totpSecretQrCode = TotpUtils.qrCode(totpSecret, realm, user); }
Source:
<code>private void updateActionAvailability() { if (getSelectedItems() == null || getSelectedItems().size() == 0) { getEnableHookCommand().setIsExecutionAllowed(false); getDisableHookCommand().setIsExecutionAllowed(false); return; } getEnableHookCommand().setIsExecutionAllowed(true); getDisableHookCommand().setIsExecutionAllowed(true); for (GlusterHookEntity hook : Linq.<GlusterHookEntity> Cast(getSelectedItems())) { if (hook.getStatus() == GlusterHookStatus.ENABLED) { getEnableHookCommand().setIsExecutionAllowed(false); } else { getDisableHookCommand().setIsExecutionAllowed(false); <START> } <END> } }</code><technical_language>2 flags break</technical_language>

Target:
private void updateActionAvailability() { if (getSelectedItems() == null || getSelectedItems().size() == 0) { getEnableHookCommand().setIsExecutionAllowed(false); getDisableHookCommand().setIsExecutionAllowed(false); return; } getEnableHookCommand().setIsExecutionAllowed(true); getDisableHookCommand().setIsExecutionAllowed(true); for (Object item : getSelectedItems()) { GlusterHookEntity hook = (GlusterHookEntity) item; if (hook.getStatus() == GlusterHookStatus.ENABLED) { getEnableHookCommand().setIsExecutionAllowed(false); } else { getDisableHookCommand().setIsExecutionAllowed(false); } if (!getEnableHookCommand().getIsExecutionAllowed() && !getDisableHookCommand().getIsExecutionAllowed()) { break; } } }
Source:
<code>public void destroy() throws Exception { this.pool.close(); <START> this.pool.removeAllIdleItems(); <END> }</code><technical_language>new close() do this for us, too</technical_language>

Target:
public void destroy() throws Exception { this.pool.close(); }
Source:
<code>public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { IRepositoryElement reviewRepoElement = delta.getElement(); if (!(reviewRepoElement instanceof ITask)) { <START> return; <END> } ITask review = (ITask) reviewRepoElement; AbstractRepositoryConnector connector = repositoryManager.getRepositoryConnector(review.getConnectorKind()); if (review != null && connector instanceof ReviewsConnector) { try { String reviewUrl = review.getUrl(); switch (delta.getKind()) { case REMOVED: break; case DELETED: deleteMappingsTo(reviewUrl); break; case ADDED: case CONTENT: TaskData taskData = taskDataManager.getTaskData(review); if (taskData == null) { continue; } TaskAttribute attr = taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION); if (attr == null) { continue; } String reviewDescription = attr.getValue(); updateMapping(reviewUrl, reviewDescription); break; default: StatusHandler.log(new Status(IStatus.ERROR, ReviewsCoreConstants.PLUGIN_ID, "Unknown change")); } } catch (CoreException e) { StatusHandler.log( new Status(IStatus.ERROR, ReviewsCoreConstants.PLUGIN_ID, "Error getting taskData.", e)); } } } }</code><technical_language>continue</technical_language>

Target:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { IRepositoryElement reviewRepoElement = delta.getElement(); if (!(reviewRepoElement instanceof ITask)) { return; } ITask review = (ITask) reviewRepoElement; AbstractRepositoryConnector connector = repositoryManager.getRepositoryConnector(review.getConnectorKind()); if (review != null && connector instanceof ReviewsConnector) { try { String reviewUrl = review.getUrl(); switch (delta.getKind()) { case DELETED: deleteMappingsTo(reviewUrl); break; case ADDED: case CONTENT: TaskData taskData = taskDataManager.getTaskData(review); if (taskData == null) { continue; } TaskAttribute attr = taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION); if (attr == null) { continue; } String reviewDescription = attr.getValue(); updateMapping(reviewUrl, reviewDescription); break; } } catch (CoreException e) { StatusHandler.log( new Status(IStatus.ERROR, ReviewsCoreConstants.PLUGIN_ID, "Error getting taskData.", e)); } } } }
Source:
<code>public ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters) { RequestBuilder builder = RequestBuilder.post("/v1/analyze"); <START> builder.query("version", versionDate); <END> if (parameters != null) { builder.bodyJson(GsonSingleton.getGson().toJsonTree(parameters).getAsJsonObject()); } else { builder.bodyJson(new JsonObject()); } return createServiceCall(builder.build(), ResponseConverterUtils.getObject(AnalysisResults.class)); }</code><technical_language>VERSION for consistency</technical_language>

Target:
public ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters) { RequestBuilder builder = RequestBuilder.post("/v1/analyze"); builder.query(VERSION, versionDate); if (parameters != null) { builder.bodyJson(GsonSingleton.getGson().toJsonTree(parameters).getAsJsonObject()); } else { builder.bodyJson(new JsonObject()); } return createServiceCall(builder.build(), ResponseConverterUtils.getObject(AnalysisResults.class)); }
Source:
<code>protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); <START> out.write(EncodingUtil.getAsciiBytes(FILE_NAME)); <END> out.write(QUOTE_BYTES); out.write(EncodingUtil.getBytes(filename, getCharSet())); out.write(QUOTE_BYTES); }</code><technical_language>I this needs check filename is null</technical_language>

Target:
protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); if (filename != null) { out.write(EncodingUtil.getAsciiBytes(FILE_NAME)); out.write(QUOTE_BYTES); out.write(EncodingUtil.getBytes(filename, getCharSet())); out.write(QUOTE_BYTES); } }
Source:
<code>public static UpdateCalibrationResponse createFromPutBatchResponse(final Map<String, Optional<Boolean>> putBatchResponse) { final UpdateCalibrationResponse updateCalibrationResponse = UpdateCalibrationResponse.createEmpty(); for (final Map.Entry<String, Optional<Boolean>> item : putBatchResponse.entrySet()) { <START> if (!item.getValue().isPresent()) { <END> updateCalibrationResponse.addFailedConditionItem(item.getKey()); } else if (item.getValue().get()) { updateCalibrationResponse.addSuccessItem(item.getKey()); } else { updateCalibrationResponse.addUnprocessedItem(item.getKey()); } } return updateCalibrationResponse; }</code><technical_language>reminder: this logic is backwards. Optional error prevents answer</technical_language>

Target:
public static UpdateCalibrationResponse createFromPutBatchResponse(final Map<String, Optional<Boolean>> putBatchResponse) { final UpdateCalibrationResponse updateCalibrationResponse = new UpdateCalibrationResponse(); for (final Map.Entry<String, Optional<Boolean>> item : putBatchResponse.entrySet()) { if (!item.getValue().isPresent()) { updateCalibrationResponse.addFailedConditionItem(item.getKey()); } else if (item.getValue().get()) { updateCalibrationResponse.addSuccessItem(item.getKey()); } else { updateCalibrationResponse.addUnprocessedItem(item.getKey()); } } return updateCalibrationResponse; }
Source:
<code>public DataContainer toContainer() { return DataContainer.createNew().set(Queries.CONTENT_VERSION, this.getContentVersion()) <START> .set(DataQuery.of("materialcost"), this.getMaterialCost()) <END> .set(DataQuery.of("levelcost"), this.getLevelCost()); }</code><technical_language>queries static in DataQueries</technical_language>

Target:
public DataContainer toContainer() { return DataContainer.createNew().set(Queries.CONTENT_VERSION, this.getContentVersion()) .set(DataQueries.MATERIALCOST, this.getMaterialCost()) .set(DataQueries.LEVELCOST, this.getLevelCost()); }
Source:
<code>public void createsCommit() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_CREATED, "{\"sha\":\"0abcd89jcabitest\"}" ) ).start(); final Commits commits = new RtCommits( new ApacheRequest(container.home()), repo() ); final JsonObject author = Json.createObjectBuilder() .add("name", "Scott").add("email", "scott@gmail.com") .add("date", "2011-06-17T14:53:35-07:00").build(); final JsonObject input = Json.createObjectBuilder() .add("message", "initial version") .add("author", author).build(); try { MatcherAssert.assertThat( commits.create(input), Matchers.instanceOf(Commit.class) ); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( <START> container.take().method(), <END> Matchers.equalTo(Request.POST) ); } finally { container.stop(); } }</code><technical_language>MkContainer works, is sets a fake HTTP server local machine. For HTTP request receives: 1. A MkQuery is stored corresponds request queues internally. container.take() method obtains MkQuery queue in a FIFO-fashion. This means HTTP request correspond invocation of take(). If more requests (you called times), throw exception. 2. responds MkAnswer(s) invoking .next(), prior calling start. If need multiple requests responses, call next() multiple times exact answers need. If runs out of requests, respond HTTP 500. In this case, request, in commits.create(input), checking method. need call take().method() check thing. store reference returned take() if need multiple times (e.g. obtain body, method): java final MkQuery query = container.take(); String body = query.body(); int method = query.method;</technical_language>

Target:
public final void createsCommit() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_CREATED, "{\"sha\":\"0abcd89jcabitest\"}" ) ).start(); final Commits commits = new RtCommits( new ApacheRequest(container.home()), repo() ); final JsonObject author = Json.createObjectBuilder() .add("name", "Scott").add("email", "scott@gmail.com") .add("date", "2011-06-17T14:53:35-07:00").build(); final JsonObject input = Json.createObjectBuilder() .add("message", "initial version") .add("author", author).build(); try { final Commit newCommit = commits.create(input); MatcherAssert.assertThat( newCommit, Matchers.instanceOf(Commit.class) ); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( newCommit.sha(), Matchers.equalTo("0abcd89jcabitest") ); } finally { container.stop(); } }