auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private BatchWriter createBatchWriter(String table) throws TableNotFoundException { BatchWriterConfig bwc = new BatchWriterConfig(); bwc.setMaxLatency( Long.parseLong(getProperties() .getProperty("accumulo.batchWriterMaxLatency", "30000")), TimeUnit.MILLISECONDS); bwc.setMaxMemory(Long.parseLong( getProperties().getProperty("accumulo.batchWriterSize", "100000"))); final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads"); int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2); if (null != numThreadsValue) { numThreads = Integer.parseInt(numThreadsValue); } <START> System.out.println("Using " + numThreads + " threads to write data"); <END> bwc.setMaxWriteThreads(numThreads); return connector.createBatchWriter(table, bwc); }</code><technical_language>matter if this println remains? harness inclined care if this is here</technical_language>

Target:
private BatchWriter createBatchWriter(String table) throws TableNotFoundException { BatchWriterConfig bwc = new BatchWriterConfig(); bwc.setMaxLatency( Long.parseLong(getProperties() .getProperty("accumulo.batchWriterMaxLatency", "30000")), TimeUnit.MILLISECONDS); bwc.setMaxMemory(Long.parseLong( getProperties().getProperty("accumulo.batchWriterSize", "100000"))); final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads"); int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2); if (null != numThreadsValue) { numThreads = Integer.parseInt(numThreadsValue); } System.err.println("Using " + numThreads + " threads to write data"); bwc.setMaxWriteThreads(numThreads); return connector.createBatchWriter(table, bwc); }
Source:
<code>public void processRow(ResultSet rs) { try { Long municipalityId = rs.getLong(MUNICIPALITY_ID_COLUMN_NAMER); HashableEntity<Court> courtId = new HashableEntity<Court>(Court.class,rs.getLong(CourtDAO.COURT_ID_COLUMN_NAME)); if(municipalityMap.containsKey(municipalityId)) { municipalityMap.get(municipalityId).courts.add(courtId); } else { Municipality municipality = new Municipality(); municipality.id = new HashableEntity<Municipality>(Municipality.class,municipalityId); municipality.name = rs.getString(MUNICIPALITY_NAME_COLUMN_NAMER); municipality.courts = Lists.newArrayList(courtId); <START> municipality.isSupported = (rs.getString("citation_datasource_id") != null)?true:false; <END> municipalityMap.put(municipalityId, municipality); } } catch (Exception e) { LogSystem.LogDBException(e); } }</code><technical_language>ternary is redundant..Just assign this: municipality.isSupported = rs.getString("citation_datasource_id") != null</technical_language>

Target:
public void processRow(ResultSet rs) { try { Long municipalityId = rs.getLong(MUNICIPALITY_ID_COLUMN_NAMER); HashableEntity<Court> courtId = new HashableEntity<Court>(Court.class,rs.getLong(CourtDAO.COURT_ID_COLUMN_NAME)); if(municipalityMap.containsKey(municipalityId)) { municipalityMap.get(municipalityId).courts.add(courtId); } else { Municipality municipality = new Municipality(); municipality.id = new HashableEntity<Municipality>(Municipality.class,municipalityId); municipality.name = rs.getString(MUNICIPALITY_NAME_COLUMN_NAMER); municipality.courts = Lists.newArrayList(courtId); municipality.isSupported = rs.getString("citation_datasource_id") != null; municipalityMap.put(municipalityId, municipality); } } catch (Exception e) { LogSystem.LogDBException(e); } }
Source:
<code>public TextArgs add(Object arg) { if (positionedArgsBuilder == null) { throw new IllegalArgumentException("Positioned arguments were already accessed, to add" + <START> "more arguments use TextArgs.copy()"); <END> } positionedArgsBuilder.add(arg); return this; }</code><technical_language>a space add</technical_language>

Target:
public TextArgs add(Object arg) { return new TextArgs( ImmutableList.builder().addAll(positionedArgs).add(arg).build(), namedArgs ); }
Source:
<code>private void updateLastKnownSequence(long seq) { if (seq > lastKnownSequence) { lastKnownSequence = seq; <START> } <END> }</code><technical_language>AtomicLong accumulateAndGet: _wrong_ of used, unwanted race conditions</technical_language>

Target:
private void updateLastKnownSequence(long seq) { lastKnownSequence.accumulateAndGet(seq, Long::max); }
Source:
<code><START> private XSiteReplicateCommand buildRemoveCommand(CleanupTask cleanupTask) { <END> Object key = cleanupTask.key; IracMetadata metadata = iracVersionGenerator.getTombstone(key); if (metadata == null) { return null; } cleanupTask.tombstone = metadata; return commandsFactory.buildIracUpdateKeyCommand(key, null, null, metadata); }</code><technical_language>This method replaced a reference EntryLoader#loadAndStoreInDataContainer <LINK_0></technical_language>

Target:
private XSiteReplicateCommand buildRemoveCommand(CleanupTask cleanupTask) { Object key = cleanupTask.key; IracMetadata metadata = iracVersionGenerator.getTombstone(key); if (metadata == null) { return null; } cleanupTask.tombstone = metadata; return commandsFactory.buildIracRemoveKeyCommand(key, metadata); }
Source:
<code>public DatasetDescriptor update(String namespace, String name, DatasetDescriptor descriptor) { Preconditions.checkArgument(DEFAULT_NAMESPACE.equals(namespace), "Non-default namespaces are not supported"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); Preconditions.checkNotNull(descriptor, "Descriptor cannot be null"); Compatibility.checkAndWarn( namespace, HBaseMetadataProvider.getTableName(name), descriptor.getSchema()); Preconditions.checkArgument(descriptor.isColumnMapped(), "Cannot update dataset %s: missing column mapping", name); String tableName = getTableName(name); String entityName = getEntityName(name); schemaManager.refreshManagedSchemaCache(tableName, entityName); Schema newSchema = getEmbeddedSchema(descriptor); String schemaString = newSchema.toString(true); EntitySchema entitySchema = new AvroEntitySchema( newSchema, schemaString, descriptor.getColumnMapping()); if (!schemaManager.hasSchemaVersion(tableName, entityName, entitySchema)) { schemaManager.migrateSchema(tableName, entityName, schemaString); } else { LOG.info("Schema hasn't changed, not migrating: (" + name + ")"); } <START> Map<String, String> properties = getProperties(descriptor); <END> schemaManager.setProperties(tableName, entityName, properties); return getDatasetDescriptor(newSchema, descriptor.getLocation()); }</code><technical_language>Do this a descriptor method? descriptor.getProperties() sense, a setter descriptor builder</technical_language>

Target:
public DatasetDescriptor update(String namespace, String name, DatasetDescriptor descriptor) { Preconditions.checkArgument(DEFAULT_NAMESPACE.equals(namespace), "Non-default namespaces are not supported"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); Preconditions.checkNotNull(descriptor, "Descriptor cannot be null"); Compatibility.checkAndWarn( namespace, HBaseMetadataProvider.getTableName(name), descriptor.getSchema()); Preconditions.checkArgument(descriptor.isColumnMapped(), "Cannot update dataset %s: missing column mapping", name); String tableName = getTableName(name); String entityName = getEntityName(name); schemaManager.refreshManagedSchemaCache(tableName, entityName); Schema newSchema = getEmbeddedSchema(descriptor); String schemaString = newSchema.toString(true); EntitySchema entitySchema = new AvroEntitySchema( newSchema, schemaString, descriptor.getColumnMapping()); if (!schemaManager.hasSchemaVersion(tableName, entityName, entitySchema)) { schemaManager.migrateSchema(tableName, entityName, schemaString); } else { LOG.info("Schema hasn't changed, not migrating: (" + name + ")"); } return getDatasetDescriptor(newSchema, descriptor.getLocation()); }
Source:
<code>public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String dir = null; <START> while (dir == null) { <END> String status = null; while (status == null) { System.out.print("Enter r/b/a for release/beta or alpha quality:\t"); String q = in.readLine(); if (q.equalsIgnoreCase("r")) { status = ""; } else if (q.equalsIgnoreCase("b")) { status = "_beta"; } else if (q.equalsIgnoreCase("a")) { status = "_alpha"; } } System.out.print("Enter add-on package name:\t"); dir = "../zap-extensions" + status + "/src/org/zaproxy/zap/extension/" + in.readLine(); if (! new File(dir).isDirectory()) { System.out.println("dir is not a directory :("); dir = null; } } System.out.print("Enter the add-n 'friendly' name:\t"); String name = in.readLine(); System.out.print("Enter icon name (eg example.png) or just return for no icon:\t"); String icon = in.readLine(); if (icon.length() == 0) { icon = null; } System.out.print("Enter a one line summary of the add-on:\t"); String intro = in.readLine(); generateHelp( new File(dir), name, icon, intro); }</code><technical_language>a do-while loop</technical_language>

Target:
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String dir = null; do { String status = null; do { System.out.print("Enter r/b/a for release/beta or alpha quality:\t"); String q = in.readLine(); if (q.equalsIgnoreCase("r")) { status = ""; } else if (q.equalsIgnoreCase("b")) { status = "_beta"; } else if (q.equalsIgnoreCase("a")) { status = "_alpha"; } } while (status == null); System.out.print("Enter add-on package name:\t"); dir = "../zap-extensions" + status + "/src/org/zaproxy/zap/extension/" + in.readLine(); if (! new File(dir).isDirectory()) { System.out.println("dir is not a directory :( " + new File(dir).getAbsolutePath()); dir = null; } } while (dir == null); System.out.print("Enter the add-on 'friendly' name:\t"); String name = in.readLine(); System.out.print("Enter icon name (eg example.png) or just return for no icon:\t"); String icon = in.readLine(); if (icon.length() == 0) { icon = null; } System.out.print("Enter a one line summary of the add-on:\t"); String intro = in.readLine(); generateHelp( new File(dir), name, icon, intro); }
Source:
<code>public void generatesPlainSnippet() { Step step = new Step(Collections.<Comment>emptyList(), "Given ", "I have 4 cukes in my \"big\" belly", 0, null, null); String snippet = new SnippetGenerator(new ClojureSnippet()).getSnippet(step); String expected = "" + "(Given #\"^I have (\\d+) cukes in my \"([^\"]*)\" belly$\" [arg1, arg2]\n" + <START> <<<<<<< HEAD <END> " (comment Express the Regexp above with the code you wish you had ))\n"; assertEquals(expected, snippet); }</code><technical_language>keft this out</technical_language>

Target:
public void generatesPlainSnippet() { Step step = new Step(Collections.<Comment>emptyList(), "Given ", "I have 4 cukes in my \"big\" belly", 0, null, null); String snippet = new SnippetGenerator(new ClojureSnippet()).getSnippet(step); String expected = "" + "(Given #\"^I have (\\d+) cukes in my \"([^\"]*)\" belly$\" [arg1, arg2]\n" + " (comment Express the Regexp above with the code you wish you had ))\n"; assertEquals(expected, snippet); }
Source:
<code>public Optional getCarrier() { <START> return Optional.empty(); END> }</code><technical_language>Could, technically, throw a mixin net.minecraft.entity.passive.AbstractHorse#initHorseChest set carrier</technical_language>

Target:
public Optional<Carrier> getCarrier() { return Optional.ofNullable(this.carrier); }
Source:
<code>public String getChartType() { <START> return "png"; <END> }</code><technical_language>define strings a constant in ChartProvider interface</technical_language>

Target:
public ImageType getChartType() { return ImageType.png; }
Source:
<code>protected void replay(long windowId) throws SQLException { isReplayed = true; MutablePair<String, String> recoveredData = new MutablePair<String, String>(); try { recoveredData = (MutablePair<String, String>)windowManager.load(operatorId, windowId); if (recoveredData != null) { if (recoveredData.left == null || recoveredData.right == null) { return; } if (recoveredData.right.equals(rangeQueryPair.getValue()) || recoveredData.right.equals(previousUpperBound)) { LOG.info("Matched so returning"); return; } JdbcPollInputOperator jdbcPoller = new JdbcPollInputOperator(); jdbcPoller.setStore(store); jdbcPoller.setKey(getKey()); jdbcPoller.setPartitionCount(getPartitionCount()); <START> jdbcPoller.setPollInterval(50); <END> jdbcPoller.setTableName(getTableName()); jdbcPoller.setBatchSize(getBatchSize()); isPollable = false; LOG.debug("[Window ID -" + windowId + "," + recoveredData.left + "," + recoveredData.right + "]"); jdbcPoller.setRangeQueryPair(new KeyValPair<String, String>(recoveredData.left, recoveredData.right)); jdbcPoller.ps = jdbcPoller.store.getConnection().prepareStatement( JdbcMetaDataUtility.buildRangeQuery(jdbcPoller.getTableName(), jdbcPoller.getKey(), jdbcPoller.getRangeQueryPair().getKey(), jdbcPoller.getRangeQueryPair().getValue()), java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); LOG.info("Query formed for recovered data -" + jdbcPoller.ps.toString()); emitReplayedTuples(jdbcPoller.ps); } } catch (IOException e) { throw new RuntimeException("replay", e); } }</code><technical_language>this a constant? If so, declare this a _DEFAULT top</technical_language>

Target:
protected void replay(long windowId) throws SQLException { isReplayed = true; MutablePair<String, String> recoveredData = new MutablePair<String, String>(); try { recoveredData = (MutablePair<String, String>)windowManager.load(operatorId, windowId); if (recoveredData != null) { if (recoveredData.left == null || recoveredData.right == null) { return; } if (recoveredData.right.equals(rangeQueryPair.getValue()) || recoveredData.right.equals(previousUpperBound)) { LOG.info("Matched so returning"); return; } JdbcPollInputOperator jdbcPoller = new JdbcPollInputOperator(); jdbcPoller.setStore(store); jdbcPoller.setKey(getKey()); jdbcPoller.setPartitionCount(getPartitionCount()); jdbcPoller.setPollInterval(getPollInterval()); jdbcPoller.setTableName(getTableName()); jdbcPoller.setBatchSize(getBatchSize()); isPollable = false; LOG.debug("[Window ID -" + windowId + "," + recoveredData.left + "," + recoveredData.right + "]"); jdbcPoller.setRangeQueryPair(new KeyValPair<String, String>(recoveredData.left, recoveredData.right)); jdbcPoller.ps = jdbcPoller.store.getConnection().prepareStatement( JdbcMetaDataUtility.buildRangeQuery(jdbcPoller.getTableName(), jdbcPoller.getKey(), jdbcPoller.getRangeQueryPair().getKey(), jdbcPoller.getRangeQueryPair().getValue()), java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); LOG.info("Query formed for recovered data - {}", jdbcPoller.ps.toString()); emitReplayedTuples(jdbcPoller.ps); } } catch (IOException e) { throw new RuntimeException("replay", e); } }
Source:
<code>private void initTestForPool(StoragePool pool, List<Guid> vmGuids, List<Guid> templatesGuids, List<Guid> removedGuids) { Guid poolId = pool.getId(); doReturn(vmGuids).when(vmAndTemplatesGenerationsDao).getVmsIdsForOvfUpdate(poolId); doReturn(templatesGuids).when(vmAndTemplatesGenerationsDao).getVmTemplatesIdsForOvfUpdate(poolId); <START> doReturn(removedGuids).when(vmAndTemplatesGenerationsDao).getIdsForOvfDeletion(poolId); <END> pool.setStatus(StoragePoolStatus.Up); }</code><technical_language>Please add affinityGroup</technical_language>

Target:
private void initTestForPool(StoragePool pool, List<Guid> vmGuids, List<Guid> templatesGuids, List<Guid> removedGuids) { Guid poolId = pool.getId(); doReturn(vmGuids).when(vmAndTemplatesGenerationsDao).getVmsIdsForOvfUpdate(poolId); doReturn(templatesGuids).when(vmAndTemplatesGenerationsDao).getVmTemplatesIdsForOvfUpdate(poolId); doReturn(removedGuids).when(vmAndTemplatesGenerationsDao).getIdsForOvfDeletion(poolId); doReturn(Collections.EMPTY_LIST).when(affinityGroupDao).getAllAffinityGroupsByVmId(any()); pool.setStatus(StoragePoolStatus.Up); }
Source:
<code>private <X> ExtendedQueryResult<T> changeOrder(EntityViewDefaultQueryResult.ChangeOrder changeOrder) { lastPaginatedQuery = null; <START> if (!context.getRepositoryMethod().isQuery()) { <END> for (CriteriaBuilderPostProcessor processor : context.getCriteriaBuilderPostProcessors()) { if (processor instanceof OrderByCriteriaBuilderPostProcessor) { OrderByCriteriaBuilderPostProcessor orderBy = (OrderByCriteriaBuilderPostProcessor) processor; if (changeOrder.matches(orderBy)) { orderBy.changeDirection(); return this; } } } } else { for (QueryStringPostProcessor processor : context.getQueryStringPostProcessors()) { if (processor instanceof OrderByQueryStringPostProcessor) { OrderByQueryStringPostProcessor orderBy = (OrderByQueryStringPostProcessor) processor; if (changeOrder.matches(orderBy)) { orderBy.changeDirection(); return this; } } } } changeOrder.addDefault(); return this; }</code><technical_language>negative logic</technical_language>

Target:
private <X> ExtendedQueryResult<T> changeOrder(EntityViewDefaultQueryResult.ChangeOrder changeOrder) { lastPaginatedQuery = null; if (context.getRepositoryMethod().isQuery()) { for (QueryStringPostProcessor processor : context.getQueryStringPostProcessors()) { if (processor instanceof OrderByQueryStringPostProcessor) { OrderByQueryStringPostProcessor orderBy = (OrderByQueryStringPostProcessor) processor; if (changeOrder.matches(orderBy)) { orderBy.changeDirection(); return this; } } } } else { for (CriteriaBuilderPostProcessor processor : context.getCriteriaBuilderPostProcessors()) { if (processor instanceof OrderByCriteriaBuilderPostProcessor) { OrderByCriteriaBuilderPostProcessor orderBy = (OrderByCriteriaBuilderPostProcessor) processor; if (changeOrder.matches(orderBy)) { orderBy.changeDirection(); return this; } } } } changeOrder.addDefault(); return this; }
Source:
<code>AllureGenerateResult generate(Path sourceDir, Path targetDir) { try { forceMkdir(targetDir.toFile()); <START> final LinkedList<String> args = new LinkedList<>(asList("generate", "-c", "-o", targetDir.toString(), sourceDir.toString())); <END> String output; if (cmdLine.isUnix() && cmdLine.hasCommand(BASH_CMD)) { args.addFirst(cmdPath.toString()); output = cmdLine.runCommand("/bin/bash", args.toArray(new String[args.size()])); } else { output = cmdLine.runCommand(cmdPath.toString(), args.toArray(new String[args.size()])); } LOGGER.info(output); return cmdLine.parseGenerateOutput(output); } catch (IOException e) { throw new RuntimeException("Failed to generate allure report", e); } }</code><technical_language>Deque instead? do need clean output directory first</technical_language>

Target:
AllureGenerateResult generate(Path sourceDir, Path targetDir) { try { final LinkedList<String> args = new LinkedList<>(asList("generate", "-o", targetDir.toString(), sourceDir.toString())); String output; if (cmdLine.isUnix() && cmdLine.hasCommand(BASH_CMD)) { args.addFirst(cmdPath.toString()); output = cmdLine.runCommand("/bin/bash", args.toArray(new String[args.size()])); } else { output = cmdLine.runCommand(cmdPath.toString(), args.toArray(new String[args.size()])); } LOGGER.info(output); return cmdLine.parseGenerateOutput(output); } catch (Exception e) { throw new RuntimeException("Failed to generate allure report", e); } }
Source:
<code>public void emptyStringToSynapseFriendlyName() { assertEquals("", BridgeUtils.toSynapseFriendlyName(" #")); <START> } <END></code><technical_language>If result is empty string, error</technical_language>

Target:
public void emptyStringToSynapseFriendlyName() { BridgeUtils.toSynapseFriendlyName(" #"); }
Source:
<code>public List<String> executeTests() throws MojoExecutionException { JMeterArgumentsArray thisTestArgs = baseTestArgs; List<String> tests = generateTestList(); List<String> results = new ArrayList<String>(); <START> SimpleDateFormat sdf = new SimpleDateFormat(REPORT_DIR_DATE_FORMAT); <END> for (String file : tests) { if(generateReports) { thisTestArgs.setReportsDirectory(reportDirectory+"/"+ FilenameUtils.getBaseName(file)+"_"+ sdf.format(new Date())); } if (remoteServerConfiguration != null) { if ((remoteServerConfiguration.isStartServersBeforeTests() && tests.get(0).equals(file)) || remoteServerConfiguration.isStartAndStopServersForEachTest()) { thisTestArgs.setRemoteStart(); thisTestArgs.setRemoteStartServerList(remoteServerConfiguration.getServerList()); } if ((remoteServerConfiguration.isStopServersAfterTests() && tests.get(tests.size() - 1).equals(file)) || remoteServerConfiguration.isStartAndStopServersForEachTest()) { thisTestArgs.setRemoteStop(); } } results.add(executeSingleTest(new File(testFilesDirectory, file), thisTestArgs)); try { TimeUnit.SECONDS.sleep(postTestPauseInSeconds); } catch (InterruptedException ignored) { } } return results; }</code><technical_language>JodaTime for date formats, this consistent</technical_language>

Target:
public List<String> executeTests() throws MojoExecutionException { JMeterArgumentsArray thisTestArgs = baseTestArgs; List<String> tests = generateTestList(); List<String> results = new ArrayList<String>(); DateTimeFormatter sdf = new DateTimeFormatterBuilder().appendPattern(REPORT_DIR_DATE_FORMAT).toFormatter(); for (String file : tests) { if(generateReports) { thisTestArgs.setReportsDirectory(reportDirectory+"/"+ FilenameUtils.getBaseName(file)+"_"+ sdf.print(new DateTime())); } if (remoteServerConfiguration != null) { if ((remoteServerConfiguration.isStartServersBeforeTests() && tests.get(0).equals(file)) || remoteServerConfiguration.isStartAndStopServersForEachTest()) { thisTestArgs.setRemoteStart(); thisTestArgs.setRemoteStartServerList(remoteServerConfiguration.getServerList()); } if ((remoteServerConfiguration.isStopServersAfterTests() && tests.get(tests.size() - 1).equals(file)) || remoteServerConfiguration.isStartAndStopServersForEachTest()) { thisTestArgs.setRemoteStop(); } } results.add(executeSingleTest(new File(testFilesDirectory, file), thisTestArgs)); try { TimeUnit.SECONDS.sleep(postTestPauseInSeconds); } catch (InterruptedException ignored) { } } return results; }
Source:
<code>public static void initialize(Props props) { logger.info("Initializing"); <START> instance = new JobCallbackManager(props); <END> isInitialized = true; }</code><technical_language>return right if initialized already</technical_language>

Target:
public static void initialize(Props props) { if (isInitialized) { logger.info("Already initialized"); return; } logger.info("Initializing"); instance = new JobCallbackManager(props); isInitialized = true; }
Source:
<code>public void flushAll( IPentahoSession session ) { final Lock writeLock = cacheLock.writeLock(); try { writeLock.lock(); resetCache( session ); flushHostedAndRemote( session ); <START> MondrianServer mondrianServer = <END> ( server != null ) ? server : MondrianServer.forId( null ); mondrianServer.getAggregationManager().getCacheControl( null, null ).flushSchemaCache(); } catch ( Exception e ) { throw new IOlapServiceException( e ); } finally { writeLock.unlock(); } }</code><technical_language>need clear server instances. bug states inconsistent methods for acquiring a mondrian instance tools. patch address that, implements workaround outlined in case. multiple instances alive, call flushSchemaCache() line active mondrian server (this.server) Id "null". clear one, other</technical_language>

Target:
public void flushAll( IPentahoSession session ) { final Lock writeLock = cacheLock.writeLock(); try { writeLock.lock(); resetCache( session ); flushHostedAndRemote( session ); if ( server != null ) { server.getAggregationManager().getCacheControl( null, null ).flushSchemaCache(); } MondrianServer.forId( null ).getAggregationManager().getCacheControl( null, null ).flushSchemaCache(); } catch ( Exception e ) { throw new IOlapServiceException( e ); } finally { writeLock.unlock(); } }
Source:
<code>public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { SymbolicValue currentVal = context.getState().peekValue(); if (currentVal == null) { return context.getState(); } Tree toCheck = syntaxNode; if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree methodInvocation = (MethodInvocationTree) syntaxNode; toCheck = methodInvocation.methodSelect(); <START> if (ExplodedGraphWalker.isObjectsMethod(methodInvocation, REQUIRE_NON_NULL_METHOD_NAME, 1)) { <END> final List<SymbolicValue> values = context.getState().peekValues(2); return context.getState().addConstraint(values.get(1), ObjectConstraint.NOT_NULL); } else if (ExplodedGraphWalker.isObjectsMethod(methodInvocation, REQUIRE_NON_NULL_METHOD_NAME, 2) || ExplodedGraphWalker.isObjectsMethod(methodInvocation, REQUIRE_NON_NULL_METHOD_NAME, 2)) { final List<SymbolicValue> values = context.getState().peekValues(3); return context.getState().addConstraint(values.get(2), ObjectConstraint.NOT_NULL); } } if (toCheck.is(Tree.Kind.MEMBER_SELECT)) { return checkMemberSelect(context, (MemberSelectExpressionTree) toCheck, currentVal); } return context.getState(); }</code><technical_language>if statements unified a number of parameters in a step</technical_language>

Target:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { SymbolicValue currentVal = context.getState().peekValue(); if (currentVal == null) { return context.getState(); } Tree toCheck = syntaxNode; if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree methodInvocation = (MethodInvocationTree) syntaxNode; toCheck = methodInvocation.methodSelect(); if (isObjectsRequireNonNullMethod(methodInvocation.symbol())) { int numberArguments = methodInvocation.arguments().size(); List<SymbolicValue> values = context.getState().peekValues(numberArguments + 1); return context.getState().addConstraint(values.get(numberArguments), ObjectConstraint.NOT_NULL); } } if (toCheck.is(Tree.Kind.MEMBER_SELECT)) { return checkMemberSelect(context, (MemberSelectExpressionTree) toCheck, currentVal); } return context.getState(); }
Source:
<code>public boolean requestArmMode(String armMode, String pinCode) { <START> logger.debug("requestArmMode(): armMode = {}", armMode == null ? "null" : armMode); <END> boolean done = false; HashMap<String, Byte> codes = new HashMap<String, Byte>(); codes.put("Disarmed", (byte) 0x00); codes.put("Stay", (byte) 0x04); codes.put("Armed", (byte) 0x05); codes.put("StayInstant", (byte) 0x14); codes.put("ArmedInstant", (byte) 0x15); codes.put("Night", (byte) 0x04); codes.put("NightInstant", (byte) 0x14); Byte code = codes.get(armMode); if (code == null) { logger.warn("PowerMax alarm binding: invalid requested arm mode: {}", armMode); } else if ((pinCode == null) || (pinCode.length() != 4)) { logger.warn("PowerMax alarm binding: requested arm mode rejected due to invalid PIN code: {}", armMode); } else { try { byte[] dynPart = new byte[3]; dynPart[0] = code; dynPart[1] = (byte) Integer.parseInt(pinCode.substring(0, 2), 16); dynPart[2] = (byte) Integer.parseInt(pinCode.substring(2, 4), 16); done = sendMessage(new PowerMaxBaseMessage(PowerMaxSendType.ARM, dynPart), false, 0); } catch (NumberFormatException e) { logger.warn("PowerMax alarm binding: requested arm mode rejected due to invalid PIN code: {}", armMode); } } return done; }</code><technical_language>I thought if armMode is null, logger class do ternary operator</technical_language>

Target:
public boolean requestArmMode(String armMode, String pinCode) { logger.debug("requestArmMode(): armMode = {}", armMode); boolean done = false; HashMap<String, Byte> codes = new HashMap<String, Byte>(); codes.put("Disarmed", (byte) 0x00); codes.put("Stay", (byte) 0x04); codes.put("Armed", (byte) 0x05); codes.put("StayInstant", (byte) 0x14); codes.put("ArmedInstant", (byte) 0x15); codes.put("Night", (byte) 0x04); codes.put("NightInstant", (byte) 0x14); Byte code = codes.get(armMode); if (code == null) { logger.warn("PowerMax alarm binding: invalid requested arm mode: {}", armMode); } else if ((pinCode == null) || (pinCode.length() != 4)) { logger.warn("PowerMax alarm binding: requested arm mode rejected due to invalid PIN code: {}", armMode); } else { try { byte[] dynPart = new byte[3]; dynPart[0] = code; dynPart[1] = (byte) Integer.parseInt(pinCode.substring(0, 2), 16); dynPart[2] = (byte) Integer.parseInt(pinCode.substring(2, 4), 16); done = sendMessage(new PowerMaxBaseMessage(PowerMaxSendType.ARM, dynPart), false, 0); } catch (NumberFormatException e) { logger.warn("PowerMax alarm binding: requested arm mode rejected due to invalid PIN code: {}", armMode); } } return done; }
Source:
<code>public List<IEventDeclaration> getEventDeclarations() { <START> ImmutableList.Builder<IEventDeclaration> builder = new ImmutableList.Builder<>(); <END> for (IEventDeclaration ied : fEvents) { if (ied != null) { builder.add(ied); } } return builder.build(); }</code><technical_language>I fail reason ImmutableList needed here. ArrayList internally right</technical_language>

Target:
public List<IEventDeclaration> getEventDeclarations() { ArrayList<IEventDeclaration> retVal = new ArrayList<>(fEvents); retVal.removeAll(Collections.singletonList(null)); return retVal; }
Source:
<code>protected boolean canDoAction() { boolean canDo; canDo = vdsGroupExists() && changesAreClusterCompatible() && logicalNetworkExists(); if (canDo) { <START> NetworkClusterValidator validator = <END> new NetworkClusterValidator(getNetworkCluster(), getVdsGroup().getcompatibility_version()); canDo = (!NetworkUtils.isManagementNetwork(getNetwork()) || validate(validator.managementNetworkAttachment(getNetworkName()))) && validate(validator.migrationPropertySupported(getNetworkName())); } return canDo; }</code><technical_language>I put this block in a separate method (i.e. validateAttachment()) do like: return vdsGroupExists() && changesAreClusterCompatible() && logicalNetworkExists() && validateAttachment();</technical_language>

Target:
protected boolean canDoAction() { return vdsGroupExists() && changesAreClusterCompatible() && logicalNetworkExists() && validateAttachment(); }
Source:
<code>private String getOwnerText(IRepositoryElement element) { <START> if (element instanceof TaskTask) { <END> String owner = ((ITask) element).getOwner(); if (!Strings.isNullOrEmpty(owner)) { return NLS.bind(Messages.TaskListToolTip_Assigned_to_X, owner); } return NLS.bind(Messages.TaskListToolTip_Assigned_to_X, Messages.TaskListToolTip_Unassigned); } return null; }</code><technical_language>check instanceof LocalTask explicitly exclude those</technical_language>

Target:
private String getOwnerText(IRepositoryElement element) { if (element instanceof ITask && !(element instanceof LocalTask)) { String owner = ((ITask) element).getOwner(); if (!Strings.isNullOrEmpty(owner)) { return NLS.bind(Messages.TaskListToolTip_Assigned_to_X, owner); } return NLS.bind(Messages.TaskListToolTip_Assigned_to_X, Messages.TaskListToolTip_Unassigned); } return null; }
Source:
<code>private static Node compileFile(File file, String outDir) throws IOException, URISyntaxException { <START> Node preludeTree = generateIRTree(new File(App.class.getResource("Prelude.bla").toURI())); <END> Node programTree = generateIRTree(file); Node combinedTree = ((ProgramNode) preludeTree).addTree((ProgramNode) programTree); new File(outDir).mkdirs(); ASTVisitor graphVisitor = new Graphvizitor(outDir); combinedTree.accept(graphVisitor); IntrospectionPass introspectionPass = new IntrospectionPass(); combinedTree.accept(introspectionPass); ScopeChecker scopeVisitor = new ScopeChecker(); combinedTree.accept(scopeVisitor); ASTVisitor bytecodeVisitor = new BytecodeGenerator(outDir); combinedTree.accept(bytecodeVisitor); return combinedTree; }</code><technical_language>I URISyntaxException - pass a filename a stream generateIRTree instead of a file</technical_language>

Target:
private static Node compileFile(File file, String outDir) throws IOException { Node preludeTree = generateIRTree(App.class.getResourceAsStream("Prelude.bla"), "Babble\\Prelude.bla"); Node programTree = generateIRTree(new FileInputStream(file), file.getPath()); Node combinedTree = ((ProgramNode) preludeTree).addTree((ProgramNode) programTree); new File(outDir).mkdirs(); ASTVisitor graphVisitor = new Graphvizitor(outDir); combinedTree.accept(graphVisitor); IntrospectionPass introspectionPass = new IntrospectionPass(); combinedTree.accept(introspectionPass); ScopeChecker scopeVisitor = new ScopeChecker(); combinedTree.accept(scopeVisitor); ASTVisitor bytecodeVisitor = new BytecodeGenerator(outDir); combinedTree.accept(bytecodeVisitor); return combinedTree; }
Source:
<code>public void validateIncompatibleJavadocCheckNames() throws IOException { final Stream<Class<?>> abstractJavadocCheckNames = CheckUtil.getCheckstyleChecks() .stream() .filter(AbstractJavadocCheck.class::isAssignableFrom); <START> final Stream<Class<?>> otherJavadocCheckNames = Stream.of(JavadocStyleCheck.class); <END> final Set<Class<?>> javadocCheckNames = Stream.concat(abstractJavadocCheckNames, otherJavadocCheckNames) .collect(Collectors.toSet()); assertWithMessage("INCOMPATIBLE_JAVADOC_CHECK_NAMES should contains all descendants " + "of AbstractJavadocCheck") .that(CheckUtil.getSimpleNames(javadocCheckNames)) .isEqualTo(INCOMPATIBLE_JAVADOC_CHECK_NAMES); }</code><technical_language>is other checks join this list. Please move a field</technical_language>

Target:
public void validateIncompatibleJavadocCheckNames() throws IOException { final Set<Class<?>> abstractJavadocCheckNames = CheckUtil.getCheckstyleChecks() .stream() .filter(AbstractJavadocCheck.class::isAssignableFrom) .collect(Collectors.toSet()); abstractJavadocCheckNames.addAll(REGEXP_JAVADOC_CHECKS); assertWithMessage("INCOMPATIBLE_JAVADOC_CHECK_NAMES should contains all descendants " + "of AbstractJavadocCheck") .that(CheckUtil.getSimpleNames(abstractJavadocCheckNames)) .isEqualTo(INCOMPATIBLE_JAVADOC_CHECK_NAMES); }
Source:
<code>private Map<Address, Address> parseResponse(InputStream is) throws IOException, URISyntaxException { JsonValue jsonValue = Json.parse(readInputStream(is)); List<JsonValue> response = jsonValue.asArray().values(); Map<Address, Address> privateToPublicAddresses = new HashMap<Address, Address>(); for (JsonValue value : response) { String privateAddress = value.asObject().get(PRIVATE_ADDRESS_PROPERTY).asString(); String publicAdress = value.asObject().get(PUBLIC_ADDRESS_PROPERTY).asString(); <START> publicAdress = StringUtil.isNullOrEmptyAfterTrim(publicAdress) ? privateAddress : publicAdress; <END> Address publicAddr = createAddress(publicAdress); privateToPublicAddresses.put(new Address(privateAddress, publicAddr.getPort()), publicAddr); } return privateToPublicAddresses; }</code><technical_language>is this impossible design of rest service? do need this default value</technical_language>

Target:
private Map<Address, Address> parseResponse(InputStream is) throws IOException { JsonValue jsonValue = Json.parse(readInputStream(is)); List<JsonValue> response = jsonValue.asArray().values(); Map<Address, Address> privateToPublicAddresses = new HashMap<Address, Address>(); for (JsonValue value : response) { String privateAddress = value.asObject().get(PRIVATE_ADDRESS_PROPERTY).asString(); String publicAddress = value.asObject().get(PUBLIC_ADDRESS_PROPERTY).asString(); Address publicAddr = createAddress(publicAddress); privateToPublicAddresses.put(new Address(privateAddress, publicAddr.getPort()), publicAddr); } return privateToPublicAddresses; }
Source:
<code><START> public TriggerChannelTypeBuilderImpl(ChannelTypeUID channelTypeUID, String label) { <END> super(channelTypeUID, label); }</code><technical_language>is sufficient this c'tor package private</technical_language>

Target:
TriggerChannelTypeBuilderImpl(ChannelTypeUID channelTypeUID, String label) { super(channelTypeUID, label); }
Source:
<code>public void setRetryAnalyzer(Class<? extends IRetryAnalyzer> c) { <START> m_retryAnalyzer = null; <END> if (c == null) { return; } try { m_retryAnalyzer = c.newInstance(); } catch (InstantiationException | IllegalAccessException e) { } }</code><technical_language>If want clean this subject, default retryAnalyzer class a real IRetryAnalyzer warn users if provide is IRetryAnalyzer. allow prepare change of annotation definition (from Class Class<? extends IRetryAnalyzer>)</technical_language>

Target:
public void setRetryAnalyzer(Class<? extends IRetryAnalyzer> c) { if (isRetryAnalyzerNotTestNGInjected(c)) { m_retryAnalyzer = ClassHelper.newInstance(c); } }
Source:
<code>private JButton getBtnApply() { if (btnApply == null) { btnApply = new JButton(); btnApply.setText(Constant.messages.getString("history.filter.button.apply")); btnApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { filter.setOpcodes(wsUiHelper.getSelectedOpcodeIntegers()); filter.setDirection(wsUiHelper.getDirection()); try{ filter.setPayloadFilter(wsUiHelper.getPattern(),wsUiHelper.getRegexCheckbox().isSelected(), wsUiHelper.getCaseIgnoreCheckbox().isSelected(),wsUiHelper.getInverseCheckbox().isSelected()); <START> }catch(PatternSyntaxException patternException) { <END> if(wsUiHelper.getRegexCheckbox().isSelected() ) { View.getSingleton().showWarningDialog(Constant.messages.getString("filter.replacedialog.invalidpattern")); wsUiHelper.getPatternTextField().grabFocus(); return; } } exitResult = JOptionPane.OK_OPTION; WebSocketMessagesViewFilterDialog.this.dispose(); } }); } return btnApply; }</code><technical_language>I suggest validating instead, e.g. WebSocketMessagesViewFilter.isValidPattern</technical_language>

Target:
private JButton getBtnApply() { if (btnApply == null) { btnApply = new JButton(); btnApply.setText(Constant.messages.getString("history.filter.button.apply")); btnApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { filter.setOpcodes(wsUiHelper.getSelectedOpcodeIntegers()); filter.setDirection(wsUiHelper.getDirection()); if(filter.isValidPattern(wsUiHelper.getPattern(), wsUiHelper.getRegexCheckbox().isSelected())) { filter.setPayloadFilter(wsUiHelper.getPattern(), wsUiHelper.getRegexCheckbox().isSelected(), wsUiHelper.getCaseIgnoreCheckbox().isSelected(), wsUiHelper.getInverseCheckbox().isSelected()); }else{ View.getSingleton().showWarningDialog(Constant.messages.getString("filter.replacedialog.invalidpattern")); wsUiHelper.getPatternTextField().requestFocusInWindow(); return; } exitResult = JOptionPane.OK_OPTION; WebSocketMessagesViewFilterDialog.this.dispose(); } }); } return btnApply; }
Source:
<code>private void scan(boolean isBackground) { for (MDNSDiscoveryParticipant participant : participants) { long start = System.currentTimeMillis(); ServiceInfo[] services; if (isBackground) { services = mdnsClient.list(participant.getServiceType()); } else { services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT); } logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(), <START> (System.currentTimeMillis() - start)); <END> for (ServiceInfo service : services) { DiscoveryResult result = participant.createResult(service); if (result != null) { thingDiscovered(result); } } } for (org.eclipse.smarthome.io.transport.mdns.discovery.MDNSDiscoveryParticipant participant : oldParticipants) { long start = System.currentTimeMillis(); ServiceInfo[] services; if (isBackground) { services = mdnsClient.list(participant.getServiceType()); } else { services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT); } logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(), (System.currentTimeMillis() - start)); for (ServiceInfo service : services) { DiscoveryResult result = participant.createResult(service); if (result != null) { thingDiscovered(result); } } } }</code><technical_language>reason for braces System.currentTimeMillis() - start? useless</technical_language>

Target:
private void scan(boolean isBackground) { for (MDNSDiscoveryParticipant participant : participants) { long start = System.currentTimeMillis(); ServiceInfo[] services; if (isBackground) { services = mdnsClient.list(participant.getServiceType()); } else { services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT); } logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(), System.currentTimeMillis() - start); for (ServiceInfo service : services) { DiscoveryResult result = participant.createResult(service); if (result != null) { thingDiscovered(result); } } } for (org.eclipse.smarthome.io.transport.mdns.discovery.MDNSDiscoveryParticipant participant : oldParticipants) { long start = System.currentTimeMillis(); ServiceInfo[] services; if (isBackground) { services = mdnsClient.list(participant.getServiceType()); } else { services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT); } logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(), System.currentTimeMillis() - start); for (ServiceInfo service : services) { DiscoveryResult result = participant.createResult(service); if (result != null) { thingDiscovered(result); } } } }
Source:
<code>public void testConflictedAttachment() throws Exception { Map<String, Object> foo1 = new HashMap<String, Object>(); foo1.put("_id", "doc-a"); Map<String, Object> atts = new HashMap<String, Object>(); Map<String, String> att = new HashMap<String, String>(); foo1.put("_attachments", atts); atts.put("att1", att); att.put("content_type", "text/plain"); att.put("data", "aGVsbG8="); foo1.put("foo", "(from remoteDb)"); Response response = remoteDb.create(foo1); MutableDocumentRevision rev = new MutableDocumentRevision(); rev.docId = "doc-a"; rev.body = DocumentBodyFactory.create("{\"foo\": \"local\"}".getBytes()); rev.attachments.put("att1", new UnsavedStreamAttachment( new ByteArrayInputStream("hello universe".getBytes()), "att1", "text/plain") ); this.datastore.createDocumentFromRevision(rev); this.push(); this.datastoreManager.deleteDatastore(this.datastore.getDatastoreName()); this.datastore = (DatastoreExtended)this.datastoreManager.openDatastore("foo-bar-baz"); this.pull(); DocumentRevision gotRev = this.datastore.getDocument("doc-a"); Assert.assertEquals(gotRev.getAttachments().size(), 1); Assert.assertEquals(gotRev.getBody().asMap().get("foo"), "local"); Assert.assertFalse(TestUtils.streamsEqual(gotRev.getAttachments().get("att1").getInputStream(), new ByteArrayInputStream("hello".getBytes()))); <START> Assert.assertTrue(TestUtils.streamsEqual(gotRev.getAttachments().get("att1").getInputStream(), new ByteArrayInputStream("hello universe".getBytes()))); <END> }</code><technical_language>Line length</technical_language>

Target:
public void testConflictedAttachment() throws Exception { Map<String, Object> foo1 = new HashMap<String, Object>(); foo1.put("_id", "doc-a"); Map<String, Object> atts = new HashMap<String, Object>(); Map<String, String> att = new HashMap<String, String>(); foo1.put("_attachments", atts); atts.put("att1", att); att.put("content_type", "text/plain"); att.put("data", "aGVsbG8="); foo1.put("foo", "(from remoteDb)"); Response response = remoteDb.create(foo1); MutableDocumentRevision rev = new MutableDocumentRevision(); rev.docId = "doc-a"; rev.body = DocumentBodyFactory.create("{\"foo\": \"local\"}".getBytes()); MutableDocumentRevision rev2 = this.datastore.createDocumentFromRevision(rev).mutableCopy(); rev2.attachments.put("att1", new UnsavedStreamAttachment( new ByteArrayInputStream("hello universe".getBytes()), "att1", "text/plain") ); this.datastore.updateDocumentFromRevision(rev2); this.push(); this.datastoreManager.deleteDatastore(this.datastore.getDatastoreName()); this.datastore = (DatastoreExtended)this.datastoreManager.openDatastore("foo-bar-baz"); this.pull(); DocumentRevision gotRev = this.datastore.getDocument("doc-a"); Assert.assertEquals(gotRev.getAttachments().size(), 1); Assert.assertEquals(gotRev.getBody().asMap().get("foo"), "local"); Assert.assertFalse(TestUtils.streamsEqual(gotRev.getAttachments().get("att1").getInputStream(), new ByteArrayInputStream("hello".getBytes()))); Assert.assertTrue(TestUtils.streamsEqual(gotRev.getAttachments().get("att1").getInputStream(), new ByteArrayInputStream("hello universe".getBytes()))); }
Source:
<code>public void shouldUseCollectionConverterWhenItExists() { String expectedResult = "[\"testing\"]"; <START> GsonJSONSerialization serialization = new GsonJSONSerialization(response, extractor, initializer, createBuilder(new CollectionSerializer()), serializee); <END> serialization.withoutRoot().from(new MyCollection()).serialize(); assertThat(result(), is(equalTo(expectedResult))); }</code><technical_language>extract another method here: java JSONSerialization serialization = serializationWithAdapter(new CollectionSerializer()); //... public JSONSerialization serializationWithAdapter(JsonSerializer adapter) { return new GsonJSONSerialization(response, extractor, initializer, createBuilder(adapter), serializee); } express test intent</technical_language>

Target:
public void shouldUseCollectionConverterWhenItExists() { GsonJSONSerialization serialization = serializationWithAdapter(new CollectionSerializer()); String expectedResult = "[\"testing\"]"; serialization.withoutRoot().from(new MyCollection()).serialize(); assertThat(result(), is(equalTo(expectedResult))); }
Source:
<code>public void write() throws StoreException { final Timer.Context context = metrics.indexFlushTime.time(); try { if (indexes.size() > 0) { Map.Entry<Long, IndexSegment> lastEntry = indexes.lastEntry(); IndexSegment currentInfo = lastEntry.getValue(); long fileEndPointerBeforeFlush = log.getLogEndOffset(); log.flush(); long lastOffset = lastEntry.getKey(); IndexSegment prevInfo = indexes.size() > 1 ? indexes.lowerEntry(lastOffset).getValue() : null; long currentLogEndPointer = log.getLogEndOffset(); while (prevInfo != null && !prevInfo.isMapped()) { if (prevInfo.getEndOffset() > currentLogEndPointer) { String message = "The read only index cannot have a file end pointer " + prevInfo.getEndOffset() + " greater than the log end offset " + currentLogEndPointer; throw new StoreException(message, StoreErrorCodes.IOError); } logger.info("Index : " + dataDir + " writing prev index with end offset " + prevInfo.getEndOffset()); prevInfo.writeIndexToFile(prevInfo.getEndOffset()); prevInfo.map(true); Map.Entry<Long, IndexSegment> infoEntry = indexes.lowerEntry(prevInfo.getStartOffset()); prevInfo = infoEntry != null ? infoEntry.getValue() : null; } <START> currentInfo.writeIndexToFile(fileEndPointerBeforeFlush); <END> } } catch (IOException e) { throw new StoreException("IO error while writing index to file", e, StoreErrorCodes.IOError); } finally { context.stop(); } }</code><technical_language>this change fix for IndexSegment</technical_language>

Target:
public void write() throws StoreException { final Timer.Context context = metrics.indexFlushTime.time(); try { if (indexes.size() > 0) { Map.Entry<Long, IndexSegment> lastEntry = indexes.lastEntry(); IndexSegment currentInfo = lastEntry.getValue(); long currentIndexEndOffsetBeforeFlush = currentInfo.getEndOffset(); long logEndOffsetBeforeFlush = log.getLogEndOffset(); if (logEndOffsetBeforeFlush < currentIndexEndOffsetBeforeFlush) { throw new StoreException("LogEndOffset " + logEndOffsetBeforeFlush + " before flush cannot be less than " + "currentEndOffSet of index " + currentIndexEndOffsetBeforeFlush, StoreErrorCodes.Illegal_Index_State); } log.flush(); long lastOffset = lastEntry.getKey(); IndexSegment prevInfo = indexes.size() > 1 ? indexes.lowerEntry(lastOffset).getValue() : null; long currentLogEndPointer = log.getLogEndOffset(); while (prevInfo != null && !prevInfo.isMapped()) { if (prevInfo.getEndOffset() > currentLogEndPointer) { String message = "The read only index cannot have a file end pointer " + prevInfo.getEndOffset() + " greater than the log end offset " + currentLogEndPointer; throw new StoreException(message, StoreErrorCodes.IOError); } logger.info("Index : " + dataDir + " writing prev index with end offset " + prevInfo.getEndOffset()); prevInfo.writeIndexToFile(prevInfo.getEndOffset()); prevInfo.map(true); Map.Entry<Long, IndexSegment> infoEntry = indexes.lowerEntry(prevInfo.getStartOffset()); prevInfo = infoEntry != null ? infoEntry.getValue() : null; } currentInfo.writeIndexToFile(currentIndexEndOffsetBeforeFlush); } } catch (IOException e) { throw new StoreException("IO error while writing index to file", e, StoreErrorCodes.IOError); } finally { context.stop(); } }