auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void ensureXmlTestIsNotNull(Class<?> clazz, XmlSuite.ParallelMode mode) { XmlSuite xmlSuite = createXmlSuite("Suite"); createXmlTest(xmlSuite, "GITHUB-1029-Test", clazz); xmlSuite.setParallel(mode); Issue1029InvokedMethodListener listener = new Issue1029InvokedMethodListener(); TestNG testng = create(xmlSuite); testng.addListener((ITestNGListener) listener); testng.setThreadCount(10); <START> testng.setThreadCount(10); <END> testng.run(); List<String> expected = Collections.nCopies(5, "GITHUB-1029-Test"); assertThat(listener.getBeforeInvocation()).containsExactlyElementsOf(expected); assertThat(listener.getAfterInvocation()).containsExactlyElementsOf(expected); }</code><technical_language>duplicate line</technical_language>

Target:
public void ensureXmlTestIsNotNull(Class<?> clazz, XmlSuite.ParallelMode mode) { XmlSuite xmlSuite = createXmlSuite("Suite"); createXmlTest(xmlSuite, "GITHUB-1029-Test", clazz); xmlSuite.setParallel(mode); Issue1029InvokedMethodListener listener = new Issue1029InvokedMethodListener(); TestNG testng = create(xmlSuite); testng.addListener((ITestNGListener) listener); testng.setThreadCount(10); testng.setDataProviderThreadCount(10); testng.run(); List<String> expected = Collections.nCopies(5, "GITHUB-1029-Test"); assertThat(listener.getBeforeInvocation()).containsExactlyElementsOf(expected); assertThat(listener.getAfterInvocation()).containsExactlyElementsOf(expected); }
Source:
<code>public void onRunFinish(boolean succeeded, BatchSinkContext context) { super.onRunFinish(succeeded, context); if (succeeded) { try { if (config.getCleanPartitionsOlderThan() != null) { long cutoffTime = context.getLogicalStartTime() - TimeParser.parseDuration(config.getCleanPartitionsOlderThan()); snapshotFileSet.deleteMatchingPartitionsByTime(cutoffTime); <START> LOG.info("Cleaning up old partition for timestamp {}", cutoffTime); <END> } snapshotFileSet.onSuccess(context.getLogicalStartTime()); } catch (Exception e) { LOG.error("Exception updating state file with value of latest snapshot, ", e); } } }</code><technical_language>this log statement is inaccurate</technical_language>

Target:
public void onRunFinish(boolean succeeded, BatchSinkContext context) { super.onRunFinish(succeeded, context); if (succeeded) { try { snapshotFileSet.onSuccess(context.getLogicalStartTime()); } catch (Exception e) { LOG.error("Exception updating state file with value of latest snapshot, ", e); } try { if (config.getCleanPartitionsOlderThan() != null) { long cutoffTime = context.getLogicalStartTime() - TimeParser.parseDuration(config.getCleanPartitionsOlderThan()); snapshotFileSet.deleteMatchingPartitionsByTime(cutoffTime); LOG.info("Cleaning up snapshots older than {}", cutoffTime); } } catch (IOException e) { LOG.error("Exception occurred while cleaning up older snapshots", e); } } }
Source:
<code>public void testGetInt_invalid() throws CTFReaderException { BitBuffer small_fixture = new BitBuffer(ByteBuffer.allocateDirect(128)); small_fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(small_fixture, 2); small_fixture.position(10); int length = 32; boolean signed = true; <START> small_fixture.get(length, signed); <END> }</code><technical_language>is assert</technical_language>

Target:
public void testGetInt_invalid() throws CTFReaderException { final BitBuffer small_fixture = new BitBuffer( java.nio.ByteBuffer.allocateDirect(128)); small_fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(small_fixture, 2); small_fixture.position(10); final int length = 32; final boolean signed = true; small_fixture.get(length, signed); }
Source:
<code>public IAnswerData getAnswer() { <START> return !binding.widgetAnswerText.getText().equals(getContext().getString(R.string.no_time_selected)) <END> ? DateTimeWidgetUtils.getTimeData(hourOfDay, minuteOfHour) : null; }</code><technical_language>need negation if turn order: return binding.widgetAnswerText.getText().equals(getContext().getString(R.string.no_time_selected)) ? null : DateTimeWidgetUtils.getTimeData(hourOfDay, minuteOfHour);</technical_language>

Target:
public IAnswerData getAnswer() { return binding.timeAnswerText.getText().equals(getContext().getString(R.string.no_time_selected)) ? null : new TimeData(selectedTime.toDateTime().toDate()); }
Source:
<code>private RevCommit resolveReflog(RevWalk rw, Ref ref, String time) throws IOException { int number; try { number = Integer.parseInt(time); } catch (NumberFormatException nfe) { throw new RevisionSyntaxException( JGitText.get().reflogResolveRequiresPositiveInteger); } if (number < 0) throw new RevisionSyntaxException( <START> JGitText.get().reflogResolveRequiresPositiveInteger); <END> ReflogReader reader = new ReflogReader(this, ref.getName()); List<ReflogEntry> entries = reader.getReverseEntries(number + 1); if (number >= entries.size()) throw new RevisionSyntaxException(MessageFormat.format( JGitText.get().reflogEntryNotFound, Integer.valueOf(number), ref.getName(), Integer.valueOf(entries.size()))); return rw.parseCommit(entries.get(number).getNewId()); }</code><technical_language>need this specific why. good is enough. change allowed values soon anyway</technical_language>

Target:
private RevCommit resolveReflog(RevWalk rw, Ref ref, String time) throws IOException { int number; try { number = Integer.parseInt(time); } catch (NumberFormatException nfe) { throw new RevisionSyntaxException(MessageFormat.format( JGitText.get().invalidReflogRevision, time)); } if (number < 0) throw new RevisionSyntaxException(MessageFormat.format( JGitText.get().invalidReflogRevision, time)); ReflogReader reader = new ReflogReader(this, ref.getName()); List<ReflogEntry> entries = reader.getReverseEntries(number + 1); if (number >= entries.size()) throw new RevisionSyntaxException(MessageFormat.format( JGitText.get().reflogEntryNotFound, Integer.valueOf(number), ref.getName(), Integer.valueOf(entries.size()))); return rw.parseCommit(entries.get(number).getNewId()); }
Source:
<code><START> public void testPingPongRoot() throws Exception { assertTrue("Device is vulnerable to CVE-2015-3636, a vulnerability in the ping " + "socket implementation. Please apply the security patch at " + "<LINK_10>", doPingPongRootTest()); <END> public void testPipeReadV() throws Exception { assertTrue("Device is vulnerable to CVE-2015-1805 and/or CVE-2016-0774," + " a vulnerability in the pipe_read() function." + " Please apply the following patches:\n" + "<LINK_6>\n" + "<LINK_9>\n", doPipeReadVTest()); } private static native boolean doPerfEventTest(); private static native boolean doPerfEventTest2(); private static native int doSockDiagTest(); private static native boolean doVrootTest(); public void testCVE20141710() throws Exception { assertTrue("Device is vulnerable to CVE-2014-1710", doCVE20141710Test()); } private static native boolean doFutexTest(); private static native boolean doCVE20141710Test(); private static native boolean doPingPongRootTest(); private static native boolean doPipeReadVTest(); }</code><technical_language>missing '}'</technical_language>

Target:
public void testPingPongRoot() throws Exception { assertTrue("Device is vulnerable to CVE-2015-3636, a vulnerability in the ping " + "socket implementation. Please apply the security patch at " + "<LINK_10>", doPingPongRootTest()); }
Source:
<code>public List<SinkRecord> add(SinkRecord record) throws SQLException { final SchemaPair schemaPair = new SchemaPair( record.keySchema(), record.valueSchema() ); if (currentSchemaPair == null) { currentSchemaPair = schemaPair; fieldsMetadata = FieldsMetadata.extract( tableId.tableName(), config.pkMode, config.pkFields, config.fieldsWhitelist, currentSchemaPair ); dbStructure.createOrAmendIfNecessary( config, connection, tableId, fieldsMetadata ); final String sql = getInsertSql(); log.debug( "{} sql: {}", config.insertMode, sql ); close(); preparedStatement = connection.prepareStatement(sql); preparedStatementBinder = dbDialect.statementBinder( preparedStatement, config.pkMode, schemaPair, fieldsMetadata, config.insertMode ); } final List<SinkRecord> flushed; if (currentSchemaPair.equals(schemaPair)) { records.add(record); if (records.size() >= config.batchSize) { <START> log.debug("Flushing buffered records after exceeding configured batch size."); <END> flushed = flush(); } else { flushed = Collections.emptyList(); } } else { log.debug("Flushing buffered records after due to unequal schema pairs: " + "Current Schemas: {}, Next Schemas: {}", currentSchemaPair, schemaPair); flushed = flush(); currentSchemaPair = null; flushed.addAll(add(record)); } return flushed; }</code><technical_language>including records.size() config.batchSize values in message? Maybe: suggestion log.debug( "Flushing buffered records number of records exceeds configured batch size {}.", records.size(), config.batch.size );</technical_language>

Target:
public List<SinkRecord> add(SinkRecord record) throws SQLException { final SchemaPair schemaPair = new SchemaPair( record.keySchema(), record.valueSchema() ); if (currentSchemaPair == null) { currentSchemaPair = schemaPair; fieldsMetadata = FieldsMetadata.extract( tableId.tableName(), config.pkMode, config.pkFields, config.fieldsWhitelist, currentSchemaPair ); dbStructure.createOrAmendIfNecessary( config, connection, tableId, fieldsMetadata ); final String sql = getInsertSql(); log.debug( "{} sql: {}", config.insertMode, sql ); close(); preparedStatement = connection.prepareStatement(sql); preparedStatementBinder = dbDialect.statementBinder( preparedStatement, config.pkMode, schemaPair, fieldsMetadata, config.insertMode ); } final List<SinkRecord> flushed; if (currentSchemaPair.equals(schemaPair)) { records.add(record); if (records.size() >= config.batchSize) { log.debug("Flushing buffered records after exceeding configured batch size {}.", config.batchSize); flushed = flush(); } else { flushed = Collections.emptyList(); } } else { log.debug("Flushing buffered records after due to unequal schema pairs: " + "current schemas: {}, next schemas: {}", currentSchemaPair, schemaPair); flushed = flush(); currentSchemaPair = null; flushed.addAll(add(record)); } return flushed; }
Source:
<code>Map<String, String> getCheckConstraints() { <START> return ImmutableMap.<String, String>builder().putAll(checkConstraints).build(); <END> }</code><technical_language>suggestion return Map.<String, String>copyOf(checkConstraints);</technical_language>

Target:
Map<String, String> getCheckConstraints() { return Map.copyOf(checkConstraints); }
Source:
<code>public void testWebDavResponse() { byte[] data = ("HTTP/1.1 102 Processing\r\n" + "Status-URI: Status-URI:<LINK_0>; 404\r\n" + "\r\n" + "1234567812345678").getBytes(); EmbeddedChannel ch = new EmbeddedChannel(new HttpClientCodec()); assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(data))); HttpResponse res = ch.readInbound(); assertThat(res.protocolVersion(), sameInstance(HttpVersion.HTTP_1_1)); assertThat(res.status(), is(HttpResponseStatus.PROCESSING)); HttpContent content = ch.readInbound(); assertThat(content.content().readableBytes(), is(0)); content.release(); assertThat(ch.finish(), is(false)); <START> assertThat(ch.readInbound(), is(nullValue())); <END> }</code><technical_language>this is redundant assert. if finish() returns false left consume</technical_language>

Target:
public void testWebDavResponse() { byte[] data = ("HTTP/1.1 102 Processing\r\n" + "Status-URI: Status-URI:<LINK_0>; 404\r\n" + "\r\n" + "1234567812345678").getBytes(); EmbeddedChannel ch = new EmbeddedChannel(new HttpClientCodec()); assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(data))); HttpResponse res = ch.readInbound(); assertThat(res.protocolVersion(), sameInstance(HttpVersion.HTTP_1_1)); assertThat(res.status(), is(HttpResponseStatus.PROCESSING)); HttpContent content = ch.readInbound(); assertThat(content.content().readableBytes(), is(0)); content.release(); assertThat(ch.finish(), is(false)); }
Source:
<code>void shouldUpdateChargeToAuthorisationRejected_IfEpdqStatusIs2() { final String payload = notificationPayloadForTransaction(payId, EPDQ_AUTHORISATION_REFUSED); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); <START> final boolean result = notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES); assertTrue(result); <END> verify(mockChargeNotificationProcessor).invoke(payId, charge, AUTHORISATION_REJECTED, null); }</code><technical_language>major lines collapsed assertTrue(notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES))</technical_language>

Target:
void shouldUpdateChargeToAuthorisationRejected_IfEpdqStatusIs2() { final String payload = notificationPayloadForTransaction(payId, EPDQ_AUTHORISATION_REFUSED); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); assertTrue(notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES)); verify(mockChargeNotificationProcessor).invoke(payId, charge, AUTHORISATION_REJECTED, null); }
Source:
<code>protected Object buildPreviewNotAvailable() { <START> return Response.status(404).entity(getTemplate("preview/preview_not_available.ftl")).type("text/html").build(); <END> }</code><technical_language>NOT_FOUND</technical_language>

Target:
protected Object buildPreviewNotAvailable() { return Response.status(NOT_FOUND) .entity(getTemplate("preview/preview_not_available.ftl")) .type("text/html") .build(); }
Source:
<code>public static boolean isSupported(Class<? extends DeletionQuery> type) { if ( SUPPORTED_TYPES == null ) { SUPPORTED_TYPES_LOCK.lock(); try { if ( SUPPORTED_TYPES == null ) { <START> Map<Integer, Class<? extends DeletionQuery>> map = new HashMap<>(); <END> map.put( SingularTermDeletionQuery.QUERY_KEY, SingularTermDeletionQuery.class ); SUPPORTED_TYPES = Collections.unmodifiableSet( new HashSet<>( map.values() ) ); } } finally { SUPPORTED_TYPES_LOCK.unlock(); } } return SUPPORTED_TYPES.contains( type ); }</code><technical_language>a bit lost here; is this map created? In end set relevant. is lazy creation worth effort (locking etc.)? thought a simple map suffice for methods of this class: private static Map<Class<? extends DeletionQuery>, DeletionQueryMapper> MAPPERS_BY_QUERY= Collections.unmodifiableMap( Collections.singletonMap(SingularTermDeletionQuery.class, new SingularTermDeletionQueryMapper() ) ); public static boolean isSupported(Class<? extends DeletionQuery> type) { return MAPPERS_BY_QUERY.containsKey( type ); } public static DeletionQueryMapper getMapper(Class<? extends DeletionQuery> type) { return MAPPERS_BY_QUERY.get( type ); } That'd simpler, missing some piece? unsure is alternative DeletionQuery implementations registered? Is supported all</technical_language>

Target:
public static boolean isSupported(Class<? extends DeletionQuery> type) { if ( SingularTermDeletionQuery.class == type ) { return true; } return false; }
Source:
<code>public void addPart(Part p, int transitDays) { if ((p.getUnit() != null) && (p.getUnit() instanceof TestUnit)) { return; } p.setDaysToArrival(transitDays); p.setBrandNew(false); int id = lastPartId + 1; p.setId(id); p.postProcessCampaignAddition(); if (p instanceof MissingPart && (null == p.getUnit() || null == p.getUnitId())) { p.setId(-1); return; } <START> if (null == p.getUnit() && !p.hasParentPart()) { <END> Part spare = checkForExistingSparePart(p); if (null != spare) { if (p instanceof Armor) { if (spare instanceof Armor) { ((Armor) spare).setAmount(((Armor) spare).getAmount() + ((Armor) p).getAmount()); MekHQ.triggerEvent(new PartChangedEvent(spare)); p.setId(-1); return; } } else if (p instanceof AmmoStorage) { if (spare instanceof AmmoStorage) { ((AmmoStorage) spare).changeShots(((AmmoStorage) p) .getShots()); MekHQ.triggerEvent(new PartChangedEvent(spare)); p.setId(-1); return; } } else { spare.incrementQuantity(); MekHQ.triggerEvent(new PartChangedEvent(spare)); p.setId(-1); return; } } } parts.put(id, p); lastPartId = id; MekHQ.triggerEvent(new PartNewEvent(p)); }</code><technical_language>suggestion if ((null == p.getUnit()) && !p.hasParentPart()) {</technical_language>

Target:
public void addPart(Part p, int transitDays) { if ((p.getUnit() != null) && (p.getUnit() instanceof TestUnit)) { return; } p.setDaysToArrival(transitDays); p.setBrandNew(false); int id = lastPartId + 1; p.setId(id); p.postProcessCampaignAddition(); if (p instanceof MissingPart && (null == p.getUnit() || null == p.getUnitId())) { p.setId(-1); return; } if ((null == p.getUnit()) && !p.hasParentPart()) { Part spare = checkForExistingSparePart(p); if (null != spare) { if (p instanceof Armor) { if (spare instanceof Armor) { ((Armor) spare).setAmount(((Armor) spare).getAmount() + ((Armor) p).getAmount()); MekHQ.triggerEvent(new PartChangedEvent(spare)); p.setId(-1); return; } } else if (p instanceof AmmoStorage) { if (spare instanceof AmmoStorage) { ((AmmoStorage) spare).changeShots(((AmmoStorage) p) .getShots()); MekHQ.triggerEvent(new PartChangedEvent(spare)); p.setId(-1); return; } } else { spare.incrementQuantity(); MekHQ.triggerEvent(new PartChangedEvent(spare)); p.setId(-1); return; } } } parts.put(id, p); lastPartId = id; MekHQ.triggerEvent(new PartNewEvent(p)); }
Source:
<code>public List<List<String>> createAlternativeNamesDictionary(List<String> classpathCsvResources) throws IOException { <START> List<List<String>> dictionary = Lists.newArrayList(); <END> for (String resource : classpathCsvResources) { List<List<String>> dictionaryFromCsv = createAltNamesDictionaryFromCsv(resource); dictionary.addAll(dictionaryFromCsv); } return dictionary; }</code><technical_language>considered List of Set of Strings? This eliminate potential duplicates right away</technical_language>

Target:
public List<Set<String>> createAlternativeNamesDictionary(List<String> classpathCsvResources) throws IOException { List<Set<String>> dictionary = Lists.newArrayList(); for (String resource : classpathCsvResources) { List<Set<String>> dictionaryFromCsv = createAltNamesDictionaryFromCsv(resource); dictionary.addAll(dictionaryFromCsv); } return dictionary; }
Source:
<code>public void onSiteChanged(OnSiteChanged event) { if (!isAdded() || mLoginFinished) { return; } if (event.isError()) { AppLog.e(AppLog.T.API, "onSiteChanged has error: " + event.error.type + " - " + event.error.toString()); if (!isAdded() || event.error.type != SiteErrorType.DUPLICATE_SITE) { onLoginFinished(false); return; } if (event.rowsAffected == 0) { ToastUtils.showToast(getContext(), R.string.cannot_add_duplicate_site); onLoginFinished(false); return; } else { ToastUtils.showToast(getContext(), R.string.duplicate_site_detected); } } <START> if (mLoginListener instanceof LoginListener) { <END> ((LoginListener) mLoginListener).startPostLoginServices(); } onLoginFinished(true); }</code><technical_language>Hmm, share some of background of this narrowing-down of start post-login services? Is some bugfix perhaps? Truth is check for listener's type a bit uneasy. do instead of a instanceof check this a by-default implemented method (see listenForLogin() for example)? method return true default subclasses need overridden return false</technical_language>

Target:
public void onSiteChanged(OnSiteChanged event) { if (!isAdded() || mLoginFinished) { return; } if (event.isError()) { AppLog.e(AppLog.T.API, "onSiteChanged has error: " + event.error.type + " - " + event.error.toString()); if (!isAdded() || event.error.type != SiteErrorType.DUPLICATE_SITE) { onLoginFinished(false); return; } if (event.rowsAffected == 0) { ToastUtils.showToast(getContext(), R.string.cannot_add_duplicate_site); onLoginFinished(false); return; } else { ToastUtils.showToast(getContext(), R.string.duplicate_site_detected); } } onLoginFinished(true); }
Source:
<code><START> default long position() { <END> return -1L; }</code><technical_language>good a default for Token implementations do (yet) support position. However, -1 a meaning for tokens. For stores starting 0, -1 simply event processed yet. Therefor, recommend OptionalLong return type. If token support positions give estimate, return OptionalLong.empty()</technical_language>

Target:
default OptionalLong position() { return OptionalLong.empty(); }
Source:
<code>public void sanitizeForSaving() { <START> this.googleId = googleId; <END> this.name = name; this.institute = institute; }</code><technical_language>SanitizationHelper.sanitizeGoogleId</technical_language>

Target:
public void sanitizeForSaving() { this.googleId = SanitizationHelper.sanitizeGoogleId(googleId); this.name = SanitizationHelper.sanitizeName(name); this.email = SanitizationHelper.sanitizeEmail(email); this.institute = SanitizationHelper.sanitizeTitle(institute); }
Source:
<code>private static boolean isCompileTimeEvaluationPossible(Expression funcExpr) { boolean compileTimeEvaluationPossible = true; Function functionCall = funcExpr.getFunctionCall(); if(functionCall.getOperandsSize() > 0) { for (Expression expression : functionCall.getOperands()) { <START> if (expression.getType() != ExpressionType.LITERAL) { <END> compileTimeEvaluationPossible = false; break; } } } return compileTimeEvaluationPossible; }</code><technical_language>this recursively evaluated, technically a function of function of literal true here. E.g. format_time(now(), 'yyyy-MM-dd')</technical_language>

Target:
private static boolean isCompileTimeEvaluationPossible(Expression funcExpr) { Function functionCall = funcExpr.getFunctionCall(); if (functionCall.getOperandsSize() > 0) { for (Expression expression : functionCall.getOperands()) { if (expression.getType() == ExpressionType.FUNCTION) { if (!isCompileTimeEvaluationPossible(expression)){ return false; } } else if (expression.getType() != ExpressionType.LITERAL) { return false; } } } return true; }
Source:
<code>public void testRowKeysWithRegEx() throws Exception{ Table table = getDefaultTable(); String[] rowKeys = { "/firstKey=1/secKey=AB/thirdKey=111", "/firstKey=1/secKey=ABC/thirdKey=222", "/firstKey=2/secKey=CD/thirdKey=333", "/firstKey=3/secKey=BT/thirdKey=444", "/firstKey=4/secKey=BTL/thirdKey=555", "/firstKey=4/secKey=AD/thirdKey=666", "/firstKey=5/secKey=SET/thirdKey=777", "/firstKey=11/secKey=AA/thirdKey=888" }; List<Put> puts = new ArrayList<>(); byte[] qualA = dataHelper.randomData("test-regex"); for (int i = 0; i < rowKeys.length; i++) { String indexStr = String.valueOf(i); puts.add( <START> new Put(rowKeys[i].getBytes()).addColumn(COLUMN_FAMILY, qualA, Bytes.toBytes(indexStr))); <END> } table.put(puts); int[] expected = { 5, 4 }; String[] conditions = { "/firstKey=4.*" }; assertRowKeysWithRegex(table, conditions, rowKeys, expected); expected = new int[] { 0, 1 }; conditions = new String[] { ".*secKey=AB.*" }; assertRowKeysWithRegex(table, conditions, rowKeys, expected); expected = new int[] { 0, 6 }; conditions = new String[] { ".*/thirdKey=111.*", ".*/thirdKey=777.*" }; assertRowKeysWithRegex(table, conditions, rowKeys, expected); }</code><technical_language>Please create a single random byte string put row keys. This test run more once</technical_language>

Target:
public void testRowKeysWithRegEx() throws Exception{ Table table = getDefaultTable(); String[] rowKeys = { "/firstKey=1/secKey=AB/thirdKey=111", "/firstKey=1/secKey=ABC/thirdKey=222", "/firstKey=11/secKey=AA/thirdKey=888", "/firstKey=2/secKey=CD/thirdKey=333", "/firstKey=3/secKey=BT/thirdKey=444", "/firstKey=4/secKey=AD/thirdKey=555", "/firstKey=4/secKey=BTL/thirdKey=666", "/firstKey=5/secKey=SET/thirdKey=777", }; List<Put> puts = new ArrayList<>(); String rowPrefix = dataHelper.randomString("testrow-"); byte[] qualA = dataHelper.randomData("test-regex"); for (int i = 0; i < rowKeys.length; i++) { String indexStr = String.valueOf(i); puts.add( new Put(Bytes.toBytes(rowPrefix + rowKeys[i])).addColumn(COLUMN_FAMILY, qualA, Bytes.toBytes(indexStr))); } table.put(puts); int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7 }; String[] conditions = { ".*" }; assertRowKeysWithRegex(table, conditions, rowPrefix, rowKeys, expected); expected = new int[]{ 5, 6 }; conditions = new String[]{ ".*/firstKey=4.*" }; assertRowKeysWithRegex(table, conditions, rowPrefix, rowKeys, expected); expected = new int[] { 0, 1 }; conditions = new String[] { ".*secKey=AB.*" }; assertRowKeysWithRegex(table, conditions, rowPrefix, rowKeys, expected); expected = new int[] { 0, 7 }; conditions = new String[] { ".*/thirdKey=111.*", ".*/thirdKey=777.*" }; assertRowKeysWithRegex(table, conditions, rowPrefix, rowKeys, expected); expected = new int[]{}; conditions = new String[]{ "" }; assertRowKeysWithRegex(table, conditions, rowPrefix, rowKeys, expected); expected = new int[]{}; conditions = new String[]{ "/unMatchedKey=NA" }; assertRowKeysWithRegex(table, conditions, rowPrefix, rowKeys, expected); }
Source:
<code>public List<Transaction> getTransactionList() { if(transactionList == null) { <START> transactionList = new ArrayList<>(); <END> } return transactionList; }</code><technical_language>This is a nitpick, return Collections.emptyList() if want: <LINK_0></technical_language>

Target:
public List<Transaction> getTransactionList() { return transactionList == null ? Collections.<Transaction>emptyList() : transactionList; }
Source:
<code>private boolean isArtifact(ITask task) { boolean hasAssosciatedTask = true; boolean hasContext = TasksUiPlugin.getContextStore().hasContext(task); boolean hasScheduledDate = false; AbstractTask abstractTask = (AbstractTask) task; if (abstractTask != null) { hasScheduledDate = abstractTask.getScheduledForDate() != null; } boolean hasDueDate = task.getDueDate() != null; <START> return hasAssosciatedTask && !(hasAssosciatedTask || hasScheduledDate || hasDueDate); <END> }</code><technical_language>hasAssosciatedTask hasContext</technical_language>

Target:
private boolean isArtifact(ITask task) { boolean hasAssosciatedTask = true; boolean hasContext = TasksUiPlugin.getContextStore().hasContext(task); boolean hasScheduledDate = false; if (task instanceof AbstractTask) { AbstractTask abstractTask = (AbstractTask) task; hasScheduledDate = abstractTask.getScheduledForDate() != null; } boolean hasDueDate = task.getDueDate() != null; return hasAssosciatedTask && !(hasContext || hasScheduledDate || hasDueDate); }
Source:
<code>public RegisteredObservers load(CuratorFramework curator) throws Exception { byte[] data; try { data = curator.getData().forPath(CONFIG_FLUO_OBSERVERS2); } catch (NoNodeException nne) { return null; } String json = new String(data, UTF_8); JsonObservers jco = new Gson().fromJson(json, JsonObservers.class); ImmutableSet.Builder<Column> weakColumnsBuilder = new ImmutableSet.Builder<Column>(); ImmutableSet.Builder<Column> strongColumnsBuilder = new ImmutableSet.Builder<Column>(); for (Entry<Column, NotificationType> entry : jco.getObservedColumns().entrySet()) { switch (entry.getValue()) { case STRONG: <START> strongColumns = strongColumnsBuilder.add(entry.getKey()).build(); <END> break; case WEAK: weakColumns = weakColumnsBuilder.add(entry.getKey()).build(); break; default: throw new IllegalStateException("Unknown notification type " + entry.getValue()); } } return new RegisteredObservers() { @Override public Observers getObservers(Environment env) { return new ObserversV2(env, jco, strongColumns, weakColumns); } @Override public ImmutableSet<Column> getObservedColumns(NotificationType nt) { switch (nt) { case STRONG: return strongColumns; case WEAK: return weakColumns; default: throw new IllegalArgumentException("Unknown notification type " + nt); } } }; }</code><technical_language>Building map for iteration of loop expensive. I suggest adding in loop building map loop</technical_language>

Target:
public RegisteredObservers load(CuratorFramework curator) throws Exception { byte[] data; try { data = curator.getData().forPath(CONFIG_FLUO_OBSERVERS2); } catch (NoNodeException nne) { return null; } String json = new String(data, UTF_8); JsonObservers jco = new Gson().fromJson(json, JsonObservers.class); ImmutableSet.Builder<Column> weakColumnsBuilder = new ImmutableSet.Builder<Column>(); ImmutableSet.Builder<Column> strongColumnsBuilder = new ImmutableSet.Builder<Column>(); for (Entry<Column, NotificationType> entry : jco.getObservedColumns().entrySet()) { switch (entry.getValue()) { case STRONG: strongColumnsBuilder.add(entry.getKey()); break; case WEAK: weakColumnsBuilder.add(entry.getKey()); break; default: throw new IllegalStateException("Unknown notification type " + entry.getValue()); } } strongColumns = strongColumnsBuilder.build(); weakColumns = weakColumnsBuilder.build(); return new RegisteredObservers() { @Override public Observers getObservers(Environment env) { return new ObserversV2(env, jco, strongColumns, weakColumns); } @Override public Set<Column> getObservedColumns(NotificationType nt) { switch (nt) { case STRONG: return strongColumns; case WEAK: return weakColumns; default: throw new IllegalArgumentException("Unknown notification type " + nt); } } }; }
Source:
<code>public ParsedConstraints loadConstraints(Project aProject) throws IOException, ParseException { ParsedConstraints merged = null; for (ConstraintSet set : listConstraintSets(aProject)) { String script = readConstrainSet(set); ConstraintsGrammar parser = new ConstraintsGrammar(new StringReader(script)); Parse p = parser.Parse(); ParsedConstraints constraints = p.accept(new ParserVisitor()); if (merged == null) { merged = constraints; } else { for (Entry<String, String> e : constraints.getImports().entrySet()) { if (merged.getImports().containsKey(e.getKey()) && !e.getValue() .equalsIgnoreCase(merged.getImports().get(e.getKey()))) { <START> String errorMessage = "Conflict detected in imports for key \"" + <END> e.getKey() + "\", conflicting values are \"" + e.getValue() + "\" & \"" + merged.getImports().get(e.getKey()) + "\". Please contact Project Admin for correcting this. Constraints feature may not work." + "\nAborting Constraint rules merge!"; throw new ParseException(errorMessage); } } merged.getImports().putAll(constraints.getImports()); for (Scope scope : constraints.getScopes()) { Scope target = merged.getScopeByName(scope.getScopeName()); if (target == null) { merged.getScopes().add(scope); } else { target.getRules().addAll(scope.getRules()); } } } } return merged; }</code><technical_language>I changes improve situation. change this a String.format(...) call</technical_language>

Target:
public ParsedConstraints loadConstraints(Project aProject) throws IOException, ParseException { ParsedConstraints merged = null; for (ConstraintSet set : listConstraintSets(aProject)) { String script = readConstrainSet(set); ConstraintsGrammar parser = new ConstraintsGrammar(new StringReader(script)); Parse p = parser.Parse(); ParsedConstraints constraints = p.accept(new ParserVisitor()); if (merged == null) { merged = constraints; } else { for (Entry<String, String> e : constraints.getImports().entrySet()) { if (merged.getImports().containsKey(e.getKey()) && !e.getValue() .equalsIgnoreCase(merged.getImports().get(e.getKey()))) { String errorMessage = "Conflict detected in imports for key \"" + e.getKey() + "\", conflicting values are \"" + e.getValue() + "\" & \"" + merged.getImports().get(e.getKey()) + "\". Please contact Project Admin for correcting this." + "Constraints feature may not work." + "\nAborting Constraint rules merge!"; throw new ParseException(errorMessage); } } merged.getImports().putAll(constraints.getImports()); for (Scope scope : constraints.getScopes()) { Scope target = merged.getScopeByName(scope.getScopeName()); if (target == null) { merged.getScopes().add(scope); } else { target.getRules().addAll(scope.getRules()); } } } } return merged; }
Source:
<code>private int numCompletedParts(List<Part> parts) { int completedTotal = 0; <START> for (Part part : parts) { <END> if (part.getMd5() != null) completedTotal++; } return completedTotal; }</code><technical_language>val</technical_language>

Target:
private int numCompletedParts(List<Part> parts) { int completedTotal = 0; for (val part : parts) { if (part.getMd5() != null) { completedTotal++; } } return completedTotal; }
Source:
<code>public void saveConcept_shouldSetAuditInfoIfAnItemIsRemovedFromAnyOfItsChildCollections() throws Exception { <START> executeDataSet("org/openmrs/api/include/ConceptServiceTest-names.xml"); <END> Concept concept = conceptService.getConcept(3000); concept.addDescription(new ConceptDescription("some description",Context.getLocale())); Assert.assertNull(concept.getDateChanged()); Assert.assertNull(concept.getChangedBy()); Assert.assertFalse(concept.getSynonyms().isEmpty()); concept.removeName(concept.getSynonyms().iterator().next()); conceptService.saveConcept(concept); Assert.assertNotNull(concept.getDateChanged()); Assert.assertNotNull(concept.getChangedBy()); }</code><technical_language>do need insert this test data</technical_language>

Target:
public void saveConcept_shouldSetAuditInfoIfAnItemIsRemovedFromAnyOfItsChildCollections() throws Exception { Concept concept = conceptService.getConcept(3); Assert.assertNull(concept.getDateChanged()); Assert.assertNull(concept.getChangedBy()); Concept concept1= conceptService.getConcept(5); ConceptAnswer conceptanswer = new ConceptAnswer(concept1); concept.addAnswer(conceptanswer); conceptService.saveConcept(concept); Assert.assertNotNull(concept.getDateChanged()); Date date=concept.getDateChanged(); Assert.assertTrue(concept.removeAnswer(conceptanswer)); conceptService.saveConcept(concept); Assert.assertNotNull(concept.getDateChanged()); Date date1=concept.getDateChanged(); Assert.assertFalse(date.equals(date1)); Assert.assertNotNull(concept.getChangedBy()); }
Source:
<code>private static InternalTask createTask(Job userJob, JavaTask task) throws JobCreationException { InternalTask javaTask; if (task.getExecutableClassName() != null) { HashMap<String, byte[]> args = task.getSerializedArguments(); try { if (isForkingTask()) { javaTask = new InternalForkedScriptTask(new ScriptExecutableContainer( new TaskScript(new SimpleScript(task.getExecutableClassName(), JavaClassScriptEngineFactory.JAVA_CLASS_SCRIPT_ENGINE_NAME, new Serializable[] { args })))); javaTask.setForkEnvironment(task.getForkEnvironment()); <START> if (isRunAsMeTask()) { <END> task.setRunAsMe(true); javaTask.setRunAsMe(true); } } else { javaTask = new InternalScriptTask(new ScriptExecutableContainer( new TaskScript(new SimpleScript(task.getExecutableClassName(), JavaClassScriptEngineFactory.JAVA_CLASS_SCRIPT_ENGINE_NAME, new Serializable[] { args })))); } } catch (InvalidScriptException e) { throw new JobCreationException(e); } } else { String msg = "You must specify your own executable task class to be launched (in every task)!"; logger.info(msg); throw new JobCreationException(msg); } try { setTaskCommonProperties(userJob, task, javaTask); } catch (Exception e) { throw new JobCreationException(e); } return javaTask; }</code><technical_language>![MAJOR](<LINK_1> Refactor this code nest more 3 if/for/while/switch/try statements. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static InternalTask createTask(Job userJob, JavaTask task) throws JobCreationException { InternalTask javaTask; if (task.getExecutableClassName() != null) { HashMap<String, byte[]> args = task.getSerializedArguments(); try { if (isForkingTask()) { javaTask = new InternalForkedScriptTask(new ScriptExecutableContainer( new TaskScript(new SimpleScript(task.getExecutableClassName(), JavaClassScriptEngineFactory.JAVA_CLASS_SCRIPT_ENGINE_NAME, new Serializable[] { args })))); javaTask.setForkEnvironment(task.getForkEnvironment()); configureRunAsMe(task); } else { javaTask = new InternalScriptTask(new ScriptExecutableContainer( new TaskScript(new SimpleScript(task.getExecutableClassName(), JavaClassScriptEngineFactory.JAVA_CLASS_SCRIPT_ENGINE_NAME, new Serializable[] { args })))); } } catch (InvalidScriptException e) { throw new JobCreationException(e); } } else { String msg = "You must specify your own executable task class to be launched (in every task)!"; logger.info(msg); throw new JobCreationException(msg); } try { setTaskCommonProperties(userJob, task, javaTask); } catch (Exception e) { throw new JobCreationException(e); } return javaTask; }
Source:
<code>private void destroyClientTempEntities(AbstractMoveItemRequest removedRequest) { <START> removedRequest.getClientSideTempEntities().stream().filter(tempEntity -> tempEntity.exists()).forEach(EntityRef::destroy); <END> }</code><technical_language>I find original version easier read in this case</technical_language>

Target:
private void destroyClientTempEntities(AbstractMoveItemRequest removedRequest) { for (EntityRef tempEntity : removedRequest.getClientSideTempEntities()) { if (tempEntity.exists()) { tempEntity.destroy(); } } }
Source:
<code>private void compareNumberOfArguments(SuperTreeImpl superTree, Symbol superClassSymbol) { Optional<ClassTree> baseClassTree = getDeclarationTree(superClassSymbol); if (baseClassTree.isPresent()) { Optional<MethodDeclarationTree> baseClassConstructor = getConstructor(baseClassTree.get()); if (baseClassConstructor.isPresent()) { Integer nbParams = baseClassConstructor.get().parameterList().size(); int nbArguments = ((CallExpressionTree) superTree.getParent()).arguments().parameters().size(); if (nbArguments != nbParams) { String message = String.format(MESSAGE_SUPER_WITH_CORRECT_NUMBER_OF_ARGUMENTS, nbParams, nbParams == 1 ? "" : "s"); <START> addIssue(superTree, message); <END> } } } }</code><technical_language>@ivandalbosco add a secondary location signature of constructor of super class</technical_language>

Target:
private void compareNumberOfArguments(SuperTreeImpl superTree, Symbol superClassSymbol) { Optional<ClassTree> baseClassTree = getDeclarationTree(superClassSymbol); if (baseClassTree.isPresent()) { Optional<MethodDeclarationTree> baseClassConstructor = getConstructor(baseClassTree.get()); if (baseClassConstructor.isPresent()) { Integer nbParams = baseClassConstructor.get().parameterList().size(); int nbArguments = ((CallExpressionTree) superTree.getParent()).arguments().parameters().size(); if (nbArguments != nbParams) { String message = String.format(MESSAGE_SUPER_WITH_CORRECT_NUMBER_OF_ARGUMENTS, nbParams, nbParams == 1 ? "" : "s"); addIssue(CheckUtils.parent(superTree), message).secondary(baseClassConstructor.get().parameterClause()); } } } }
Source:
<code>public void setUpSuite() throws Exception { super.setUpSuite(); setUpScriptProject("ModelMembers"); setUpScriptProject(BUILDPATH_PRJ_0); setUpScriptProject(BUILDPATH_PRJ_1); setUpScriptProject("p1"); setUpScriptProject("p2"); deleteProject("P"); <START> Locale.setDefault(Locale.US); <END> }</code><technical_language>break some other tests</technical_language>

Target:
public void setUpSuite() throws Exception { super.setUpSuite(); setUpScriptProject("ModelMembers"); setUpScriptProject(BUILDPATH_PRJ_0); setUpScriptProject(BUILDPATH_PRJ_1); setUpScriptProject("p1"); setUpScriptProject("p2"); deleteProject("P"); }
Source:
<code>private boolean isInterestingContainer(TaskContainerDelta delta) { if (delta.getElement() instanceof ITask) { ITask task = (ITask) delta.getElement(); boolean isProperKind = delta.getKind() == Kind.CONTENT || delta.getKind() == Kind.ADDED; <START> boolean isReviewConnector = getConnectorFromTask(task) instanceof GerritConnector; <END> return isProperKind && isReviewConnector; } return false; }</code><technical_language>Check for ReviewsConnector instead of GerritConnector</technical_language>

Target:
private boolean isInterestingContainer(TaskContainerDelta delta) { if (delta.getElement() instanceof ITask) { ITask task = (ITask) delta.getElement(); boolean isProperKind = delta.getKind() == Kind.CONTENT || delta.getKind() == Kind.ADDED; boolean isReviewConnector = getConnectorFromTask(task) instanceof ReviewsConnector; return isProperKind && isReviewConnector; } return false; }
Source:
<code>private boolean canDeleteSegment(PBDSegment segment) throws IOException { for (ReadCursor cursor : m_readCursors.values()) { if (cursor.m_segment != null && (cursor.m_segment.segmentId() >= segment.segmentId())) { PBDSegmentReader segmentReader = segment.getReader(cursor.m_cursorId); <START> if (cursor.m_segment.segmentId() == segment.segmentId()) { END> if (segmentReader == null) segmentReader = segment.openForRead(cursor.m_cursorId); } if (segmentReader != null) { if (!segmentReader.allReadAndDiscarded()) return false; } } else { return false; } } return true; }</code><technical_language>Is this nested IF check necessary? I "cursor.m_segment.segmentId() == segment.segmentId()" "segmentReader == null" true if cursor.m_segment equals segment, a segmentReader in m_readCursors in m_closedCursors, segmentReader returned getReader() null in this case</technical_language>

Target:
private boolean canDeleteSegment(PBDSegment segment) throws IOException { for (ReadCursor cursor : m_readCursors.values()) { if (cursor.m_segment != null && (cursor.m_segment.segmentId() >= segment.segmentId())) { PBDSegmentReader segmentReader = segment.getReader(cursor.m_cursorId); if (segmentReader == null) { assert(cursor.m_segment.segmentId() == segment.segmentId()); segmentReader = segment.openForRead(cursor.m_cursorId); } if (!segmentReader.allReadAndDiscarded()) return false; } else { return false; } } return true; }
Source:
<code>protected AbstractControllerService(final ProcessType processType, final RunningModeControl runningModeControl, final ConfigurationPersister configurationPersister, final ControlledProcessState processState, final ResourceDefinition rootResourceDefinition, final OperationStepHandler prepareStep, final ExpressionResolver expressionResolver, final ManagedAuditLogger auditLogger, final DelegatingConfigurableAuthorizer authorizer, final BootErrorCollector bootErrorCollector) { this(processType, runningModeControl, configurationPersister, processState, rootResourceDefinition, null, <START> prepareStep, expressionResolver, auditLogger, authorizer, bootErrorCollector); <END> }</code><technical_language>is this method (new param) necessary? existing constructor create BootErrorCollector itself? I missed I place a BootErrorCollector constructed a ref object needed code constructed it</technical_language>

Target:
protected AbstractControllerService(final ProcessType processType, final RunningModeControl runningModeControl, final ConfigurationPersister configurationPersister, final ControlledProcessState processState, final ResourceDefinition rootResourceDefinition, final OperationStepHandler prepareStep, final ExpressionResolver expressionResolver, final ManagedAuditLogger auditLogger, final DelegatingConfigurableAuthorizer authorizer, final BootErrorCollector bootErrorCollector) { this(processType, runningModeControl, configurationPersister, processState, rootResourceDefinition, null, prepareStep, expressionResolver, auditLogger, authorizer); }
Source:
<code>public void withOdbc(final Command command, final String name) { withDependencies( "Preparing " + name, "Using " + name, new Dependency[] { <START> Dependency.cranPackage("odbc", "1.1.5", true) <END> }, true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); }</code><technical_language>add this master list of package dependencies in admin guide</technical_language>

Target:
public void withOdbc(final Command command, final String name) { withDependencies( "Preparing " + name, "Using " + name, new Dependency[] { Dependency.cranPackage("odbc", "1.1.5") }, true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); }
Source:
<code>public void convertAndAdd(final CommonProfile profile, final AttributeLocation attributeLocation, final String name, final Object value) { if (value != null) { final Object convertedValue; final AttributeConverter<? extends Object> converter = this.converters.get(name); if (converter != null) { convertedValue = converter.convert(value); if (convertedValue != null) { logger.debug("converted to => key: / value: / {}", name, convertedValue, convertedValue.getClass()); } } else { convertedValue = value; logger.debug("no conversion => key: / value: / {}", name, convertedValue, convertedValue.getClass()); } switch (attributeLocation) { case PROFILE_ATTRIBUTE: profile.addAttribute(name, convertedValue); break; case AUTHENTICATION_ATTRIBUTE: profile.addAuthenticationAttribute(name, convertedValue); break; default: <START> logger.debug("Unsupported attribute location {}.", attributeLocation); <END> break; } } }</code><technical_language>I reach this default case. remove PROFILE_ATTRIBUTE case default</technical_language>

Target:
public void convertAndAdd(final CommonProfile profile, final AttributeLocation attributeLocation, final String name, final Object value) { if (value != null) { final Object convertedValue; final AttributeConverter<? extends Object> converter = this.converters.get(name); if (converter != null) { convertedValue = converter.convert(value); if (convertedValue != null) { logger.debug("converted to => key: / value: / {}", name, convertedValue, convertedValue.getClass()); } } else { convertedValue = value; logger.debug("no conversion => key: / value: / {}", name, convertedValue, convertedValue.getClass()); } if (attributeLocation.equals(AUTHENTICATION_ATTRIBUTE)) { profile.addAuthenticationAttribute(name, convertedValue); } else { profile.addAttribute(name, convertedValue); } } }
Source:
<code>public void run() { log.info("Starting v2 pipeline template source to artifact migration"); Predicate<Pipeline> hasV2TemplateSource = p -> { <START> Map<String, Object> template = (Map<String, Object>) p.getOrDefault("template", null); <END> if (template == null) { return false; } String schema = (String) p.getOrDefault("schema", ""); return schema.equals("v2") && isTemplateSource(template) && StringUtils.isNotEmpty((String) template.getOrDefault("source", "")); }; pipelineDAO.all().stream() .filter(hasV2TemplateSource) .forEach(pipeline -> migrate(pipelineDAO, pipeline)); }</code><technical_language>nit: getOrDefault(key, null) is get(key)</technical_language>

Target:
public void run() { log.info("Starting v2 pipeline template source to artifact migration"); Predicate<Pipeline> hasV2TemplateSource = p -> { Map<String, Object> template = (Map<String, Object>) p.get("template"); if (template == null) { return false; } String schema = (String) p.getOrDefault("schema", ""); return schema.equals("v2") && isTemplateSource(template) && StringUtils.isNotEmpty((String) template.getOrDefault("source", "")); }; pipelineDAO.all().stream() .filter(hasV2TemplateSource) .forEach(pipeline -> migrate(pipelineDAO, pipeline)); }
Source:
<code>public void testSyncInOut() throws Exception { String routeId = "testSyncInOnlyExceptionRoute"; RouteBuilder builder = new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId(routeId) .setBody(simple("${body.getParameter(\"request\")}")) .to("mock:result"); } }; context.addRoutes(builder); try { <START> ServiceRegistry.get().register("GlobalCamelService", context); <END> String expectedBody = "helloRequest"; resultEndpoint.expectedBodiesReceived(expectedBody); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter("camel-endpoint-id", "start"); workItem.setParameter("request", expectedBody); TestWorkItemManager manager = new TestWorkItemManager(); AbstractCamelWorkItemHandler handler = new InOutCamelWorkItemHandler(); handler.executeWorkItem(workItem, manager); assertThat(manager.getResults().size(), equalTo(1)); resultEndpoint.assertIsSatisfied(); } finally { context.removeRoute(routeId); } }</code><technical_language>again.</technical_language>

Target:
public void testSyncInOut() throws Exception { String routeId = "testSyncInOnlyExceptionRoute"; RouteBuilder builder = new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId(routeId) .setBody(simple("${body.getParameter(\"Request\")}")) .to("mock:result"); } }; context.addRoutes(builder); try { ServiceRegistry.get().register(JBPMConstants.GLOBAL_CAMEL_CONTEXT_SERVICE_KEY, context); String expectedBody = "helloRequest"; resultEndpoint.expectedBodiesReceived(expectedBody); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter(JBPMConstants.CAMEL_ENDPOINT_ID_WI_PARAM, "start"); workItem.setParameter("Request", expectedBody); TestWorkItemManager manager = new TestWorkItemManager(); AbstractCamelWorkItemHandler handler = new InOutCamelWorkItemHandler(); handler.executeWorkItem(workItem, manager); assertThat(manager.getResults().size(), equalTo(1)); resultEndpoint.assertIsSatisfied(); } finally { context.removeRoute(routeId); } }