auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static <T> Call<List<T>> emptyList() { <START> return (Call<List<T>>) CALL_EMPTY_LIST.clone(); <END> }</code><technical_language>I exact logic if Call.create(Collections.emptyList()) instead of clone, avoid extra static constant</technical_language>

Target:
public static <T> Call<List<T>> emptyList() { return Call.create(Collections.emptyList()); }
Source:
<code>public CompletableFuture<Long> tryReadLastAddConfirmed() { <START> CompletableFuture<Long> counter = new CompletableFuture<>(); <END> ReadLastConfirmedCallback callback = (int rc, long lastConfirmed, Object ctx) -> { SyncCallbackUtils.finish(rc, lastConfirmed, counter); }; asyncTryReadLastConfirmed(callback, counter); return counter; }</code><technical_language>change counter</technical_language>

Target:
public CompletableFuture<Long> tryReadLastAddConfirmed() { FutureReadLastConfirmed result = new FutureReadLastConfirmed(); asyncTryReadLastConfirmed(result, null); return result; }
Source:
<code>private void enforceTaskTTLs() { Instant startDeadline = ssm.getStoreTime().minus(taskTTL); long lastId = 0; <START> List<TaskAttemptSummary> expiredTasks = ssm.findTasksStartedBeforeWithStateAndType(TaskType.of(0), TaskStateCode.notDoneStates(), startDeadline, lastId, 100); <END> for (TaskAttemptSummary task : expiredTasks) { AttemptStateFlags stateFlags; try { stateFlags = ssm.getAttemptStateFlags(task.getAttemptId()); } catch (ResourceNotFoundException e) { logger.debug("Session Attempt not found, ignoring: {}", task, e); continue; } if (stateFlags.isCancelRequested()) { logger.debug("Session Attempt already canceled, ignoring: {}", task); continue; } logger.info("Task timed out, canceling Session Attempt: {}", task); ssm.requestCancelAttempt(task.getAttemptId()); } }</code><technical_language>Please double-check: task-generating tasks (e.g. loop>, td_for_each, etc.) timeout if of subtasks finish taskTTL seconds TaskStateCode.notDoneStates() includes PLANNED state tasks grouping-only tasks. This is intended, right</technical_language>

Target:
private void enforceTaskTTLs() { Instant startDeadline = ssm.getStoreTime().minus(taskTTL); List<TaskAttemptSummary> expiredTasks = ssm.findTasksStartedBeforeWithState(TaskStateCode.notDoneStates(), startDeadline, (long) 0, 100); Map<Long, List<TaskAttemptSummary>> attempts = expiredTasks.stream() .collect(groupingBy(TaskAttemptSummary::getAttemptId)); for (Map.Entry<Long, List<TaskAttemptSummary>> entry : attempts.entrySet()) { logger.info("Task(s) timed out, canceling Session Attempt: {}, tasks={}", entry.getKey(), entry.getValue()); boolean canceled = ssm.requestCancelAttempt(entry.getKey()); String taskIds = entry.getValue().stream().mapToLong(TaskAttemptSummary::getId).mapToObj(Long::toString).collect(joining(",")); if (canceled) { sendTimeoutNotification("Task execution timeout: " + taskIds, entry.getKey()); } } }
Source:
<code>public void doSubmit() { <START> if (!checkCanSubmit(IMessageProvider.ERROR)) { <END> return; } super.doSubmit(); }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
public void doSubmit() { if (!checkCanSubmit(IMessageProvider.ERROR)) return; super.doSubmit(); }
Source:
<code><START> public void testGetForVdsFilteredWithPermissions() { <END> storage_pool result = dao.get(vds, PRIVILEGED_USER_ID, true); assertGetResult(result); }</code><technical_language>s/get/getForVds/</technical_language>

Target:
public void testGetForVdsFilteredWithPermissions() { storage_pool result = dao.getForVds(vds, PRIVILEGED_USER_ID, true); assertGetResult(result); }
Source:
<code>public void testUpperCamelCase() throws IOException { String[] command = { inputFile.getPath() }; addExpectMsg(Messages.CLASS_NAME, 3, 7, "error"); addExpectMsg(Messages.CLASS_NAME, 7, 7, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 24, 8, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 25, 8, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 26, 8, "error"); addExpectMsg(Messages.ENUM_NAME, 42, 6, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 43, 8, "error"); addExpectMsg(Messages.ENUM_NAME, 46, 6, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 47, 8, "error"); addExpectMsg(Messages.ENUM_NAME, 50, 6, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 55, 8, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 63, 8, "error"); addExpectMsg(Messages.STRUCT_NAME, 72, 8, "error"); addExpectMsg(Messages.STRUCT_NAME, 76, 8, "error"); addExpectMsg(Messages.PROTOCOL_NAME, 90, 10, "error"); addExpectMsg(Messages.PROTOCOL_NAME, 94, 10, "error"); addExpectMsg(Messages.PROTOCOL_NAME, 98, 10, "error"); Tailor.main(command); for(String msg : outContent.toString().split(NEWLINE_REGEX)) { String truncatedMsg = msg.substring(msg.indexOf(inputFile.getName())); <START> assertTrue(expectedMessages.contains(truncatedMsg)); <END> } }</code><technical_language>need compare set of expected messages equal set of output lines ensure correctness. Currently if is output, this test pass</technical_language>

Target:
public void testUpperCamelCase() throws IOException { String[] command = { inputFile.getPath() }; addExpectedMsg(Messages.CLASS_NAME, 3, 7, "error"); addExpectedMsg(Messages.CLASS_NAME, 7, 7, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 24, 8, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 25, 8, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 26, 8, "error"); addExpectedMsg(Messages.ENUM_NAME, 42, 6, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 43, 8, "error"); addExpectedMsg(Messages.ENUM_NAME, 46, 6, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 47, 8, "error"); addExpectedMsg(Messages.ENUM_NAME, 50, 6, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 55, 8, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 63, 8, "error"); addExpectedMsg(Messages.STRUCT_NAME, 72, 8, "error"); addExpectedMsg(Messages.STRUCT_NAME, 76, 8, "error"); addExpectedMsg(Messages.PROTOCOL_NAME, 90, 10, "error"); addExpectedMsg(Messages.PROTOCOL_NAME, 94, 10, "error"); addExpectedMsg(Messages.PROTOCOL_NAME, 98, 10, "error"); Tailor.main(command); Set<String> actualOutput = new HashSet<>(); for (String msg : outContent.toString().split(NEWLINE_REGEX)) { String truncatedMsg = msg.substring(msg.indexOf(inputFile.getName())); actualOutput.add(truncatedMsg); } assertTrue(actualOutput.size() == expectedMessages.size()); assertTrue(actualOutput.containsAll(expectedMessages)); }
Source:
<code>public void run() { FileInputStream inputStream; try { inputStream = new FileInputStream("/proc/net/dev"); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); try { String line = br.readLine(); while (line != null) { line = line.trim(); if (line.startsWith(iface)) { String[] vals = line.split(":")[1].trim().split("\\s+"); if (initialValue == null) { initialValue = new BigDecimal(vals[valueIndex]); timeline.addValue(getCategory(), new Timeline.Value(0)); } else { timeline.addValue(getCategory(), new Timeline.Value(new BigDecimal(vals[valueIndex]).subtract(initialValue))); } break; } line = br.readLine(); } <START> br.close(); <END> } catch (Exception e) { log.error("Exception occurred while reading /proc/net/dev.", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.error("Exception occurred while closing /proc/net/dev.", e); } } } } catch (FileNotFoundException e) { log.error("File /proc/net/dev was not found!", e); } }</code><technical_language>Well, this get invoked if exception is thrown before</technical_language>

Target:
public void run() { FileInputStream inputStream; try { inputStream = new FileInputStream("/proc/net/dev"); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); try { String line = br.readLine(); while (line != null) { line = line.trim(); if (line.startsWith(iface)) { String[] vals = line.split(":")[1].trim().split("\\s+"); if (initialValue == null) { initialValue = new BigDecimal(vals[valueIndex]); timeline.addValue(getCategory(), new Timeline.Value(0)); } else { timeline.addValue(getCategory(), new Timeline.Value(new BigDecimal(vals[valueIndex]).subtract(initialValue))); } break; } line = br.readLine(); } } catch (Exception e) { log.error("Exception occurred while reading /proc/net/dev.", e); } finally { try { if (br != null) br.close(); if (inputStream != null) inputStream.close(); } catch (IOException e) { log.error("Exception occurred while closing /proc/net/dev.", e); } } } catch (FileNotFoundException e) { log.error("File /proc/net/dev was not found!", e); } }
Source:
<code>public void testWriteByteArrays() throws Throwable { describe("Write byte arrays to a file and verify" + " the stream statistics are updated"); Path path = methodPath(); FileSystem fs = getFileSystem(); fs.mkdirs(path.getParent()); <START> try (FSDataOutputStream out = fs.create(path, true)) { <END> final byte[] bytes = ContractTestUtils.toAsciiByteArray( "statistically-speaking"); final int len = bytes.length; out.write(bytes); IOStatistics statistics = extractStatistics(out); verifyStatisticValue(statistics, STREAM_WRITE_BYTES, len); out.write(bytes); verifyStatisticValue(statistics, STREAM_WRITE_BYTES, len * 2); out.close(); statistics = extractStatistics(out); verifyStatisticValue(statistics, STREAM_WRITE_BYTES, len * 2); } finally { fs.delete(path, false); } }</code><technical_language>Is fs.delete() required in tests? teardown() care of it</technical_language>

Target:
public void testWriteByteArrays() throws Throwable { describe("Write byte arrays to a file and verify" + " the stream statistics are updated"); Path path = methodPath(); FileSystem fs = getFileSystem(); fs.mkdirs(path.getParent()); boolean writesInBlocks = streamWritesInBlocks(); try (FSDataOutputStream out = fs.create(path, true)) { Object demandStatsString = demandStringify(out); final byte[] bytes = ContractTestUtils.toAsciiByteArray( "statistically-speaking"); final long len = bytes.length; out.write(bytes); out.flush(); IOStatistics statistics = extractStatistics(out); verifyStatisticCounterValue(statistics, STREAM_WRITE_BYTES, writesInBlocks ? 0 : len); out.write(bytes); out.flush(); verifyStatisticCounterValue(statistics, STREAM_WRITE_BYTES, writesInBlocks ? 0 : len * 2); out.close(); statistics = extractStatistics(out); verifyStatisticCounterValue(statistics, STREAM_WRITE_BYTES, len * 2); Assertions.assertThat(demandStatsString.toString()) .contains(Long.toString(len * 2)); } finally { fs.delete(path, false); } }
Source:
<code>private void apply(PacketContext context, UUID ownerId, boolean isPortFilter, RuleResult res, int depth, List<UUID> traversedChains) { context.jlog().debug("Processing chain with name and ID {}", name, id); if (depth > 10) { throw new IllegalStateException("Deep recursion when processing " + "chain " + traversedChains.get(0)); } context.addFlowTag(flowInvTag); traversedChains.add(id); Iterator<Rule> iter = rules.iterator(); res.action = Action.CONTINUE; while (iter.hasNext() && res.action == Action.CONTINUE) { Rule r = iter.next(); r.process(context, res, ownerId, isPortFilter); <START> if (res.action == Action.TRACE) { <END> throw TraceRequiredException.instance(); } if (res.action == Action.JUMP) { Chain jumpChain = getJumpTarget(res.jumpToChain); if (null == jumpChain) { context.jlog().error("ignoring jump to chain : not found.", res.jumpToChain, context); res.action = Action.CONTINUE; } else if (traversedChains.contains(jumpChain.id)) { context.jlog().warn( "cannot jump from chain to chain -- already visited", this, jumpChain, context); res.action = Action.CONTINUE; } else { jumpChain.apply(context, ownerId, isPortFilter, res, depth + 1, traversedChains); if (res.action == Action.RETURN) res.action = Action.CONTINUE; } } } assert res.action != Action.JUMP; }</code><technical_language>want throw if tracing this packet</technical_language>

Target:
private void apply(PacketContext context, UUID ownerId, boolean isPortFilter, RuleResult res, int depth, List<UUID> traversedChains) { context.jlog().debug("Processing chain with name and ID {}", name, id); if (depth > 10) { throw new IllegalStateException("Deep recursion when processing " + "chain " + traversedChains.get(0)); } context.addFlowTag(flowInvTag); traversedChains.add(id); Iterator<Rule> iter = rules.iterator(); res.action = Action.CONTINUE; while (iter.hasNext() && res.action == Action.CONTINUE) { Rule r = iter.next(); r.process(context, res, ownerId, isPortFilter); if (res.action == Action.JUMP) { Chain jumpChain = getJumpTarget(res.jumpToChain); if (null == jumpChain) { context.jlog().error("ignoring jump to chain : not found.", res.jumpToChain, context); res.action = Action.CONTINUE; } else if (traversedChains.contains(jumpChain.id)) { context.jlog().warn( "cannot jump from chain to chain -- already visited", this, jumpChain, context); res.action = Action.CONTINUE; } else { jumpChain.apply(context, ownerId, isPortFilter, res, depth + 1, traversedChains); if (res.action == Action.RETURN) res.action = Action.CONTINUE; } } } assert res.action != Action.JUMP; }
Source:
<code>public void testRestoreUserFromPrefs() { Client client = new Client(getContext(), "api-key"); client.clearUser(); SharedPreferences sharedPref = getContext().getSharedPreferences("com.bugsnag.android", Context.MODE_PRIVATE); sharedPref.edit() .putString("user.id", "123456") .putString("user.email", "mr.test@email.com") .putString("user.name", "Mr Test") .commit(); client = new Client(getContext(), "api-key"); final User user = new User(); client.beforeNotify(new BeforeNotify() { @Override public boolean run(Error error) { user.setId(error.getUser().getId()); user.setEmail(error.getUser().getEmail()); user.setName(error.getUser().getName()); return true; } }); client.notify(new RuntimeException("Testing")); assertEquals("123456", user.getId()); assertEquals("mr.test@email.com", user.getEmail()); assertEquals("Mr Test", user.getName()); <START> client.clearUser(); <END> }</code><technical_language>This belongs in tearDown() for this class</technical_language>

Target:
public void testRestoreUserFromPrefs() { SharedPreferences sharedPref = getContext().getSharedPreferences("com.bugsnag.android", Context.MODE_PRIVATE); sharedPref.edit() .putString("user.id", "123456") .putString("user.email", "mr.test@email.com") .putString("user.name", "Mr Test") .commit(); Configuration config = new Configuration("api-key"); config.setPersistUserBetweenSessions(true); Client client = new Client(getContext(), config); final User user = new User(); client.beforeNotify(new BeforeNotify() { @Override public boolean run(Error error) { user.setId(error.getUser().getId()); user.setEmail(error.getUser().getEmail()); user.setName(error.getUser().getName()); return true; } }); client.notify(new RuntimeException("Testing")); assertEquals("123456", user.getId()); assertEquals("mr.test@email.com", user.getEmail()); assertEquals("Mr Test", user.getName()); }
Source:
<code>private NamespaceDescriptor ensureNamespaceCreated(String schemaName) throws SQLException { SQLException sqlE = null; try (HBaseAdmin admin = getAdmin()) { <START> final String quorum = ZKConfig.getZKQuorumServersString(config); <END> final String znode = this.props.get(HConstants.ZOOKEEPER_ZNODE_PARENT); logger.debug("Found quorum: " + quorum + ":" + znode); boolean nameSpaceExists = true; NamespaceDescriptor namespaceDescriptor = null; try { namespaceDescriptor = admin.getNamespaceDescriptor(schemaName); } catch (org.apache.hadoop.hbase.NamespaceNotFoundException e) { nameSpaceExists = false; } if (!nameSpaceExists) { namespaceDescriptor = NamespaceDescriptor.create(schemaName).build(); admin.createNamespace(namespaceDescriptor); } return namespaceDescriptor; } catch (IOException e) { sqlE = ServerUtil.parseServerException(e); } finally { if (sqlE != null) { throw sqlE; } } return null; }</code><technical_language>Remove this variables logger statement</technical_language>

Target:
private NamespaceDescriptor ensureNamespaceCreated(String schemaName) throws SQLException { SQLException sqlE = null; try (HBaseAdmin admin = getAdmin()) { NamespaceDescriptor namespaceDescriptor = null; try { namespaceDescriptor = NamespaceDescriptor.create(schemaName).build(); admin.createNamespace(namespaceDescriptor); } catch (org.apache.hadoop.hbase.NamespaceExistException e) return namespaceDescriptor; } catch (IOException e) { sqlE = ServerUtil.parseServerException(e); } finally { if (sqlE != null) { throw sqlE; } } return null; }
Source:
<code>public void testGetCollectionPage() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); buyClient.getCollections(1, new Callback<List<Collection>>() { @Override public void success(List<Collection> collections) { assertNotNull(collections); assertFalse(collections.isEmpty()); boolean found = false; for (Collection collection : collections) { <START> if ("frontpage".equals(collection.getHandle())) { <END> found = true; break; } } assertTrue(found); latch.countDown(); } @Override public void failure(BuyClientError error) { fail(); } }); latch.await(); }</code><technical_language>a constant in test data</technical_language>

Target:
public void testGetCollectionPage() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); buyClient.getCollections(1, new Callback<List<Collection>>() { @Override public void success(List<Collection> collections) { assertNotNull(collections); assertFalse(collections.isEmpty()); boolean found = false; for (Collection collection : collections) { if (data.getCollectionHandle().equals(collection.getHandle())) { found = true; break; } } assertTrue(found); latch.countDown(); } @Override public void failure(BuyClientError error) { fail(); } }); latch.await(); }
Source:
<code>private void writeStringToFile(File file, String str) throws IOException { <START> try (BufferedWriter bw = new BufferedWriter(new FileWriter(file.toString()))) { <END> bw.write(str); } }</code><technical_language>need call file.toString() -> FileWriter File in constructor well</technical_language>

Target:
private void writeStringToFile(File file, String str) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(str); } }
Source:
<code>public void afterTest() { new TransactionTemplate(this.transactionManager).execute(status -> { final int deletedGroupToMessageRows = jdbcTemplate.update("delete from INT_GROUP_TO_MESSAGE"); final int deletedMessages = jdbcTemplate.update("delete from INT_MESSAGE"); final int deletedMessageGroups = jdbcTemplate.update("delete from INT_MESSAGE_GROUP"); <START> LOG.info(String.format("Cleaning Database - Deleted Messages: %s, " + <END> "Deleted GroupToMessage Rows: %s, Deleted Message Groups: %s", deletedMessages, deletedGroupToMessageRows, deletedMessageGroups)); return null; }); }</code><technical_language>unconditional logs in tests. mind removing in next polishing? Thanks</technical_language>

Target:
public void afterTest() { new TransactionTemplate(this.transactionManager).execute(status -> { this.jdbcTemplate.update("delete from INT_GROUP_TO_MESSAGE"); this.jdbcTemplate.update("delete from INT_MESSAGE"); this.jdbcTemplate.update("delete from INT_MESSAGE_GROUP"); return null; }); }
Source:
<code>public ResultSet extract(PreparedStatement statement) { long executeStart = 0; if ( this.sqlStatementLogger.getLogSlowQuery() > 0 ) { executeStart = System.currentTimeMillis(); } try { final ResultSet rs; try { jdbcExecuteStatementStart(); rs = statement.executeQuery(); } finally { jdbcExecuteStatementEnd(); <START> sqlStatementLogger.logSlowQuery( statement.toString(), executeStart ); <END> } postExtract( rs, statement ); return rs; } catch (SQLException e) { throw sqlExceptionHelper.convert( e, "could not extract ResultSet" ); } }</code><technical_language>this is executed if feature is enabled? In statement.toString() is a performance problem. (same for other methods)</technical_language>

Target:
public ResultSet extract(PreparedStatement statement) { long executeStart = 0; if ( this.sqlStatementLogger.getLogSlowQuery() > 0 ) { executeStart = System.currentTimeMillis(); } try { final ResultSet rs; try { jdbcExecuteStatementStart(); rs = statement.executeQuery(); } finally { jdbcExecuteStatementEnd(); sqlStatementLogger.logSlowQuery( statement, executeStart ); } postExtract( rs, statement ); return rs; } catch (SQLException e) { throw sqlExceptionHelper.convert( e, "could not extract ResultSet" ); } }
Source:
<code>public void configure(final MapperFactory mapperFactory) { mapperFactory .classMap(com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AmrProfileStatusCode.class, AmrProfileStatusCode.class).field("amrProfileStatusCodeFlag", "amrProfileStatusCodeFlags") .byDefault().register(); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsRequestConverter()); mapperFactory.getConverterFactory().registerConverter(new PushNotificationsAlarmConverter()); mapperFactory.getConverterFactory().registerConverter(new MeterValueConverter()); mapperFactory.getConverterFactory().registerConverter(new XsdDateTimeToLongConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicReadsRequestGasQueryConverter()); <START> mapperFactory.getConverterFactory().registerConverter(new ObisCodeValuesConverter()); <END> mapperFactory.getConverterFactory().registerConverter(new ProfileEntryValueVoConverter()); }</code><technical_language>Is this converter needed</technical_language>

Target:
public void configure(final MapperFactory mapperFactory) { mapperFactory .classMap(com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AmrProfileStatusCode.class, AmrProfileStatusCode.class).field("amrProfileStatusCodeFlag", "amrProfileStatusCodeFlags") .byDefault().register(); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsRequestConverter()); mapperFactory.getConverterFactory().registerConverter(new PushNotificationsAlarmConverter()); mapperFactory.getConverterFactory().registerConverter(new MeterValueConverter()); mapperFactory.getConverterFactory().registerConverter(new XsdDateTimeToLongConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicReadsRequestGasQueryConverter()); mapperFactory.getConverterFactory().registerConverter(new ObisCodeValuesConverter()); mapperFactory.getConverterFactory().registerConverter(new ProfileEntryValueConverter()); mapperFactory.getConverterFactory().registerConverter(new ProfileGenericDataResponseConverter()); }
Source:
<code>public void shouldAcceptAndApplyValidDiscountCode() throws Exception { withCartDiscountAndDiscountCode(sphereClient, discountCode -> { withTaxedAndFilledCart(sphereClient, cart -> { when(cartInSession.findCartId()).thenReturn(Optional.of(cart.getId())); final Map<String, String> bodyForm = new HashMap<>(); bodyForm.put("code", discountCode.getCode()); final Result result = route(new Http.RequestBuilder() .uri("/en/cart/discount/add") .method(POST) .bodyForm(bodyForm)); <START> assertThat(result.status()).isEqualTo(SEE_OTHER); <END> return cart; }); return discountCode; }); }</code><technical_language>check redirection target is expect, a redirection for another topic</technical_language>

Target:
public void shouldAcceptAndApplyValidDiscountCode() throws Exception { withCartDiscountAndDiscountCode(sphereClient, discountCode -> { withTaxedAndFilledCart(sphereClient, cart -> { when(cartInSession.findCartId()).thenReturn(Optional.of(cart.getId())); final Map<String, String> bodyForm = new HashMap<>(); bodyForm.put("code", discountCode.getCode()); final Result result = route(new Http.RequestBuilder() .uri("/en/cart/discount/add") .method(POST) .bodyForm(bodyForm)); assertThat(result.status()).isEqualTo(SEE_OTHER); assertThat(result.redirectLocation()) .isPresent() .hasValue("/en/cart"); return cart; }); return discountCode; }); }
Source:
<code>public void stop() { this.cache.removeListener(this); PrivilegedAction<List<Runnable>> action = () -> this.executor.shutdownNow(); WildFlySecurityManager.doUnchecked(action); try { this.executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } <START> this.dispatcher.close(); <END> this.scheduler.close(); this.identifierFactory.stop(); }</code><technical_language>finally</technical_language>

Target:
public void stop() { this.cache.removeListener(this); PrivilegedAction<List<Runnable>> action = () -> this.executor.shutdownNow(); WildFlySecurityManager.doUnchecked(action); try { this.executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { this.dispatcher.close(); this.scheduler.close(); this.identifierFactory.stop(); } }
Source:
<code>protected int getStreamingFetchSize() { <START> return 50; <END> }</code><technical_language>suggest configurable</technical_language>

Target:
protected int getStreamingFetchSize() { return DEFAULT_STREAMING_RESULT_SIZE; }
Source:
<code>protected void validatePlan(String SQL, int numberOfFragments, Object ...types) { List<AbstractPlanNode> fragments = compileToFragments(SQL); assertEquals(String.format("Expected %d fragments, not %d", numberOfFragments, fragments.size()), numberOfFragments, fragments.size()); int idx = 0; int fragment = 1; int nchildren = types.length; System.out.printf("Plan for <%s>\n", SQL); for (AbstractPlanNode plan : fragments) { printPlanNodes(plan, fragment, numberOfFragments); if (fragment > 1) { assertEquals("Expected a fragment to start here", PlanNodeType.INVALID, types[idx]); idx += 1; } fragment += 1; for (;plan != null; idx += 1) { if (types.length <= idx) { fail(String.format("Expected %d plan nodes, but found more.", types.length)); } if (types[idx] instanceof PlanNodeType) { <START> assertEquals(String.format("Expected %s plan node by found %s", types[idx], plan.getPlanNodeType()), <END> types[idx], plan.getPlanNodeType()); } else if (types[idx] instanceof PlanWithInlineNodes) { PlanWithInlineNodes branch = (PlanWithInlineNodes)types[idx]; String error = branch.match(plan); if (error != null) { fail(error); } } else { fail("Expected a PlanNodeType or an array of PlanNodeTypes here."); } plan = (plan.getChildCount() > 0) ? plan.getChild(0) : null; } } assertEquals(nchildren, idx); }</code><technical_language>Typo, "by" "but"</technical_language>

Target:
protected void validatePlan(String SQL, int numberOfFragments, Object ...types) { List<AbstractPlanNode> fragments = compileToFragments(SQL); assertEquals(String.format("Expected %d fragments, not %d", numberOfFragments, fragments.size()), numberOfFragments, fragments.size()); int idx = 0; int fragment = 1; int nchildren = types.length; System.out.printf("Plan for <%s>\n", SQL); for (AbstractPlanNode plan : fragments) { printPlanNodes(plan, fragment, numberOfFragments); if (fragment > 1) { assertEquals("Expected a fragment to start here", PlanNodeType.INVALID, types[idx]); idx += 1; } fragment += 1; for (;plan != null; idx += 1) { if (types.length <= idx) { fail(String.format("Expected %d plan nodes, but found more.", types.length)); } if (types[idx] instanceof PlanNodeType) { assertEquals(String.format("Expected %s plan node but found %s", types[idx], plan.getPlanNodeType()), types[idx], plan.getPlanNodeType()); } else if (types[idx] instanceof PlanWithInlineNodes) { PlanWithInlineNodes branch = (PlanWithInlineNodes)types[idx]; String error = branch.match(plan); if (error != null) { fail(error); } } else { fail("Expected a PlanNodeType or an array of PlanNodeTypes here."); } plan = (plan.getChildCount() > 0) ? plan.getChild(0) : null; } } assertEquals(nchildren, idx); }
Source:
<code>public static Map<String, List<String>> getAvailableNamesSpaces(SSOExtensionsManager extensionsManager) { Map<String, List<String>> namespacesMap = new HashMap<>(); for (ExtensionProxy authz : extensionsManager.getExtensionsByService(Authz.class.getName())) { String authzName = authz.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME); for (String namespace : authz.getContext().<Collection<String>>get(Authz.ContextKeys.AVAILABLE_NAMESPACES, Collections.<String>emptyList())) { if (!namespacesMap.containsKey(authzName)) { namespacesMap.put(authzName, new ArrayList<>()); } namespacesMap.get(authzName).add(namespace); } } for (List<String> entry : namespacesMap.values()) { <START> Collections.sort(entry); <END> } return namespacesMap; }</code><technical_language>do entry.sort(naturalOrder()); java.util.Comparator.naturalOrder</technical_language>

Target:
public static Map<String, List<String>> getAvailableNamesSpaces(SSOExtensionsManager extensionsManager) { Map<String, List<String>> namespacesMap = new HashMap<>(); extensionsManager.getExtensionsByService(Authz.class.getName()) .forEach(authz -> { String authzName = authz.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME); authz.getContext().<Collection<String>>get(Authz.ContextKeys.AVAILABLE_NAMESPACES, Collections.<String>emptyList()) .forEach(namespace -> { if (!namespacesMap.containsKey(authzName)) { namespacesMap.put(authzName, new ArrayList<>()); } namespacesMap.get(authzName).add(namespace); }); }); namespacesMap.values().forEach(Collections::sort); return namespacesMap; }
Source:
<code>private static Value buildPortInfo( InputPortInfo portInfo, ProgramInspector inspector, Set< String > referredTypesSet ) { Value result = Value.create(); result.setFirstChild( PortInfoType.NAME, portInfo.id() ); if( portInfo.location() != null ) { result.setFirstChild( PortInfoType.LOCATION, portInfo.location().toString() ); } if( portInfo.protocol() != null ) { <START> result.setFirstChild( PortInfoType.PROTOCOL, portInfo.protocol().toString() ); <END> } if( portInfo.getDocumentation() != null ) { result.setFirstChild( PortInfoType.DOCUMENTATION, portInfo.getDocumentation() ); } ValueVector interfaces = result.getChildren( PortInfoType.INTERFACE ); portInfo.getInterfaceList().forEach( i -> interfaces.add( buildInterfaceInfo( i, referredTypesSet ) ) ); getAggregatedInterfaces( portInfo, inspector ) .forEach( i -> interfaces.add( buildInterfaceInfo( i, referredTypesSet ) ) ); return result; }</code><technical_language>this protocolId rest</technical_language>

Target:
private static Value buildPortInfo( InputPortInfo portInfo, ProgramInspector inspector, Set< String > referredTypesSet ) { Value result = Value.create(); result.setFirstChild( PortInfoType.NAME, portInfo.id() ); if( portInfo.location() != null ) { result.setFirstChild( PortInfoType.LOCATION, portInfo.location().toString() ); } if( portInfo.protocol() != null ) { result.setFirstChild( PortInfoType.PROTOCOL, portInfo.protocolId() ); } if( portInfo.getDocumentation() != null ) { result.setFirstChild( PortInfoType.DOCUMENTATION, portInfo.getDocumentation() ); } ValueVector interfaces = result.getChildren( PortInfoType.INTERFACE ); portInfo.getInterfaceList().forEach( i -> interfaces.add( buildInterfaceInfo( i, referredTypesSet ) ) ); getAggregatedInterfaces( portInfo, inspector ) .forEach( i -> interfaces.add( buildInterfaceInfo( i, referredTypesSet ) ) ); return result; }
Source:
<code>public Date parse(String source) throws ParseException { <START> if (source.matches(".+\\.\\d\\d\\d\\d\\d\\d\\d\\d\\dZ$")) { <END> source = source.replaceAll("\\d\\d\\d\\d\\d\\dZ$", "Z"); } return super.parse(source); }</code><technical_language>\\d{9} instead for readability</technical_language>

Target:
public Date parse(String source) throws ParseException { if (source.matches(".+\\.\\d{9}Z$")) { source = source.replaceAll("\\d{6}Z$", "Z"); } return super.parse(source); }
Source:
<code>private Optional<String> getDockerHubToolAsString(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final String repoUrl = DOCKERHUB_URL + "repositories/" + repo + "/tags"; String command = "curl " + repoUrl; Optional<String> response; <START> try { <END> Process process = Runtime.getRuntime().exec(command.split(" ")); InputStream inputStream = process.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } response = Optional.of(sb.toString()); inputStreamReader.close(); bufferedReader.close(); if (response.isPresent()) { return response; } } catch (IOException ex) { LOG.info("Unable to get DockerHub response for " + repo); } return Optional.empty(); }</code><technical_language>a number of try..with resources Right a couple of Exceptions leave unclosed readers</technical_language>

Target:
private Optional<String> getDockerHubToolAsString(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final String repoUrl = DOCKERHUB_URL + "repositories/" + repo + "/tags"; Optional<String> response; try { URL url = new URL(repoUrl); response = Optional.of(IOUtils.toString(url, "UTF-8")); if (response.isPresent()) { return response; } } catch (IOException ex) { LOG.info("Unable to get DockerHub response for " + repo); } return Optional.empty(); }
Source:
<code>protected Void doInBackground(Void... params) { try { <START> UserSubscriptions.syncMultiReddits(MainActivity.this); <END> } catch (final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { new AlertDialogWrapper.Builder(MainActivity.this) .setTitle(R.string.err_title) .setMessage(e instanceof ApiException ? getString(R.string.misc_err) + ": " + ((ApiException) e).getExplanation() + "\n" + getString(R.string.misc_retry) : getString(R.string.misc_err)) .setNeutralButton(R.string.btn_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }).create().show(); } }); e.printStackTrace(); } return null; }</code><technical_language>This method throw (it ignores network/api errors), remove try/catch</technical_language>

Target:
protected Void doInBackground(Void... params) { UserSubscriptions.syncMultiReddits(MainActivity.this); return null; }
Source:
<code>public String[] getAllSchemaNames( long milliSeconds ) { class TempThread extends Thread { private List<String> names = new ArrayList<String>( ); @Override public void run( ) { ResultSet rs = JdbcMetaDataProvider.this.getAllSchemas( ); String odaDriver = JdbcMetaDataProvider.this.driverClass.toLowerCase(); <START> boolean isCassandra = ( odaDriver !=null && odaDriver.indexOf("cassandra") != -1 ); <END> String otscpfKeyspace = null; if (isCassandra) { String odaUrl = JdbcMetaDataProvider.this.url; StringTokenizer st = new StringTokenizer(odaUrl, ";"); while (st.hasMoreTokens()) { String key = st.nextToken().toUpperCase(); if (key.indexOf(OT_SCHEMA_PREFIX) == 0) { int equalIndex = key.indexOf("="); if (equalIndex != -1) { otscpfKeyspace = key.substring(equalIndex + 1); } break; } } } if ( rs != null ) { try { while ( rs.next( ) ) { String schemaName = rs.getString( "TABLE_SCHEM" ); if ( isCassandra && otscpfKeyspace != null ) { if ( !schemaName.equalsIgnoreCase( otscpfKeyspace ) ) { schemaName = null; } } if ( schemaName != null ) { names.add( schemaName ); } } } catch ( SQLException e ) { logger.log( Level.WARNING, e.getMessage( ), e ); } } } public String[] getResult( ) { return names.toArray( new String[0] ); } } TempThread tt = new TempThread( ); tt.start( ); try { tt.join( milliSeconds ); } catch ( InterruptedException e ) { } return tt.getResult( ); }</code><technical_language>Abstract JDBC layer check hardcoded name depend specific JDBC driver. This logic push extension layer jdbc.cassandra. More code refactor is required</technical_language>

Target:
public String[] getAllSchemaNames( long milliSeconds ) { class TempThread extends Thread { private List<String> names = new ArrayList<String>( ); @Override public void run( ) { ResultSet rs = JdbcMetaDataProvider.this.getAllSchemas( ); if ( rs != null ) { try { while ( rs.next( ) ) { names.add( rs.getString( "TABLE_SCHEM" ) ); } } catch ( SQLException e ) { logger.log( Level.WARNING, e.getMessage( ), e ); } } } public String[] getResult( ) { return names.toArray( new String[0] ); } } TempThread tt = new TempThread( ); tt.start( ); try { tt.join( milliSeconds ); } catch ( InterruptedException e ) { } return tt.getResult( ); }
Source:
<code>public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize) throws IOException { validateIndex(index); long written = 0; BlobReadInfo blobReadInfo = blobReadInfoList.get(index); String blobIdStr = blobReadInfo.getBlobId().getID(); try { if (!blobReadInfo.isPrefetched()) { blobReadInfo.prefetchBlob(blobStore); } ByteBuffer outputBuffer = blobReadInfo.getPrefetchedBuffer(); long sizeToRead = Math.min(maxSize, blobReadInfo.getBlobSize() - relativeOffset); outputBuffer.limit((int) (relativeOffset + sizeToRead)); outputBuffer.position((int) (relativeOffset)); written = channel.write(outputBuffer); } catch (StoreException ex) { <START> throw new IOException("Write of cloud blob " + blobIdStr + " failed"); <END> } logger.trace("Downloaded bytes to the write channel from the cloud blob : {}", written, blobIdStr); return written; }</code><technical_language>add ex exception</technical_language>

Target:
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize) throws IOException { validateIndex(index); long written = 0; BlobReadInfo blobReadInfo = blobReadInfoList.get(index); String blobIdStr = blobReadInfo.getBlobId().getID(); try { if (!blobReadInfo.isPrefetched()) { blobReadInfo.prefetchBlob(blobStore); } ByteBuffer outputBuffer = blobReadInfo.getPrefetchedBuffer(); long sizeToRead = Math.min(maxSize, blobReadInfo.getBlobSize() - relativeOffset); outputBuffer.limit((int) (relativeOffset + sizeToRead)); outputBuffer.position((int) (relativeOffset)); written = channel.write(outputBuffer); } catch (StoreException ex) { throw new IOException("Write of cloud blob " + blobIdStr + " failed", ex); } logger.trace("Downloaded bytes to the write channel from the cloud blob : {}", written, blobIdStr); return written; }
Source:
<code>public void workerCount_can_be_controlled_via_plugin() throws IOException { String workerCount = "5"; OrchestratorBuilder builder = Orchestrator.builderEnv() <START> .setZipFile(FileLocation.byWildcardMavenFilename(new File("../sonar-application/target"), "sonar*.zip").getFile()) <END> .addPlugin(pluginArtifact("fake-governance-plugin")) .setServerProperty("fakeGovernance.workerCount", workerCount); orchestrator = builder.build(); orchestrator.start(); Set<String> line = Files.lines(orchestrator.getServer().getCeLogs().toPath()) .filter(s -> s.contains("Compute Engine will use ")) .collect(Collectors.toSet()); assertThat(line) .hasSize(1); assertThat(line.iterator().next()).contains(workerCount); }</code><technical_language>zip is useless</technical_language>

Target:
public void workerCount_can_be_controlled_via_plugin() throws IOException { String workerCount = "5"; OrchestratorBuilder builder = Orchestrator.builderEnv() .addPlugin(pluginArtifact("fake-governance-plugin")) .setServerProperty("fakeGovernance.workerCount", workerCount); orchestrator = builder.build(); orchestrator.start(); Set<String> line = Files.lines(orchestrator.getServer().getCeLogs().toPath()) .filter(s -> s.contains("Compute Engine will use ")) .collect(Collectors.toSet()); assertThat(line) .hasSize(1); assertThat(line.iterator().next()).contains(workerCount); }
Source:
<code><START> public static ICPPFunction[] instantiateForFunctionCall(ICPPFunction[] fns, ICPPTemplateArgument[] tmplArgs, <END> List<IType> fnArgs, List<ValueCategory> argCats, boolean withImpliedObjectArg) { boolean requireTemplate = tmplArgs != null; boolean haveTemplate = false; for (final ICPPFunction func : fns) { if (func instanceof ICPPConstructor || (func instanceof ICPPMethod && ((ICPPMethod) func).isDestructor())) requireTemplate = false; if (func instanceof ICPPFunctionTemplate) { if (containsDependentType(fnArgs)) return new ICPPFunction[] { CPPDeferredFunction.createForCandidates(fns) }; if (requireTemplate && hasDependentArgument(tmplArgs)) return new ICPPFunction[] { CPPDeferredFunction.createForCandidates(fns) }; haveTemplate = true; break; } } if (!haveTemplate && !requireTemplate) return fns; final List<ICPPFunction> result = new ArrayList<>(fns.length); for (ICPPFunction fn : fns) { if (fn != null) { if (fn instanceof ICPPFunctionTemplate) { ICPPFunctionTemplate fnTmpl = (ICPPFunctionTemplate) fn; ICPPFunction inst = instantiateForFunctionCall(fnTmpl, tmplArgs, fnArgs, argCats, withImpliedObjectArg); if (inst != null) result.add(inst); } else if (!requireTemplate || fn instanceof ICPPUnknownBinding) { result.add(fn); } } } return result.toArray(new ICPPFunction[result.size()]); }</code><technical_language>This too</technical_language>

Target:
static ICPPFunction[] instantiateForFunctionCall(ICPPFunction[] fns, ICPPTemplateArgument[] tmplArgs, List<IType> fnArgs, List<ValueCategory> argCats, boolean withImpliedObjectArg) { boolean requireTemplate = tmplArgs != null; boolean haveTemplate = false; for (final ICPPFunction func : fns) { if (func instanceof ICPPConstructor || (func instanceof ICPPMethod && ((ICPPMethod) func).isDestructor())) requireTemplate = false; if (func instanceof ICPPFunctionTemplate) { if (containsDependentType(fnArgs)) return new ICPPFunction[] { CPPDeferredFunction.createForCandidates(fns) }; if (requireTemplate && hasDependentArgument(tmplArgs)) return new ICPPFunction[] { CPPDeferredFunction.createForCandidates(fns) }; haveTemplate = true; break; } } if (!haveTemplate && !requireTemplate) return fns; final List<ICPPFunction> result = new ArrayList<>(fns.length); for (ICPPFunction fn : fns) { if (fn != null) { if (fn instanceof ICPPFunctionTemplate) { ICPPFunctionTemplate fnTmpl = (ICPPFunctionTemplate) fn; ICPPFunction inst = instantiateForFunctionCall(fnTmpl, tmplArgs, fnArgs, argCats, withImpliedObjectArg); if (inst != null) result.add(inst); } else if (!requireTemplate || fn instanceof ICPPUnknownBinding) { result.add(fn); } } } return result.toArray(new ICPPFunction[result.size()]); }
Source:
<code>public final Entity getSource() { if (source == null || !source.isValid()) { return null; } else { return source; <START> } <END> }</code><technical_language>return (source != null && source.isValid()) ? source : null;</technical_language>

Target:
public final Entity getSource() { return (source != null && source.isValid()) ? source : null; }
Source:
<code>protected void doClose() throws Exception { Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> queue = tempInboundMessages(); if (isNotEmpty(queue)) { <START> queue.clear(); <END> } state = State.CLOSED; }</code><technical_language>This is enough... need release message fail promise. ClosedChannelException exception = null; for (;;) { AbstractMap.SimpleEntry<Object, ChannelPromise> entry = queue.poll(); if (entry == null) { break; } ReferenceCountedUtil.release(entry.getKey()); ChannelPromise promise = entry.getValue(); if (promise != null) { if (exception == null) { exception = new ClosedChannelException(); } promise.tryFailure(exception); } }</technical_language>

Target:
protected void doClose() throws Exception { state = State.CLOSED; if (isNotEmpty(tempInboundMessages)) { ClosedChannelException exception = null; for (;;) { AbstractMap.SimpleEntry<Object, ChannelPromise> entry = tempInboundMessages.poll(); if (entry == null) { break; } Object value = entry.getKey(); if (value != null) { ReferenceCountUtil.release(value); } ChannelPromise promise = entry.getValue(); if (promise != null) { if (exception == null) { exception = new ClosedChannelException(); } promise.tryFailure(exception); } } } }
Source:
<code>private CompletableFuture<?> index(PojoSessionWorkExecutor workExecutor, Object entity) throws InterruptedException { if ( Thread.currentThread().isInterrupted() ) { throw new InterruptedException(); } CompletableFuture<?> task = null; try { task = workExecutor.add( entity ); } catch (Throwable e) { handleException( entity, e ); <START> } <END> return task; }</code><technical_language>Alternatively pattern elsewhere: task = Futures.create( () -> workExecutor.add( entity ) ); exception occurring while creating future simply result in Futures.create() returning a future completed exceptionally. get rid of try/catch. a lamba, in this case, I worth it</technical_language>

Target:
private CompletableFuture<?> index(PojoSessionWorkExecutor workExecutor, Object entity) throws InterruptedException { if ( Thread.currentThread().isInterrupted() ) { throw new InterruptedException(); } CompletableFuture<?> future = Futures.create( () -> workExecutor.add( entity ) .exceptionally( exception -> { handleException( entity, exception ); return null; } ) ); monitor.documentsBuilt( 1 ); return future; }
Source:
<code>private Menu createUpdateMenu() { Menu update = new Menu("Update"); MenuItem checkProgress = new MenuItem("Check progress..."); <START> if (ui.updateManager == null) { <END> checkProgress.setDisable(true); } else { checkProgress.setOnAction(e -> { Platform.runLater(() -> ui.updateProgressWindow.showWindow()); }); } update.getItems().addAll(checkProgress); return update; }</code><technical_language>this happen</technical_language>

Target:
private Menu createUpdateMenu() { Menu update = new Menu("Update"); MenuItem checkProgress = new MenuItem("Check progress..."); checkProgress.setOnAction(e -> { ui.showUpdateProgressWindow(); }); update.getItems().addAll(checkProgress); return update; }
Source:
<code><START> public static ITimeEvent findEvent(ITimeGraphEntry entry, long time, int n) { <END> if (null == entry || ! entry.hasTimeEvents()) { return null; } Iterator<ITimeEvent> iterator = entry.getTimeEventsIterator(); if (iterator == null) { return null; } ITimeEvent nextEvent = null; ITimeEvent currEvent = null; ITimeEvent prevEvent = null; while (iterator.hasNext()) { nextEvent = iterator.next(); long nextStartTime = nextEvent.getTime(); if (nextStartTime > time) { break; } if (currEvent == null || currEvent.getTime() != nextStartTime || (nextStartTime != time && currEvent.getDuration() != nextEvent.getDuration())) { prevEvent = currEvent; currEvent = nextEvent; } } if (n == -1) { if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { return prevEvent; } return currEvent; } else if (n == 0) { if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { return currEvent; } return null; } else if (n == 1) { if (nextEvent != null && nextEvent.getTime() > time) { return nextEvent; } return null; } else if (n == 2) { return currEvent; } return null; }</code><technical_language>This change is unrelated histogram update shoudn't part of this patch</technical_language>

Target:
static ITimeEvent findEvent(ITimeGraphEntry entry, long time, int n) { if (null == entry || ! entry.hasTimeEvents()) { return null; } Iterator<ITimeEvent> iterator = entry.getTimeEventsIterator(); if (iterator == null) { return null; } ITimeEvent nextEvent = null; ITimeEvent currEvent = null; ITimeEvent prevEvent = null; while (iterator.hasNext()) { nextEvent = iterator.next(); long nextStartTime = nextEvent.getTime(); if (nextStartTime > time) { break; } if (currEvent == null || currEvent.getTime() != nextStartTime || (nextStartTime != time && currEvent.getDuration() != nextEvent.getDuration())) { prevEvent = currEvent; currEvent = nextEvent; } } if (n == -1) { if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { return prevEvent; } return currEvent; } else if (n == 0) { if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { return currEvent; } return null; } else if (n == 1) { if (nextEvent != null && nextEvent.getTime() > time) { return nextEvent; } return null; } else if (n == 2) { return currEvent; } return null; }