auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void testGetRecoveryCourseForInstructor() { ______TS("success: instructor with deleted course"); InstructorAttributes instructor = dataBundle.instructors.get("instructor1OfCourse3"); CourseAttributes course = coursesLogic.getRecoveryCourseForInstructor(instructor); assertNotNull(course); ______TS("boundary: instructor without any courses"); instructor = dataBundle.instructors.get("instructor5"); course = coursesLogic.getRecoveryCourseForInstructor(instructor); assertNull(course); ______TS("Null parameter"); try { coursesLogic.getRecoveryCourseForInstructor(null); signalFailureToDetectException(); } catch (AssertionError e) { assertEquals(Const.StatusCodes.DBLEVEL_NULL_INPUT, e.getMessage()); } }

Target:
private void testGetRecoveryCourseForInstructor() { ______TS("success: instructor with deleted course"); InstructorAttributes instructor = dataBundle.instructors.get("instructor1OfCourse3"); CourseAttributes course = coursesLogic.getRecoveryCourseForInstructor(instructor); assertNotNull(course); ______TS("boundary: instructor without any deleted courses"); instructor = dataBundle.instructors.get("instructor5"); course = coursesLogic.getRecoveryCourseForInstructor(instructor); assertNull(course); ______TS("Null parameter"); try { coursesLogic.getRecoveryCourseForInstructor(null); signalFailureToDetectException(); } catch (AssertionError e) { assertEquals(Const.StatusCodes.DBLEVEL_NULL_INPUT, e.getMessage()); } }
Source:
public void testJobQueries(){ List<TaskExecution> expectedTaskExecutionList = new ArrayList<TaskExecution>(2); expectedTaskExecutionList.add(TestVerifierUtils.createSampleTaskExecutionNoArg()); expectedTaskExecutionList.add(TestVerifierUtils.createSampleTaskExecutionNoArg()); for (TaskExecution expectedTaskExecution : expectedTaskExecutionList) { expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); } Set jobIds = new HashSet<Long>(2); jobIds.add(123L); jobIds.add(456L); this.dao.getBatchJobAssociations().put( expectedTaskExecutionList.get(0).getExecutionId(), jobIds); assertEquals(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()), this.dao.getTaskExecutionIdByJobExecutionId(123L)); assertEquals(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()), this.dao.getTaskExecutionIdByJobExecutionId(456L)); assertNull(this.dao.getTaskExecutionIdByJobExecutionId(789L)); }

Target:
public void testJobQueries(){ List<TaskExecution> expectedTaskExecutionList = new ArrayList<>(2); expectedTaskExecutionList.add(TestVerifierUtils.createSampleTaskExecutionNoArg()); expectedTaskExecutionList.add(TestVerifierUtils.createSampleTaskExecutionNoArg()); for (TaskExecution expectedTaskExecution : expectedTaskExecutionList) { expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); } Set jobIds = new HashSet<Long>(2); jobIds.add(123L); jobIds.add(456L); this.dao.getBatchJobAssociations().put( expectedTaskExecutionList.get(0).getExecutionId(), jobIds); assertEquals(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()), this.dao.getTaskExecutionIdByJobExecutionId(123L)); assertEquals(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()), this.dao.getTaskExecutionIdByJobExecutionId(456L)); assertNull(this.dao.getTaskExecutionIdByJobExecutionId(789L)); }
Source:
void removeTokenCacheItem(final TokenCacheItem tokenCacheItem, final String resource) throws AuthenticationException { CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_DELETE); cacheEvent.setRequestId(mAuthRequest.getTelemetryRequestId()); Telemetry.getInstance().startEvent(mAuthRequest.getTelemetryRequestId(), EventStrings.TOKEN_CACHE_DELETE); final List<String> keys; final TokenEntryType tokenEntryType = tokenCacheItem.getTokenEntryType(); switch (tokenEntryType) { case REGULAR_TOKEN_ENTRY : cacheEvent.setTokenTypeRT(true); Logger.v(TAG, "Regular RT was used to get access token, remove entries " + "for regular RT entries."); keys = getKeyListToRemoveForRT(tokenCacheItem); break; case MRRT_TOKEN_ENTRY : cacheEvent.setTokenTypeMRRT(true); Logger.v(TAG, "MRRT was used to get access token, remove entries for both " + "MRRT entries and regular RT entries."); keys = getKeyListToRemoveForMRRT(tokenCacheItem); final TokenCacheItem regularRTItem = new TokenCacheItem(tokenCacheItem); regularRTItem.setResource(resource); keys.addAll(getKeyListToRemoveForRT(regularRTItem)); break; case FRT_TOKEN_ENTRY : cacheEvent.setTokenTypeFRT(true); Logger.v(TAG, "FRT was used to get access token, remove entries for " + "FRT entries."); keys = getKeyListToRemoveForFRT(tokenCacheItem); break; default : throw new AuthenticationException(ADALError.INVALID_TOKEN_CACHE_ITEM); } for (final String key : keys) { mTokenCacheStore.removeItem(key); } Telemetry.getInstance().stopEvent(mAuthRequest.getTelemetryRequestId(), cacheEvent, EventStrings.TOKEN_CACHE_DELETE); }

Target:
void removeTokenCacheItem(final TokenCacheItem tokenCacheItem, final String resource) throws AuthenticationException { final CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_DELETE); cacheEvent.setRequestId(mTelemetryRequestId); Telemetry.getInstance().startEvent(mTelemetryRequestId, EventStrings.TOKEN_CACHE_DELETE); final List<String> keys; final TokenEntryType tokenEntryType = tokenCacheItem.getTokenEntryType(); switch (tokenEntryType) { case REGULAR_TOKEN_ENTRY : cacheEvent.setTokenTypeRT(true); Logger.v(TAG, "Regular RT was used to get access token, remove entries " + "for regular RT entries."); keys = getKeyListToRemoveForRT(tokenCacheItem); break; case MRRT_TOKEN_ENTRY : cacheEvent.setTokenTypeMRRT(true); cacheEvent.setTokenTypeRT(true); Logger.v(TAG, "MRRT was used to get access token, remove entries for both " + "MRRT entries and regular RT entries."); keys = getKeyListToRemoveForMRRT(tokenCacheItem); final TokenCacheItem regularRTItem = new TokenCacheItem(tokenCacheItem); regularRTItem.setResource(resource); keys.addAll(getKeyListToRemoveForRT(regularRTItem)); break; case FRT_TOKEN_ENTRY : cacheEvent.setTokenTypeFRT(true); Logger.v(TAG, "FRT was used to get access token, remove entries for " + "FRT entries."); keys = getKeyListToRemoveForFRT(tokenCacheItem); break; default : throw new AuthenticationException(ADALError.INVALID_TOKEN_CACHE_ITEM); } for (final String key : keys) { mTokenCacheStore.removeItem(key); } Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_DELETE); }
Source:
private void writeAddress(VmDevice device) { if (!device.getAddress().isEmpty()) { writeAddress(StringMapUtils.string2Map(device.getAddress())); } }

Target:
private void writeAddress(VmDevice device) { writeAddress(StringMapUtils.string2Map(device.getAddress())); }
Source:
private Champ insertIntoPrefix(final int index, final ByteArrayWrapper key, final MaybeMultihash val) { final HashPrefixPayload[] src = this.contents; final HashPrefixPayload[] result = new HashPrefixPayload[src.length]; System.arraycopy(src, 0, result, 0, src.length); KeyElement[] prefix = new KeyElement[src[index].mappings.length + 1]; System.arraycopy(src[index].mappings, 0, prefix, 0, src[index].mappings.length); prefix[prefix.length - 1] = new KeyElement(key, val); Arrays.sort(prefix, Comparator.comparing(m -> m.key)); result[index] = new HashPrefixPayload(prefix, null); return new Champ(dataMap, nodeMap, result); }

Target:
private Champ insertIntoPrefix(final int index, final ByteArrayWrapper key, final MaybeMultihash val) { final HashPrefixPayload[] src = this.contents; final HashPrefixPayload[] result = Arrays.copyOf(src, src.length); KeyElement[] prefix = new KeyElement[src[index].mappings.length + 1]; System.arraycopy(src[index].mappings, 0, prefix, 0, src[index].mappings.length); prefix[prefix.length - 1] = new KeyElement(key, val); Arrays.sort(prefix, Comparator.comparing(m -> m.key)); result[index] = new HashPrefixPayload(prefix); return new Champ(dataMap, nodeMap, result); }
Source:
public void queueLogin(Player player) { if (player.getState() == EntityState.NEW && !logins.contains(player)) { logins.offer(player); } }

Target:
public void queueLogin(Player player) { if (player.getState() == EntityState.NEW && !logins.contains(player)) { logins.add(player); } }
Source:
public final void deliverResponse(final Exchange exchange, final Response response) { if (response == null) { throw new NullPointerException("Response must not be null"); } else if (exchange == null) { throw new NullPointerException("Exchange must not be null"); } else if (exchange.getRequest() == null) { throw new IllegalArgumentException("Exchange does not contain request"); } else { boolean processed = preDeliverResponse(exchange, response); if (!processed && exchange.getRequest().getResponse() == null) { exchange.getRequest().setResponse(response); } } }

Target:
public final void deliverResponse(final Exchange exchange, final Response response) { if (response == null) { throw new NullPointerException("Response must not be null"); } else if (exchange == null) { throw new NullPointerException("Exchange must not be null"); } else if (exchange.getRequest() == null) { throw new IllegalArgumentException("Exchange does not contain request"); } else { boolean processed = preDeliverResponse(exchange, response); if (!processed) { exchange.getRequest().setResponse(response); } } }
Source:
public static void verifyParallelism(ExecutionEnvironment env, int expectedParallelism) { Optimizer compiler = new Optimizer(null, new DefaultCostEstimator(), new Configuration()); OptimizedPlan optimizedPlan = compiler.compile(env.createProgramPlan()); List<PlanNode> queue = new ArrayList<>(); queue.addAll(optimizedPlan.getDataSinks()); while (queue.size() > 0) { PlanNode node = queue.remove(queue.size() - 1); assertTrue("Wrong parallelism for " + node.toString(), node.getParallelism() <= expectedParallelism); for (Channel channel : node.getInputs()) { queue.add(channel.getSource()); } } }

Target:
public static void verifyParallelism(ExecutionEnvironment env, int expectedParallelism) { env.setParallelism(2 * expectedParallelism); Optimizer compiler = new Optimizer(null, new DefaultCostEstimator(), new Configuration()); OptimizedPlan optimizedPlan = compiler.compile(env.createProgramPlan()); List<PlanNode> queue = new ArrayList<>(); queue.addAll(optimizedPlan.getDataSinks()); while (queue.size() > 0) { PlanNode node = queue.remove(queue.size() - 1); assertTrue("Wrong parallelism for " + node.toString(), node.getParallelism() <= expectedParallelism); for (Channel channel : node.getInputs()) { queue.add(channel.getSource()); } } }
Source:
public static <S,D> DocumentStream<D> map(final DocumentStream<S> source,final Function<S,D> map) { return new DocumentStreamMapper<S,D>(source,map); }

Target:
static <S,D> DocumentStream<D> map(final DocumentStream<S> source,final Function<S,D> map) { if(source instanceof RewindableDocumentStream) return new RewindableDocumentStream.RewindableDocumentStreamMapper<S,D>((RewindableDocumentStream<S>)source,map); else return new DocumentStreamMapper<S,D>(source,map); }
Source:
protected GroupSetProvider(GroupBackend groupBackend, @GerritServerConfig Config config, ThreadLocalRequestContext threadContext, ServerRequestContext serverCtx, String section, String subsection, String name) { RequestContext ctx = threadContext.setContext(serverCtx); String[] groupNames = config.getStringList(section, subsection, name); ImmutableSet.Builder<AccountGroup.UUID> builder = ImmutableSet.builder(); for (String n : groupNames) { GroupReference g = GroupBackends.findBestSuggestion(groupBackend, n); if (g == null) { log.warn("Group \"{}\" not in database, skipping.", n); } else { builder.add(g.getUUID()); } } groupIds = builder.build(); threadContext.setContext(ctx); }

Target:
protected GroupSetProvider(GroupBackend groupBackend, @GerritServerConfig Config config, ThreadLocalRequestContext threadContext, ServerRequestContext serverCtx, String section, String subsection, String name) { RequestContext ctx = threadContext.setContext(serverCtx); try { String[] groupNames = config.getStringList(section, subsection, name); ImmutableSet.Builder<AccountGroup.UUID> builder = ImmutableSet.builder(); for (String n : groupNames) { GroupReference g = GroupBackends.findBestSuggestion(groupBackend, n); if (g == null) { log.warn("Group \"{}\" not in database, skipping.", n); } else { builder.add(g.getUUID()); } } groupIds = builder.build(); } finally { threadContext.setContext(ctx); } }
Source:
protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.getPropertiesComponent().setLocation("ref:prop"); ((ElytronComponent) context.getComponent("elytron")).setSecurityDomainBuilder(getSecurityDomainBuilder()); ((ElytronComponent) context.getComponent("elytron")).setMechanismName(getMechanismName()); ((ElytronComponent) context.getComponent("elytron")).setElytronProvider(getElytronProvider()); return context; }

Target:
protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.getPropertiesComponent().setLocation("ref:prop"); context.getComponent("elytron", ElytronComponent.class).setSecurityDomainBuilder(getSecurityDomainBuilder()); context.getComponent("elytron", ElytronComponent.class).setMechanismName(getMechanismName()); context.getComponent("elytron", ElytronComponent.class).setElytronProvider(getElytronProvider()); return context; }
Source:
public void prepareRun(BatchSourceContext context) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); Job job = JobUtils.createInstance(); Configuration conf = job.getConfiguration(); conf.set(HiveConf.ConfVars.METASTOREURIS.varname, config.metaStoreURI); if (UserGroupInformation.isSecurityEnabled()) { conf.set(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL.varname, "true"); conf.set("hive.metastore.token.signature", HiveAuthFactory.HS2_CLIENT_TOKEN); } HCatInputFormat.setInput(conf, config.dbName, config.tableName, config.partitions); HCatSchema hCatSchema = HCatInputFormat.getTableSchema(conf); if (config.schema != null) { hCatSchema = HiveSchemaConverter.toHiveSchema(Schema.parseJson(config.schema), hCatSchema); HCatInputFormat.setOutputSchema(job, hCatSchema); } HiveSchemaStore.storeHiveSchema(context, config.dbName, config.tableName, hCatSchema); context.setInput(Input.of(config.referenceName, new SourceInputFormatProvider(HCatInputFormat.class, conf))); } finally { Thread.currentThread().setContextClassLoader(classLoader); } }

Target:
public void prepareRun(BatchSourceContext context) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { Job job = JobUtils.createInstance(); Configuration conf = job.getConfiguration(); conf.set(HiveConf.ConfVars.METASTOREURIS.varname, config.metaStoreURI); if (UserGroupInformation.isSecurityEnabled()) { conf.set(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL.varname, "true"); conf.set("hive.metastore.token.signature", HiveAuthFactory.HS2_CLIENT_TOKEN); } HCatInputFormat.setInput(conf, config.dbName, config.tableName, config.partitions); HCatSchema hCatSchema = HCatInputFormat.getTableSchema(conf); if (config.schema != null) { hCatSchema = HiveSchemaConverter.toHiveSchema(Schema.parseJson(config.schema), hCatSchema); HCatInputFormat.setOutputSchema(job, hCatSchema); } HiveSchemaStore.storeHiveSchema(context, config.dbName, config.tableName, hCatSchema); context.setInput(Input.of(config.referenceName, new SourceInputFormatProvider(HCatInputFormat.class, conf))); } finally { Thread.currentThread().setContextClassLoader(classLoader); } }
Source:
public List<Alert> getExampleAlerts() { List<Alert> alerts = new ArrayList<Alert>(); alerts.add( buildAlert( new Result( "ExampleLibrary", "x.y.z", Collections.<String, Set<String>>emptyMap(), null), "") .build()); return alerts; }

Target:
public List<Alert> getExampleAlerts() { List<Alert> alerts = new ArrayList<Alert>(); alerts.add( buildAlert(new Result("ExampleLibrary", "x.y.z", Collections.emptyMap(), null), "") .build()); return alerts; }
Source:
JsonIterator getNextLineIterator() { if (lineIterator != null) { lineIterator = null; } final JsonIterator iterator = resultIterator.next(); return iterator; }

Target:
private JsonIterator getNextLineIterator() { if (lineIterator != null) { lineIterator = null; } final JsonIterator iterator = resultIterator.next(); return iterator; }
Source:
public E previous() { E e = iterator.previous(); lastRet = ObservableArrayList.this.list.indexOf(e); return e; }

Target:
public E previous() { final E e = iterator.previous(); lastRet = ObservableArrayList.this.list.indexOf(e); return e; }
Source:
public boolean visitMethodInvocation(MethodInvocation node) { if (!hasRuntimePermissionAnnotation) { return super.visitMethodInvocation(node); } if (!"onRequestPermissionsResult".equals(node.astName().astValue())) { return super.visitMethodInvocation(node); } if (node.astOperand() instanceof VariableReference) { VariableReference ref = (VariableReference) node.astOperand(); if (generatedClassName.equals(ref.astIdentifier().astValue())) { hasOnRequestPermissionResultCall = true; } } return super.visitMethodInvocation(node); }

Target:
public boolean visitMethodInvocation(MethodInvocation node) { if (!hasRuntimePermissionAnnotation || hasOnRequestPermissionResultCall) { return super.visitMethodInvocation(node); } if (!"onRequestPermissionsResult".equals(node.astName().astValue())) { return super.visitMethodInvocation(node); } if (node.astOperand() instanceof VariableReference) { VariableReference ref = (VariableReference) node.astOperand(); if (generatedClassName.equals(ref.astIdentifier().astValue())) { hasOnRequestPermissionResultCall = true; } } return super.visitMethodInvocation(node); }
Source:
public void retryCustomConfirmation(String email) throws AppException { Util.checkEmpty(email, "email"); AtomicReference<AppException> error = new AtomicReference<>(null); call(TYPE_CALL_CUSTOM_CONFIRMATION_FUNCTION, new OsJNIVoidResultCallback(error), email); ResultHandler.handleResult(null, error); }

Target:
public void retryCustomConfirmation(String email) throws AppException { Util.checkEmpty(email, "email"); AtomicReference<AppException> error = new AtomicReference<>(null); call(TYPE_RETRY_CUSTOM_CONFIRMATION, new OsJNIVoidResultCallback(error), email); ResultHandler.handleResult(null, error); }
Source:
public GrayOutUnavailableLabelProvider(ViewerFilter filter) { this.display = Display.getDefault(); this.filter = filter; toDispose = new HashSet<Image>(); }

Target:
public GrayOutUnavailableLabelProvider(ViewerFilter filter) { this.display = PlatformUI.getWorkbench().getDisplay(); this.filter = filter; toDispose = new HashSet<Image>(); }
Source:
private void addSequence(Object generatorKey, String sequenceName, int initialValue) { Label generatorKeyLabel = DynamicLabel.label( generatorKey.toString() ); Map<String, Object> params = new HashMap<String, Object>(); params.put( INITIAL_VALUE_QUERY_PARAM, initialValue ); String query = "MERGE (n" + labels( sequenceName, generatorKeyLabel.name(), NodeLabel.SEQUENCE.name() ) + " ) ON CREATE SET n.`" + sequenceName + "` = {" + INITIAL_VALUE_QUERY_PARAM + "} RETURN n"; engine.execute( query, params ); }

Target:
private void addSequence(Object generatorKey, String sequenceName, int initialValue) { Label generatorKeyLabel = generatorKeyLabel( generatorKey ); String query = "MERGE (n" + labels( generatorKeyLabel.name(), NodeLabel.SEQUENCE.name() ) + " { " + SEQUENCE_NAME_PROPERTY + ": {" + SEQUENCE_NAME_QUERY_PARAM + "}} ) ON CREATE SET n." + CURRENT_VALUE_PROPERTY + " = {" + INITIAL_VALUE_QUERY_PARAM + "} RETURN n"; engine.execute( query, params( sequenceName, initialValue ) ); }
Source:
public long getCountUsersByName(String filter) throws DotDataException { filter = SQLUtil.sanitizeParameter(filter); DotConnect dotConnect = new DotConnect(); boolean isFilteredByName = UtilMethods.isSet(filter); filter = (isFilteredByName ? filter : ""); StringBuffer baseSql = new StringBuffer("select count(*) as count from user_ where companyid = ? and userid <> 'system' "); String userFullName = dotConnect.concat( new String[]{ "firstname", "' '", "lastname" } ); if( isFilteredByName ) { baseSql.append(" and lower("); baseSql.append(userFullName); baseSql.append(") like ?"); } baseSql.append(" and delete_in_progress = "); baseSql.append(DbConnectionFactory.getDBFalse()); String sql = baseSql.toString(); dotConnect.setSQL(sql); Logger.debug( UserFactoryLiferayImpl.class,"::getCountUsersByName -> query: " + dotConnect.getSQL() ); dotConnect.addParam(PublicCompanyFactory.getDefaultCompanyId()); if(isFilteredByName) { dotConnect.addParam("%"+filter.toLowerCase()+"%"); } return dotConnect.getInt("count"); }

Target:
public long getCountUsersByName(String filter) throws DotDataException { filter = SQLUtil.sanitizeParameter(filter); DotConnect dotConnect = new DotConnect(); boolean isFilteredByName = UtilMethods.isSet(filter); filter = (isFilteredByName ? filter : ""); StringBuilder baseSql = new StringBuilder("select count(*) as count from user_ where companyid = ? and userid <> 'system' "); String userFullName = dotConnect.concat( new String[]{ "firstname", "' '", "lastname" } ); if( isFilteredByName ) { baseSql.append(" and lower("); baseSql.append(userFullName); baseSql.append(") like ?"); } baseSql.append(" and delete_in_progress = "); baseSql.append(DbConnectionFactory.getDBFalse()); String sql = baseSql.toString(); dotConnect.setSQL(sql); Logger.debug( UserFactoryLiferayImpl.class,"::getCountUsersByName -> query: " + dotConnect.getSQL() ); dotConnect.addParam(PublicCompanyFactory.getDefaultCompanyId()); if(isFilteredByName) { dotConnect.addParam("%"+filter.toLowerCase()+"%"); } return dotConnect.getInt("count"); }
Source:
public void testSetUnaryTestsWhenUnaryTestsIsNull() { final ItemDefinition wb = mock(ItemDefinition.class); final UnaryTests wbAllowedValues = mock(UnaryTests.class); final org.kie.dmn.model.api.ItemDefinition dmn = mock(org.kie.dmn.model.api.ItemDefinition.class); final org.kie.dmn.model.api.UnaryTests dmnAllowedValues = null; when(dmn.getAllowedValues()).thenReturn(dmnAllowedValues); setUnaryTests(wb, dmn); verify(wb, never()).setAllowedValues(any()); verify(wbAllowedValues, never()).setParent(any()); }

Target:
public void testSetUnaryTestsWhenUnaryTestsIsNull() { final ItemDefinition wb = mock(ItemDefinition.class); final UnaryTests wbAllowedValues = mock(UnaryTests.class); final org.kie.dmn.model.api.ItemDefinition dmn = mock(org.kie.dmn.model.api.ItemDefinition.class); final org.kie.dmn.model.api.UnaryTests dmnAllowedValues = null; when(dmn.getAllowedValues()).thenReturn(dmnAllowedValues); setUnaryTests(wb, dmn); verify(wb, never()).setAllowedValues(wbAllowedValues); verify(wbAllowedValues, never()).setParent(wb); }
Source:
public PackFile(File packFile, int extensions) { this.packFile = new PackFileName(packFile); this.packLastModified = (int) (packFile.lastModified() >> 10); this.extensions = extensions; hash = System.identityHashCode(this) * 31; length = Long.MAX_VALUE; }

Target:
public PackFile(File packFile, int extensions) { this.packFileName = new PackFileName(packFile); this.packLastModified = (int) (packFileName.lastModified() >> 10); this.extensions = extensions; hash = System.identityHashCode(this) * 31; length = Long.MAX_VALUE; }
Source:
public BackendClusterEnabledFeaturesResource(ClusterResource parent, String clusterId) { this(); this.clusterId = clusterId; }

Target:
public BackendClusterEnabledFeaturesResource(ClusterResource parent, String clusterId) { super(ClusterFeature.class, org.ovirt.engine.core.common.businessentities.AdditionalFeature.class); this.clusterId = clusterId; }
Source:
public Integer call() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); final TProtocol streamProtocol = new TBinaryProtocol.Factory().getProtocol(new TIOStreamTransport(baos)); do { final Span span = queue.poll(5, TimeUnit.SECONDS); if (span != null) { baos.reset(); try { span.write(streamProtocol); final KeyedMessage<byte[], byte[]> message = new KeyedMessage<>("zipkin", baos.toByteArray()); producer.send(message); numProcessedSpans++; } catch (TException e) { LOGGER.log(Level.WARNING, "TException when writing span.", e); } } } while(!stop); return numProcessedSpans; }

Target:
public Integer call() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); final TProtocol streamProtocol = new TBinaryProtocol.Factory().getProtocol(new TIOStreamTransport(baos)); do { final Span span = queue.poll(5, TimeUnit.SECONDS); if (span == null) { continue; } baos.reset(); try { span.write(streamProtocol); final ProducerRecord<byte[], byte[]> message = new ProducerRecord<>("zipkin", baos.toByteArray()); producer.send(message); numProcessedSpans++; } catch (TException e) { LOGGER.log(Level.WARNING, "TException when writing span.", e); } } while (!stop); return numProcessedSpans; }
Source:
public static void register(final DataProviderRegistrator registrator) { registrator .asImmutable(BlockState.class) .create(Keys.IS_POWERED) .get(h -> h.get(AbstractButtonBlock.POWERED)) .set((h, v) -> h.with(AbstractButtonBlock.POWERED, v)) .supports(AbstractButtonBlock.class::isInstance); }

Target:
public static void register(final DataProviderRegistrator registrator) { registrator .asImmutable(BlockState.class) .create(Keys.IS_POWERED) .get(h -> h.get(AbstractButtonBlock.POWERED)) .set((h, v) -> h.with(AbstractButtonBlock.POWERED, v)) .supports(h -> h.getBlock() instanceof AbstractButtonBlock); }
Source:
public Expr apply(final List<Expr> args) { if (args.size() < 2 || args.size() > 4) { throw new IAE("'%s' must have 2 to 4 arguments", name()); } final Expr arg = args.get(0); if (args.stream().skip(1).allMatch(Expr::isLiteral)) { final PeriodGranularity granularity = getGranularity(args, ExprUtils.nilBindings()); class TimestampFloorExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { return ExprEval.of(granularity.bucketStart(new DateTime(arg.eval(bindings).asLong())).getMillis()); } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new TimestampFloorExpr(); } else { class TimestampFloorDynamicExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { final PeriodGranularity granularity = getGranularity(args, bindings); return ExprEval.of(granularity.bucketStart(new DateTime(arg.eval(bindings).asLong())).getMillis()); } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new TimestampFloorDynamicExpr(); } }

Target:
public Expr apply(final List<Expr> args) { if (args.size() < 2 || args.size() > 4) { throw new IAE("Function[%s] must have 2 to 4 arguments", name()); } if (args.stream().skip(1).allMatch(Expr::isLiteral)) { return new TimestampFloorExpr(args); } else { return new TimestampFloorDynamicExpr(args); } }
Source:
public static void testSetByte() { final byte[] destination = new byte[POSITIONS_PER_PAGE]; byte[] sourceBytes = new byte[POSITIONS_PER_PAGE]; RANDOM.nextBytes(sourceBytes); List<Byte> source = Bytes.asList(sourceBytes); testSequential( source, ARRAY_BYTE_INDEX_SCALE, destination, (bytes, index, value) -> setByte((byte[]) bytes, (int) index, (byte) value), (bytes, index) -> getByte((byte[]) bytes, (int) index)); source = new ArrayList<Byte>(Collections.nCopies(POSITIONS_PER_PAGE, (byte) 0)); testRandom( source, ARRAY_BYTE_INDEX_SCALE, destination, (bytes, index, value) -> setByte((byte[]) bytes, (int) index, (byte) value), (bytes, index) -> getByte((byte[]) bytes, (int) index)); }

Target:
public static void testSetByte() { byte[] source = new byte[POSITIONS_PER_PAGE]; ThreadLocalRandom.current().nextBytes(source); testSequential(Bytes.asList(source), ARRAY_BYTE_INDEX_SCALE, UncheckedByteArrays::setByteUnchecked, UncheckedByteArrays::getByteUnchecked); testRandom(Bytes.asList(source), ARRAY_BYTE_INDEX_SCALE, UncheckedByteArrays::setByteUnchecked, UncheckedByteArrays::getByteUnchecked); }
Source:
protected Vector<URL> filterResources(Vector<URL> urlList) { if (m_useResourceFiltering) { Vector<URL> newUrlList = new Vector<URL>(); Vector<URL> customUrlList = new Vector<URL>(); Enumeration<URL> elements = urlList.elements(); while (elements.hasMoreElements()) { URL resource = elements.nextElement(); newUrlList.add(resource); if (isUrlFromBundlePrefixes(resource)) { customUrlList.add(resource); } } if (!customUrlList.isEmpty()) { urlList = customUrlList; } else { urlList = newUrlList; } } return urlList; }

Target:
protected Vector<URL> filterResources(Vector<URL> urlList) { if (isUseResourceFilteringEnabled()) { Vector<URL> newUrlList = new Vector<URL>(); Vector<URL> customUrlList = new Vector<URL>(); Enumeration<URL> resources = urlList.elements(); while (resources != null && resources.hasMoreElements()) { URL resource = resources.nextElement(); newUrlList.add(resource); if (isUrlFromBundlePrefixes(resource)) { customUrlList.add(resource); } } if (!customUrlList.isEmpty()) { urlList = customUrlList; } else { urlList = newUrlList; } } return urlList; }
Source:
private String getValueForRegex(String replacement, Matcher matcher){ String value = replacement; for (String substitution : splitRegexBackReferences(replacement)) { int i = Integer.valueOf(substitution.substring(1)); String _replacement = matcher.groupCount() >= i && matcher.group(i) != null ? Matcher.quoteReplacement(matcher.group(i)) : ""; value = value.replaceFirst("\\" + substitution, _replacement); } return value.trim(); }

Target:
private String getValueForRegex(String replacement, Matcher matcher){ String value = replacement; for (String substitution : splitRegexBackReferences(replacement)) { int backreference = Integer.valueOf(substitution.substring(1)); String _replacement = matcher.groupCount() >= backreference && matcher.group(backreference) != null ? Matcher.quoteReplacement(matcher.group(backreference)) : ""; value = value.replaceFirst("\\" + substitution, _replacement); } return value.trim(); }
Source:
public void cleanup() { System.out.println("L="); for (int i = 0; i < numRows; ++i) { for (final VectorEntry valueEntry : parameterWorker.pull(i)) { System.out.print(" " + valueEntry.value()); } System.out.println(); } System.out.println("R="); for (int i = 0; i < numColumns; ++i) { for (final VectorEntry valueEntry : parameterWorker.pull(i)) { System.out.print(" " + valueEntry.value()); } System.out.println(); } workload.clear(); }

Target:
public void cleanup() { System.out.println("L="); for (int i = 1; i <= numRows; ++i) { for (final VectorEntry valueEntry : parameterWorker.pull(-i)) { System.out.print(" " + valueEntry.value()); } System.out.println(); } System.out.println("R'="); for (int i = 1; i <= numColumns; ++i) { for (final VectorEntry valueEntry : parameterWorker.pull(i)) { System.out.print(" " + valueEntry.value()); } System.out.println(); } workload.clear(); }
Source:
public List<TaskState> getTasksPaginated(final int offset, final int limit) { int _offset = 0; int _limit = getTasks().size(); if (offset > 0 && offset < _limit) _offset = offset; if (limit > 0 && limit < _limit) _limit = limit; if (_offset > _limit) { int tmp = _offset; _offset = _limit; _limit = tmp; } return getTasks().subList(_offset, _limit); }

Target:
public TaskStatesPage getTasksPaginated(final int offset, final int limit) { int total_size = getTasks().size(); PageBoundaries pb = sanitizeBoundaries(getTasks(), offset, limit); return new TaskStatesPage(getTasks().subList(pb.getOffset(), pb.getLimit()), total_size); }
Source:
public long getCountOfLoadedCommits() { return countOfLoadedCommits; }

Target:
long getCountOfLoadedCommits() { return countOfLoadedCommits; }
Source:
public void testDelete() throws InterruptedException { server.enqueue(response202WithHeader()); final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup); vmssAPI.delete(vmssname); assertSent(server, "DELETE", "/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/" + "Microsoft.Compute" + "/VirtualMachineScaleSets/jclouds-vmssname?api-version=2017-03-30"); }

Target:
public void testDelete() throws InterruptedException { server.enqueue(response202WithHeader()); final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup); assertNotNull(vmssAPI.delete(vmssname)); assertSent(server, "DELETE", "/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/" + "Microsoft.Compute" + "/VirtualMachineScaleSets/jclouds-vmssname?api-version=2017-03-30"); }
Source:
public boolean isCheckboxEnabled(String sampleName) { String checkboxId = format(CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE, sampleName); String checkboxLocator = format(" return seleniumWebDriverHelper .waitVisibilityAndGetAttribute(By.xpath(checkboxLocator), "aria-checked") .equals("true"); }

Target:
public boolean isCheckboxEnabled(String sampleName) { final String checkboxId = format(CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE, sampleName); final String checkboxLocator = format(" final String checkboxStateAttribute = "aria-checked"; return seleniumWebDriverHelper .waitVisibilityAndGetAttribute(By.xpath(checkboxLocator), checkboxStateAttribute) .equals("true"); }
Source:
private void addDefaultProperties(DelegatingResourceDescription description) { description.addProperty("uuid"); description.addProperty("radiologyOrder", Representation.REF); description.addProperty("reportDate"); description.addProperty("reportStatus"); description.addProperty("reportBody"); description.addProperty("principalResultsInterpreter", Representation.REF); description.addProperty("display"); }

Target:
private void addDefaultProperties(DelegatingResourceDescription description) { description.addProperty("uuid"); description.addProperty("radiologyOrder", Representation.REF); description.addProperty("reportDate"); description.addProperty("principalResultsInterpreter", Representation.REF); description.addProperty("reportStatus"); description.addProperty("reportBody"); description.addProperty("display"); }
Source:
public void restrictedGroupAccessForbiddenTest() throws Exception { context.turnOffAuthorisationSystem(); EPerson memberRestrictGroup = EPersonBuilder.createEPerson(context) .withEmail("eperson1@mail.com") .withPassword("qwerty01") .build(); Group restrictGroup = GroupBuilder.createGroup(context) .addMember(memberRestrictGroup) .build(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1) .withName("Collection 1") .build(); Item itemRestrictedByGroup = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2011-11-13") .withAuthor("Smith, Donald") .withReaderGroup(restrictGroup) .build(); context.restoreAuthSystemState(); String tokenMemberRestrictedGroup = getAuthToken(memberRestrictGroup.getEmail(), "qwerty01"); getClient(tokenMemberRestrictedGroup).perform(get("/api/core/items/" + itemRestrictedByGroup.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", is(ItemMatcher.matchItemProperties(itemRestrictedByGroup)))); String tokenEPerson = getAuthToken(eperson.getEmail(), password); getClient(tokenEPerson).perform(get("/api/core/items/" + itemRestrictedByGroup.getID())) .andExpect(status().isForbidden()); }

Target:
public void restrictedGroupAccessForbiddenTest() throws Exception { context.turnOffAuthorisationSystem(); EPerson memberRestrictGroup = EPersonBuilder.createEPerson(context) .withEmail("eperson1@mail.com") .withPassword("qwerty01") .build(); Group restrictGroup = GroupBuilder.createGroup(context) .addMember(memberRestrictGroup) .build(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1) .withName("Collection 1") .build(); Item itemRestrictedByGroup = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2011-11-13") .withAuthor("Smith, Donald") .withReaderGroup(restrictGroup) .build(); context.restoreAuthSystemState(); String tokenMemberRestrictedGroup = getAuthToken(memberRestrictGroup.getEmail(), "qwerty01"); getClient(tokenMemberRestrictedGroup).perform(get("/api/core/items/" + itemRestrictedByGroup.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", is(ItemMatcher.matchItemProperties(itemRestrictedByGroup)))); String tokenEPerson = getAuthToken(eperson.getEmail(), password); getClient(tokenEPerson).perform(get("/api/core/items/" + itemRestrictedByGroup.getID())) .andExpect(status().isForbidden()); getClient().perform(get("/api/core/items/" + itemRestrictedByGroup.getID())) .andExpect(status().isUnauthorized()); }
Source:
public TmfModelResponse<List<TmfEventTableColumnDataModel>> fetchTree(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<TmfEventTableColumnDataModel> model = new ArrayList<>(); for (ITmfEventAspect<?> aspect : getTraceAspects(getTrace())) { long id = fAspectToIdMap.computeIfAbsent(aspect, a -> fAtomicLong.getAndIncrement()); fIdToAspectMap.putIfAbsent(id, aspect); model.add(new TmfEventTableColumnDataModel(id, -1, aspect.getName(), aspect.getHelpText(), aspect.isHiddenByDefault())); } return new TmfModelResponse<>(model, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }

Target:
public TmfModelResponse<List<TmfEventTableColumnDataModel>> fetchTree(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<TmfEventTableColumnDataModel> model = new ArrayList<>(); for (ITmfEventAspect<?> aspect : getTraceAspects(getTrace())) { synchronized (fAspectToIdMap) { long id = fAspectToIdMap.computeIfAbsent(aspect, a -> fAtomicLong.getAndIncrement()); fIdToAspectMap.putIfAbsent(id, aspect); model.add(new TmfEventTableColumnDataModel(id, -1, aspect.getName(), aspect.getHelpText(), aspect.isHiddenByDefault())); } } return new TmfModelResponse<>(model, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
private boolean isBuiltInCheckRequired(UpgradeCheck upgradeCheck, UpgradeType upgradeType) { if (upgradeType == null) { return true; } UpgradeCheckInfo annotation = upgradeCheck.getClass().getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return false; } UpgradeType[] upgradeTypes = annotation.required(); if (ArrayUtils.contains(upgradeTypes, upgradeType)) { return true; } return false; }

Target:
private boolean isBuiltInCheckRequired(UpgradeCheck upgradeCheck, UpgradeType upgradeType) { if (upgradeType == null) { return true; } UpgradeCheckInfo annotation = upgradeCheck.getClass().getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return false; } UpgradeType[] upgradeTypes = annotation.required(); return ArrayUtils.contains(upgradeTypes, upgradeType); }
Source:
private void addDefaultGroup(DbSession dbSession, UserDto userDto) { String defaultGroupName = settings.getString(CoreProperties.CORE_DEFAULT_GROUP); if (defaultGroupName == null) { return; } String defOrgUuid = defaultOrganizationProvider.get().getUuid(); List<GroupDto> userGroups = dbClient.groupDao().selectByUserLogin(dbSession, userDto.getLogin()); if (userGroups.stream().anyMatch(g -> defOrgUuid.equals(g.getOrganizationUuid()) && g.getName().equals(defaultGroupName))) { return; } Optional<GroupDto> groupDto = dbClient.groupDao().selectByName(dbSession, defOrgUuid, defaultGroupName); if (!groupDto.isPresent()) { throw new ServerException(HttpURLConnection.HTTP_INTERNAL_ERROR, format("The default group '%s' for new users does not exist. Please update the general security settings to fix this issue.", defaultGroupName)); } dbClient.userGroupDao().insert(dbSession, new UserGroupDto().setUserId(userDto.getId()).setGroupId(groupDto.get().getId())); }

Target:
private void addDefaultGroup(DbSession dbSession, UserDto userDto) { String defaultGroupName = settings.getString(CoreProperties.CORE_DEFAULT_GROUP); if (defaultGroupName == null) { return; } String defOrgUuid = defaultOrganizationProvider.get().getUuid(); List<GroupDto> userGroups = dbClient.groupDao().selectByUserLogin(dbSession, userDto.getLogin()); if (isUserAlreadyMemberOfDefaultGroup(defaultGroupName, defOrgUuid, userGroups)) { return; } Optional<GroupDto> groupDto = dbClient.groupDao().selectByName(dbSession, defOrgUuid, defaultGroupName); if (!groupDto.isPresent()) { throw new ServerException(HttpURLConnection.HTTP_INTERNAL_ERROR, format("The default group '%s' for new users does not exist. Please update the general security settings to fix this issue.", defaultGroupName)); } dbClient.userGroupDao().insert(dbSession, new UserGroupDto().setUserId(userDto.getId()).setGroupId(groupDto.get().getId())); }
Source:
public void testGetWebhook() { for (String zone : api.getConfiguredZones()) { Group g = created.get(zone).get(0); WebhookApi webhookApi; boolean foundWebhook = false; for (ScalingPolicyResponse sp : g.getScalingPolicies()) { webhookApi = api.getWebhookApiForZoneAndGroupAndPolicy(zone, g.getId(), sp.getId()); WebhookResponse webhookList = webhookApi.list().first().get(); if (webhookList != null) { WebhookResponse webhookGet = webhookApi.get(webhookList.getId()); assertEquals(webhookList, webhookGet); foundWebhook = true; } } assertTrue(foundWebhook, "No webhooks were found, and some were expected"); } }

Target:
public void testGetWebhook() { for (String zone : api.getConfiguredZones()) { Group g = created.get(zone).get(0); WebhookApi webhookApi; boolean foundWebhook = false; for (ScalingPolicyResponse sp : g.getScalingPolicies()) { webhookApi = api.getWebhookApiForZoneAndGroupAndPolicy(zone, g.getId(), sp.getId()); WebhookResponse webhookResponse = webhookApi.list().first().get(); if (webhookResponse != null) { WebhookResponse webhookGet = webhookApi.get(webhookResponse.getId()); assertEquals(webhookResponse, webhookGet); foundWebhook = true; } } assertTrue(foundWebhook, "No webhooks were found, and some were expected"); } }
Source:
public @Nullable ITmfTreeDataProvider<? extends ITmfTreeDataModel> createProvider(ITmfTrace trace, String secondaryId) { ITmfTreeDataProvider<? extends ITmfTreeDataModel> provider = create(trace, secondaryId); if (provider != null) { return provider; } Collection<ITmfTrace> traces = TmfTraceManager.getTraceSet(trace); if (traces.size() > 1) { return TmfTreeXYCompositeDataProvider.create(traces, Objects.requireNonNull("FlameChart"), FlameChartDataProvider.ID, secondaryId); } return null; }

Target:
public @Nullable ITmfTreeDataProvider<? extends ITmfTreeDataModel> createProvider(ITmfTrace trace, String secondaryId) { ITmfTreeDataProvider<? extends ITmfTreeDataModel> provider = create(trace, secondaryId); if (provider != null) { return provider; } Collection<ITmfTrace> traces = TmfTraceManager.getTraceSet(trace); if (traces.size() > 1) { return TmfTreeXYCompositeDataProvider.create(traces, Objects.requireNonNull(Messages.FlameChartDataProvider_Title), FlameChartDataProvider.ID, secondaryId); } return null; }
Source:
public void start() { if (!consumerPollThread.isAlive()) { LOG.info("Starting KafkaConsumerProxy polling thread for system " + systemName + " " + this.toString()); consumerPollThread.start(); while (!isRunning) { try { consumerPollThreadStartLatch.await(3000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.info("Got InterruptedException", e); } } } else { LOG.debug("Tried to start an already started KafkaConsumerProxy (%s). Ignoring.", this.toString()); } }

Target:
public void start() { if (!consumerPollThread.isAlive()) { LOG.info("Starting KafkaConsumerProxy polling thread for " + this.toString()); consumerPollThread.start(); while (!isRunning && failureCause == null) { try { consumerPollThreadStartLatch.await(3000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.info("Ignoring InterruptedException while waiting for consumer poll thread to start.", e); } } } else { LOG.warn("Tried to start an already started KafkaConsumerProxy (%s). Ignoring.", this.toString()); } if (topicPartitionToSSP.size() == 0) { String msg = String.format("Cannot start KafkaConsumerProxy without any registered TopicPartitions for %s", systemName); LOG.error(msg); throw new SamzaException(msg); } }
Source:
public static String fileToBase64String(File isoFile) throws IOException { byte[] encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(isoFile)); return new String(encoded, com.cloud.utils.StringUtils.getPreferredCharset()); }

Target:
public static String fileToBase64String(File isoFile) throws IOException { byte[] encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(isoFile)); return new String(encoded, StandardCharsets.US_ASCII); }
Source:
public void testDocumentRemovedCommentEventListener() throws Exception { DocumentModel doc = doCreateADocWithComments(); assertNotNull(doc); List<Comment> comments = commentManager.getComments(session, doc.getId()); assertFalse(comments.isEmpty()); session.removeDocument(doc.getRef()); session.save(); if (TransactionHelper.isTransactionActiveOrMarkedRollback()) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } waitForAsyncExec(); DocumentModelList documents = session.query(String.format("Select * From Comment Where %s = '%s'", NXQL.ECM_ANCESTORID, doc.getId())); assertTrue(documents.isEmpty()); }

Target:
public void testDocumentRemovedCommentEventListener() throws Exception { DocumentModel doc = doCreateADocWithComments(); assertNotNull(doc); List<Comment> comments = commentManager.getComments(session, doc.getId()); assertFalse(comments.isEmpty()); session.removeDocument(doc.getRef()); session.save(); if (TransactionHelper.isTransactionActiveOrMarkedRollback()) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } waitForAsyncExec(); comments = commentManager.getComments(session, doc.getId()); assertTrue(comments.isEmpty()); }