auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static synchronized TaskDescriptor getTaskDescriptor() { if (_identifier != null) { return _identifier; } try { Iterator<TaskDescriptor> identifiers = _loader.iterator(); if (identifiers.hasNext()) { _identifier = identifiers.next(); if (identifiers.hasNext()) { LOGGER.info("Found more than one provider for TaskDescriptor, picked first one"); } } else { LOGGER.error("No provider found for TaskDescriptor, falling back to DefaultTaskDescriptor"); _identifier = getDefaultTaskDescriptor(); } } catch (ServiceConfigurationError e) { LOGGER.error("Unable to load provider for TaskDescriptor, falling back to DefaultTaskDescriptor", e.getMessage()); _identifier = getDefaultTaskDescriptor(); } return _identifier; }

Target:
static synchronized TaskDescriptor getTaskDescriptor() { if (_identifier != null) { return _identifier; } try { Iterator<TaskDescriptor> identifiers = _loader.iterator(); if (identifiers.hasNext()) { _identifier = identifiers.next(); LOGGER.info("Using TaskDescriptor: " + _identifier.getClass()); while (identifiers.hasNext()) { TaskDescriptor descriptor = identifiers.next(); LOGGER.debug("Discarding TaskDescriptor: as its not first one to be loaded: ", descriptor.getClass()); } } else { LOGGER.info("No provider found for TaskDescriptor, falling back to DefaultTaskDescriptor"); _identifier = getDefaultTaskDescriptor(); } } catch (ServiceConfigurationError e) { LOGGER.error("Unable to load provider for TaskDescriptor, falling back to DefaultTaskDescriptor", e.getMessage()); _identifier = getDefaultTaskDescriptor(); } return _identifier; }
Source:
public ExternalMetadata(Map<String, Object> metadata) { this.metadata = metadata; }

Target:
public ExternalMetadata(Map<String, Object> metadata) { this.metadata = Map.copyOf(metadata); }
Source:
public DiskWriteModel getDisk(int deviceId) { return fDisks.computeIfAbsent(deviceId, k -> new DiskWriteModel(deviceId, checkNotNull(getStateSystemBuilder()))); }

Target:
public DiskWriteModel getDisk(int deviceId) { return fDisks.computeIfAbsent(deviceId, k -> new DiskWriteModel(k, checkNotNull(getStateSystemBuilder()))); }
Source:
public RecordWriter getRecordWriter(final HdfsSinkConnectorConfig conf, final String filename) { try { return new RecordWriter() { final Path path = new Path(filename); FileSystem fs = FileSystem.newInstance(path.toUri(), conf.getHadoopConfiguration()); final OutputStream out = fs.create(path); final OutputStreamWriter streamWriter = new OutputStreamWriter( out, Charset.defaultCharset() ); final BufferedWriter writer = new BufferedWriter(streamWriter, WRITER_BUFFER_SIZE); @Override public void write(SinkRecord record) { log.trace("Sink record: {}", record.toString()); try { String value = (String) record.value(); writer.write(value); writer.newLine(); } catch (IOException e) { throw new ConnectException(e); } } @Override public void commit() @Override public void close() { try { writer.close(); fs.close(); } catch (IOException e) { throw new ConnectException(e); } } }; } catch (IOException e) { throw new ConnectException(e); } }

Target:
public RecordWriter getRecordWriter(final HdfsSinkConnectorConfig conf, final String filename) { try { return new RecordWriter() { final Path path = new Path(filename); final FileSystem fs = FileSystem.newInstance(path.toUri(), conf.getHadoopConfiguration()); final OutputStream out = fs.create(path); final OutputStreamWriter streamWriter = new OutputStreamWriter( out, Charset.defaultCharset() ); final BufferedWriter writer = new BufferedWriter(streamWriter, WRITER_BUFFER_SIZE); @Override public void write(SinkRecord record) { log.trace("Sink record: {}", record.toString()); try { String value = (String) record.value(); writer.write(value); writer.newLine(); } catch (IOException e) { throw new ConnectException(e); } } @Override public void commit() @Override public void close() { IOException error = null; try { writer.close(); } catch (IOException e) { error = e; throw new ConnectException(e); } finally { try { fs.close(); } catch (IOException e) { if (error == null) { throw new ConnectException(e); } } } } }; } catch (IOException e) { throw new ConnectException(e); } }
Source:
public Signature resolveOperator(OperatorType operatorType, List<? extends Type> argumentTypes) throws OperatorNotFoundException { try { return operatorNamespace.resolveOperator(operatorType, argumentTypes); } catch (PrestoException e) { if (!(e instanceof OperatorNotFoundException)) { throw e; } } throw new OperatorNotFoundException( operatorType, argumentTypes.stream() .map(Type::getTypeSignature) .collect(toImmutableList())); }

Target:
public Signature resolveOperator(OperatorType operatorType, List<? extends Type> argumentTypes) { return globalFunctionNamespace.resolveOperator(operatorType, argumentTypes); }
Source:
public static void initEnvironment() { if(!integrationTestsStarted) { File testBranchFolder = TestResourceFile.getResourceFile("org/scenarioo/rest/testConfiguration"); System.setProperty("scenarioo.data", testBranchFolder.getAbsolutePath()); ScenarioDocuBuildsManager.resetInstance(); integrationTestsStarted = true; } }

Target:
public static void initEnvironment() { if(!integrationTestsStarted) { ScenarioDocuBuildsManager.resetInstance(); integrationTestsStarted = true; } }
Source:
public static boolean isReservedCqlKeyword(String id) { return id != null && RESERVED_KEYWORDS.contains(id); }

Target:
public static boolean isReservedCqlKeyword(String id) { if (id == null) { return false; } int hash = caseInsensitiveHash(id); List<char[]> keywords = RESERVED_KEYWORDS.get(hash); if (keywords == null) { return false; } else { for (char[] keyword : keywords) { if (equalsIgnoreCaseAscii(id, keyword)) { return true; } } return false; } }
Source:
protected void setUp() throws Exception { source = "void foo() {\r\n\r\n for(int i = 0; i < 10; i++){\r\n\r\n }\r\n\r\n"; expectedSource = "void foo() {\r\n\tfor (int i = 0; i < 10; i++) {\r\n\t}\r\n}"; super.setUp(); }

Target:
protected void setUp() throws Exception { source = "void foo() {\n" + "\n" + " for(int i = 0; i < 10; i++){\n" + "\n" + " }\n" + "\n"; expectedSource = "void foo() {\n" + " for (int i = 0; i < 10; i++) {\n" + " }\n" + "}"; super.setUp(); }
Source:
public Optional<String> getReference() { if (isNullOrEmpty(transactionId) && isNullOrEmpty(payIdSub)) { return Optional.empty(); } return Optional.of(transactionId + "/" + payIdSub); }

Target:
public Optional<String> getReference() { if (isNullOrEmpty(transactionId) || isNullOrEmpty(payIdSub)) { return Optional.empty(); } return Optional.of(transactionId + "/" + payIdSub); }
Source:
protected boolean validate() { NetworkValidator validator = new NetworkValidator(vmDao, networkDao.get(getNetworkId())); return validate(validator.networkIsSet(getNetworkId())) && validate(validator.notRemovingManagementNetwork()) && validate(validator.notIscsiBondNetwork()) && validate(validator.networkNotUsedByVms()) && validate(validator.networkNotUsedByTemplates()) && validate(getRemoveExternalNetworkValidationResult()); }

Target:
protected boolean validate() { NetworkValidator validator = new NetworkValidator(vmDao, getNetwork()); return validate(validator.networkIsSet(getNetworkId())) && validate(validator.notRemovingManagementNetwork()) && validate(validator.notIscsiBondNetwork()) && validate(validator.networkNotUsedByVms()) && validate(validator.networkNotUsedByTemplates()) && validate(getRemoveExternalNetworkValidationResult()); }
Source:
public Object[][] getEmptyArrays(){ final String BAM = BamFileIoUtils.BAM_FILE_EXTENSION; final String SAM = IOUtil.SAM_FILE_EXTENSION; final String CRAM = CramIO.CRAM_FILE_EXTENSION; return new Object[][]{ {new int[0], int[].class, BAM}, {new short[0], short[].class, BAM}, {new byte[0], byte[].class, BAM}, {new float[0], float[].class, BAM}, {new int[0], int[].class, SAM}, {new short[0], short[].class, SAM}, {new byte[0], byte[].class, SAM}, {new float[0], float[].class, SAM}, {new int[0], int[].class, CRAM}, {new short[0], short[].class, CRAM}, {new byte[0], byte[].class, CRAM}, {new float[0], float[].class, CRAM}, }; }

Target:
private static Object[][] getEmptyArrays() { return new Object[][]{ {new int[0], int[].class}, {new short[0], short[].class}, {new byte[0], byte[].class}, {new float[0], float[].class}, }; }
Source:
public static STGroup findStringTemplateGroup(ClassLoader classLoader, String path) { final STGroup cached = CACHE.get(path); if (cached != null) { return cached; } synchronized (StringTemplateSqlLocator.class) { return CACHE.computeIfAbsent(path, p -> readStringTemplateGroup(classLoader, path)); } }

Target:
public static STGroup findStringTemplateGroup(ClassLoader classLoader, String path) { return CACHE.computeIfAbsent(path, p -> ThreadLocal.withInitial(() -> readStringTemplateGroup(classLoader, path))).get(); }
Source:
public SequencerServer(ServerContext serverContext, SequencerFactoryHelper sequencerFactoryHelper) { this.serverContext = serverContext; this.sequencerFactoryHelper = sequencerFactoryHelper; Config config = Config.parse(serverContext.getServerConfig()); this.executor = serverContext.getExecutorService(1, "sequencer-"); this.globalLogTail = sequencerFactoryHelper.getGlobalLogTail(); this.cache = sequencerFactoryHelper.getSequencerServerCache( config.getCacheSize(), globalLogTail - 1 ); this.streamsAddressMap = sequencerFactoryHelper.getStreamAddressSpaceMap(); this.streamTailToGlobalTailMap = sequencerFactoryHelper.getStreamTailToGlobalTailMap(); this.txResolutionTimer = MeterRegistryProvider.getInstance().map(registry -> registry.timer("sequencer.tx-resolution.timer")); this.streamsPerTx = MeterRegistryProvider.getInstance().map(registry -> DistributionSummary.builder("sequencer.tx-resolution.num_streams") .baseUnit("stream") .publishPercentiles(0.50, 0.95, 0.99) .register(registry)); }

Target:
public SequencerServer(ServerContext serverContext, SequencerFactoryHelper sequencerFactoryHelper) { this.serverContext = serverContext; this.sequencerFactoryHelper = sequencerFactoryHelper; Config config = Config.parse(serverContext.getServerConfig()); this.executor = serverContext.getExecutorService(1, "sequencer-"); this.globalLogTail = sequencerFactoryHelper.getGlobalLogTail(); this.cache = sequencerFactoryHelper.getSequencerServerCache( config.getCacheSize(), globalLogTail - 1 ); this.streamsAddressMap = sequencerFactoryHelper.getStreamAddressSpaceMap(); this.streamTailToGlobalTailMap = sequencerFactoryHelper.getStreamTailToGlobalTailMap(); this.txResolutionTimer = MeterRegistryProvider.getInstance().map(registry -> registry.timer("sequencer.tx-resolution.timer")); this.streamsPerTx = MeterRegistryProvider.getInstance().map(registry -> DistributionSummary.builder("sequencer.tx-resolution.num_streams") .baseUnit("stream") .publishPercentiles(percentiles) .register(registry)); }
Source:
public void handleMessage(Message message) { Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS); List<String> authorizationHeader = headers.get(OAUTH); if (authorizationHeader == null || authorizationHeader.isEmpty()) { return; } LOGGER.debug("Setting access token to the authorization header."); headers.remove(OAUTH); headers.put(AUTHORIZATION, authorizationHeader); headers.remove(OAUTH); }

Target:
public void handleMessage(Message message) { Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS); List<String> authorizationHeader = headers.get(OAUTH); if (authorizationHeader == null || authorizationHeader.isEmpty()) { return; } LOGGER.debug("Setting access token to the authorization header."); headers.put(AUTHORIZATION, authorizationHeader); headers.remove(OAUTH); }
Source:
public Template persist(Template template) { if(Strings.isNullOrEmpty(body)) { StringBuilder sb = new StringBuilder(); for (Container container : containers) { sb.append("#parseContainer('").append(container.getIdentifier()).append("')") .append(System.getProperty("line.separator")); } template.setBody(sb.toString()); } else { template.setBody(body); } try { return templateAPI.saveTemplate(template, host, user, false); } catch (DotDataException | DotSecurityException e) { throw new RuntimeException(e); } }

Target:
public Template persist(Template template) { final String uuid = UUIDGenerator.generateUuid(); if(Strings.isNullOrEmpty(body)) { StringBuilder sb = new StringBuilder(); for (Map<String, String> containerMap : containers) { sb.append("#parseContainer(") .append(StringPool.APOSTROPHE) .append(containerMap.get("containerId")) .append(StringPool.APOSTROPHE) .append(StringPool.COMMA) .append(StringPool.APOSTROPHE) .append(containerMap.get("uuid")) .append(StringPool.APOSTROPHE) .append(")") .append(System.getProperty("line.separator")); } template.setBody(sb.toString()); } else { template.setBody(body); } try { return templateAPI.saveTemplate(template, host, user, false); } catch (DotDataException | DotSecurityException e) { throw new RuntimeException(e); } }
Source:
public void search_shouldReturnAllReportTemplatesByGivenPublisher() throws Exception { MockHttpServletRequest mrrtReportTemplateRequest = request(RequestMethod.GET, getURI()); mrrtReportTemplateRequest.setParameter(MrrtReportTemplateSearchHandler.REQUEST_PARAM_PUBLISHER, PUBLISHER_QUERY); mrrtReportTemplateRequest.setParameter("v", Representation.FULL.getRepresentation()); SimpleObject resultMrrtReportTemplate = deserialize(handle(mrrtReportTemplateRequest)); assertNotNull(resultMrrtReportTemplate); List<Object> hits = (List<Object>) resultMrrtReportTemplate.get("results"); MrrtReportTemplateSearchCriteria searchCriteria = new MrrtReportTemplateSearchCriteria.Builder().withPublisher(PUBLISHER_QUERY) .build(); assertThat(hits.size(), is(1)); assertThat(PropertyUtils.getProperty(hits.get(0), "uuid"), is(mrrtReportTemplateService.getMrrtReportTemplates(searchCriteria) .get(0) .getUuid())); assertNull(PropertyUtils.getProperty(resultMrrtReportTemplate, "totalCount")); }

Target:
public void search_shouldReturnAllReportTemplatesByGivenPublisher() throws Exception { MockHttpServletRequest mrrtReportTemplateRequest = request(RequestMethod.GET, getURI()); mrrtReportTemplateRequest.setParameter(MrrtReportTemplateSearchHandler.REQUEST_PARAM_PUBLISHER, PUBLISHER_QUERY); SimpleObject resultMrrtReportTemplate = deserialize(handle(mrrtReportTemplateRequest)); assertNotNull(resultMrrtReportTemplate); List<Object> hits = (List<Object>) resultMrrtReportTemplate.get("results"); MrrtReportTemplateSearchCriteria searchCriteria = new MrrtReportTemplateSearchCriteria.Builder().withPublisher(PUBLISHER_QUERY) .build(); assertThat(hits.size(), is(1)); assertThat(PropertyUtils.getProperty(hits.get(0), "uuid"), is(mrrtReportTemplateService.getMrrtReportTemplates(searchCriteria) .get(0) .getUuid())); assertNull(PropertyUtils.getProperty(resultMrrtReportTemplate, "totalCount")); }
Source:
private String getColSeparator(String format) { switch (format) { case "csv": return ","; case "tsv": return " "; case "psv": return "|"; default: throw new IllegalArgumentException( String.format("Invalid format '%s'. Must be one of %s", format, Joiner.on(',').join(FORMATS))); } }

Target:
private String getColSeparator(String format) { switch (SeparatorFormat.valueOf(format.toUpperCase())) { case CSV: return ","; case TSV: return " "; case PSV: return "|"; default: throw new IllegalArgumentException( String.format("Invalid format '%s'. Must be one of %s", format, EnumSet.allOf(SeparatorFormat.class))); } }
Source:
public void openFolderInTerminalTest() { seleniumWebDriver.navigate().refresh(); projectExplorer.waitProjectExplorer(); projectExplorer.waitAndSelectItem(PROJECT_NAME); projectExplorer.expandPathInProjectExplorer(PROJECT_NAME + PATH_TO_EXPAND); projectExplorer.waitAndSelectItem(PROJECT_NAME + PATH_TO_EXPAND); projectExplorer.openContextMenuByPathSelectedItem(PROJECT_NAME + PATH_TO_EXPAND); projectExplorer.waitContextMenu(); projectExplorer.clickOnItemInContextMenu(OPEN_IN_TERMINAL); terminal.waitNumberTerminalTab(2); String terminalWorkDir = terminal.getVisibleTextFromTerminal(); Assert.assertTrue(terminalWorkDir.trim().endsWith(PROJECT_NAME + PATH_TO_EXPAND + "$")); projectExplorer.waitAndSelectItem(PROJECT_NAME + FILE); projectExplorer.openContextMenuByPathSelectedItem(PROJECT_NAME + FILE); projectExplorer.waitContextMenu(); projectExplorer.clickOnItemInContextMenu(OPEN_IN_TERMINAL); terminal.waitNumberTerminalTab(3); terminalWorkDir = terminal.getVisibleTextFromTerminal(); Assert.assertTrue(terminalWorkDir.trim().endsWith(PROJECT_NAME + "$")); }

Target:
public void openFolderInTerminalTest() { seleniumWebDriver.navigate().refresh(); projectExplorer.waitProjectExplorer(); projectExplorer.waitAndSelectItem(PROJECT_NAME); projectExplorer.expandPathInProjectExplorer(PROJECT_NAME + PATH_TO_EXPAND); projectExplorer.waitAndSelectItem(PROJECT_NAME + PATH_TO_EXPAND); projectExplorer.openContextMenuByPathSelectedItem(PROJECT_NAME + PATH_TO_EXPAND); projectExplorer.waitContextMenu(); projectExplorer.clickOnItemInContextMenu(OPEN_IN_TERMINAL); terminal.waitNumberTerminalTab(2); terminal.waitExpectedTextIntoTerminal(PROJECT_NAME + PATH_TO_EXPAND + "$"); projectExplorer.waitAndSelectItem(PROJECT_NAME + FILE); projectExplorer.openContextMenuByPathSelectedItem(PROJECT_NAME + FILE); projectExplorer.waitContextMenu(); projectExplorer.clickOnItemInContextMenu(OPEN_IN_TERMINAL); terminal.waitNumberTerminalTab(3); terminal.waitExpectedTextIntoTerminal(PROJECT_NAME + "$"); }
Source:
private StreamProperties unordered(boolean unordered) { if (unordered) { return new StreamProperties( distribution, exactColumnOrder, partitioningColumns, false, otherActualProperties != null ? ActualProperties.builderFrom(otherActualProperties).unordered(true).build() : null); } return this; }

Target:
private StreamProperties unordered(boolean unordered) { if (unordered) { ActualProperties updatedProperies = null; if (otherActualProperties != null) { updatedProperies = ActualProperties.builderFrom(otherActualProperties) .unordered(true) .build(); } return new StreamProperties( distribution, partitioningColumns, false, updatedProperies); } return this; }
Source:
public Builder setBaseDataDir(Optional<Path> baseDataDir) { this.baseDataDir = baseDataDir; return this; }

Target:
public Builder setBaseDataDir(Optional<Path> baseDataDir) { this.baseDataDir = requireNonNull(baseDataDir, "baseDataDir is null"); return this; }
Source:
public static Expr.NumericBinding withSuppliers(final Map<String, Supplier<Number>> bindings) { return new Expr.NumericBinding() { @Override public Number get(String name) { Supplier<Number> supplier = bindings.get(name); return supplier == null ? null : supplier.get(); } }; }

Target:
public static Expr.ObjectBinding withSuppliers(final Map<String, Supplier<Number>> bindings) { return new Expr.ObjectBinding() { @Override public Number get(String name) { Supplier<Number> supplier = bindings.get(name); return supplier == null ? null : supplier.get(); } }; }
Source:
public void testQueryIsNullOperator() { List<QueryParam> variables = list(isNotNull("var_a")); List<ProcessInstanceWithVarsDesc> data = advanceVariableDataService.queryProcessByVariables(emptyList(), variables, queryContext); if (queryContext.getCount() > 0) { Assert.assertThat(data.size(), is(queryContext.getCount())); } for (ProcessInstanceWithVarsDesc p : data) { Assert.assertNotNull(p.getVariables().get("var_a")); } }

Target:
public void testQueryIsNullOperator() { List<QueryParam> attributes = list(isNull(TASK_ATTR_OWNER)); List<UserTaskInstanceWithPotOwnerDesc> data = advanceVariableDataService.queryUserTasksByVariables(attributes, emptyList(), emptyList(), emptyList(), queryContext); if (queryContext.getCount() > 0) { Assert.assertThat(data.size(), is(queryContext.getCount())); } for (UserTaskInstanceWithPotOwnerDesc p : data) { Assert.assertNull(p.getActualOwner()); } }
Source:
public void connect(int clientId, String clientName) throws RemoteException { logger.log(Level.INFO, "Client " + clientName + " connected"); amountOfPingsReceived++; try { ClientInterface ci = (ClientInterface) Naming.lookup(clientName); field.addPlayer(clientId); ci.initializeField(field); AddPlayerAction apa = new AddPlayerAction(clientId, field.getPlayer(clientId).getxPos(), field.getPlayer(clientId).getyPos()); broadcastActionToClients(apa); broadcastActionToServers(apa); connectedPlayers.put(clientId, ci); } catch (Exception e) { e.printStackTrace(); } if (!gameStarted) { logger.log(Level.INFO, "Game started on server " + ID); gameStarted = true; } checkAndUpdateGUI(); }

Target:
public void connect(int clientId, String clientName) throws RemoteException { logger.log(Level.INFO, "Client " + clientName + " connected"); clientAmountOfMessagesReceived++; try { ClientInterface ci = (ClientInterface) Naming.lookup(clientName); field.addPlayer(clientId); ci.initializeField(field); AddPlayerAction apa = new AddPlayerAction(clientId, field.getPlayer(clientId).getxPos(), field.getPlayer(clientId).getyPos()); broadcastActionToClients(apa); broadcastActionToServers(apa); connectedPlayers.put(clientId, ci); } catch (Exception e) { e.printStackTrace(); } if (!gameStarted) { logger.log(Level.INFO, "Game started on server " + ID); gameStarted = true; } checkAndUpdateGUI(); }
Source:
private ProjectTrackerPreferenceSnapshot takeSnapshot() { String branch = getBranch(); if (StringUtils.isEmptyOrNull(branch)) return null; List<String> projectPaths = getAssociatedProjectsPaths(); if (projectPaths == null) return null; return new ProjectTrackerPreferenceSnapshot(repository, branch, projectPaths); }

Target:
private ProjectTrackerPreferenceSnapshot takeSnapshot() { String branch = getBranch(); if (StringUtils.isEmptyOrNull(branch)) return null; List<String> projectPaths = getAssociatedProjectsPaths(); if (projectPaths.isEmpty()) { return null; } return new ProjectTrackerPreferenceSnapshot(repository, branch, projectPaths); }
Source:
public void check(DecoratedKey key) { if (!checkBoolean(key)) throw new RuntimeException("Key " + key + " is not contained in the given ranges"); }

Target:
public boolean check(DecoratedKey key) { assert lastKey == null || key.compareTo(lastKey) > 0; lastKey = key; if (normalizedRanges.isEmpty()) return true; if (rangeIndex > normalizedRanges.size() - 1) throw new IllegalStateException("RangeOwnHelper can only be used to find the first out-of-range-token"); while (!normalizedRanges.get(rangeIndex).contains(key.getToken())) { rangeIndex++; if (rangeIndex > normalizedRanges.size() - 1) return false; } return true; }
Source:
public void testValidate() { final VM vm = new VM(); vm.setStatus(VMStatus.Down); command.setVm(vm); command.setStoragePool(new StoragePool()); doReturn(true).when(command).checkRngDeviceClusterCompatibility(); doReturn(true).when(command).checkPayload(any(VmPayload.class)); doReturn(true).when(command).checkDisksInBackupStorage(); command.setCluster(new Cluster()); ValidateTestUtils.runAndAssertValidateSuccess(command); }

Target:
public void testValidate() { final VM vm = new VM(); vm.setStatus(VMStatus.Down); command.setVm(vm); command.setStoragePool(new StoragePool()); doReturn(true).when(command).checkRngDeviceClusterCompatibility(); doReturn(true).when(command).checkPayload(any(VmPayload.class)); doReturn(false).when(command).checkDisksInBackupStorage(); command.setCluster(new Cluster()); ValidateTestUtils.runAndAssertValidateSuccess(command); }
Source:
private CoordinateReferenceSystem getGeometryCrs(Geometry geometry) { CoordinateReferenceSystem crs = (CoordinateReferenceSystem) geometry.getUserData(); if (crs == null) { crs = DefaultGeographicCRS.WGS84; LOGGER.debug("CRS not found in geometry, defaulting to WGS84"); } return crs; }

Target:
private CoordinateReferenceSystem getGeometryCrs(Geometry geometry) { if (geometry.getUserData() instanceof CoordinateReferenceSystem) { return (CoordinateReferenceSystem) geometry.getUserData(); } LOGGER.trace("CRS not found in geometry, defaulting to WGS84"); return DefaultGeographicCRS.WGS84; }
Source:
public List<RGB> sample(List<Point> samplePoints) { for (Point p : samplePoints) { if (!getBounds().contains(p)) { throw new IllegalArgumentException("Pixel outside of the image"); } } List<RGB> retVal = new ArrayList<>(samplePoints.size()); for (Point p : samplePoints) { retVal.add(getPixel(p.x, p.y)); } return retVal; }

Target:
public List<RGB> sample(List<Point> samplePoints) { for (Point p : samplePoints) { if (!getBounds().contains(p)) { throw new IllegalArgumentException("Point outside of the image"); } } List<RGB> retVal = new ArrayList<>(samplePoints.size()); for (Point p : samplePoints) { retVal.add(getPixel(p.x, p.y)); } return retVal; }
Source:
public int hashCode() { int hash = 5; hash = 79 * hash + (this.pushedBy != null ? this.pushedBy.hashCode() : 0); return hash; }

Target:
public int hashCode() { return Objects.hashCode(this.pushedBy); }
Source:
private void writeCsvRecordForProject(Map<String, CSVWriter> projectToFile, String outputFolderPath, ProjectModel projectModel, String[] line) { if (!projectToFile.containsKey(MERGED_CSV_FILENAME)) { String mergedFilename = PathUtil.cleanFileName(MERGED_CSV_FILENAME) + ".csv"; CSVWriter mergedFileWriter = initCSVWriter(outputFolderPath + mergedFilename, true); projectToFile.put(MERGED_CSV_FILENAME, mergedFileWriter); } if (!projectToFile.containsKey(projectModel.getName())) { String filename = PathUtil.cleanFileName(projectModel.getRootFileModel().getFileName()) + ".csv"; CSVWriter writer = initCSVWriter(outputFolderPath + filename, false); projectToFile.put(projectModel.getName(), writer); LOG.info("Setting csv filename to: " + filename + " for id: " + projectModel.getId()); projectModel.setCsvFilename(filename); } projectToFile.get(projectModel.getName()).writeNext(line); ArrayList<String> mergedList = new ArrayList<String>(Arrays.stream(line).collect(Collectors.toList())); mergedList.add(projectModel.getName()); String[] mergedLine = new String[ mergedList.size() ]; projectToFile.get(MERGED_CSV_FILENAME).writeNext(mergedList.toArray(mergedLine)); }

Target:
private void writeCsvRecordForProject(Map<String, CSVWriter> projectToFile, String outputFolderPath, ProjectModel projectModel, String[] line) { if (!projectToFile.containsKey(MERGED_CSV_FILENAME)) { String mergedFilename = PathUtil.cleanFileName(MERGED_CSV_FILENAME) + ".csv"; CSVWriter mergedFileWriter = initCSVWriter(outputFolderPath + mergedFilename, true); projectToFile.put(MERGED_CSV_FILENAME, mergedFileWriter); } if (!projectToFile.containsKey(projectModel.getName())) { String filename = PathUtil.cleanFileName(projectModel.getRootFileModel().getFileName()) + ".csv"; CSVWriter writer = initCSVWriter(outputFolderPath + filename, false); projectToFile.put(projectModel.getName(), writer); LOG.info("Setting csv filename to: " + filename + " for id: " + projectModel.getId()); projectModel.setCsvFilename(filename); } projectToFile.get(projectModel.getName()).writeNext(line); ArrayList<String> mergedList = new ArrayList<String>(Arrays.stream(line).collect(Collectors.toList())); mergedList.add(projectModel.getRootFileModel().asFile().getName()); String[] mergedLine = new String[ mergedList.size() ]; projectToFile.get(MERGED_CSV_FILENAME).writeNext(mergedList.toArray(mergedLine)); }
Source:
private void decryptFile(String crypterClassName, File tempEncryptedFile, File tempDecryptedFile) { PinotCrypter pinotCrypter = PinotCrypterFactory.create(crypterClassName); LOGGER.info("Using crypter class for decryption.", pinotCrypter.getClass().getName()); pinotCrypter.decrypt(tempEncryptedFile, tempDecryptedFile); }

Target:
private void decryptFile(String crypterClassName, File tempEncryptedFile, File tempDecryptedFile) { PinotCrypter pinotCrypter = PinotCrypterFactory.create(crypterClassName); LOGGER.info("Using crypter class for decrypting to {}", pinotCrypter.getClass().getName(), tempEncryptedFile, tempDecryptedFile); pinotCrypter.decrypt(tempEncryptedFile, tempDecryptedFile); }
Source:
public CommunicationClientCredential(String accessKey) { Objects.requireNonNull(accessKey, "'accessKey' cannot be null"); byte[] key = Base64.getDecoder().decode(accessKey); Mac sha256HMAC = null; try { sha256HMAC = Mac.getInstance("HmacSHA256"); sha256HMAC.init(new SecretKeySpec(key, "HmacSHA256")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } this.sha256HMAC = sha256HMAC; }

Target:
public CommunicationClientCredential(String accessKey) { Objects.requireNonNull(accessKey, "'accessKey' cannot be null"); byte[] key = Base64.getDecoder().decode(accessKey); Mac sha256HMAC = null; try { sha256HMAC = Mac.getInstance("HmacSHA256"); sha256HMAC.init(new SecretKeySpec(key, "HmacSHA256")); } catch (NoSuchAlgorithmException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } catch (InvalidKeyException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } this.sha256HMAC = sha256HMAC; }
Source:
void onSaveWorkspace() { view_.bringToFront(); server_.isFunctionMasked( "save.image", "base", new ErrorLoggingServerRequestCallback<Boolean>() { public void onResponseReceived(Boolean isMasked) { String code = isMasked ? "base::save.image" : "save.image"; consoleDispatcher_.saveFileAsThenExecuteCommand( "Save Workspace As", ".RData", true, code); }; }); }

Target:
void onSaveWorkspace() { view_.bringToFront(); server_.isFunctionMasked( "save.image", "base", new ServerRequestCallback<Boolean>() { public void onResponseReceived(Boolean isMasked) { String code = isMasked ? "base::save.image" : "save.image"; consoleDispatcher_.saveFileAsThenExecuteCommand( "Save Workspace As", ".RData", true, code); } @Override public void onError(ServerError error) { Debug.logError(error); consoleDispatcher_.saveFileAsThenExecuteCommand( "Save Workspace As", ".RData", true, "save.image"); }; }); }
Source:
public ScheduledFuture<?> scheduleWithCronExpression(Runnable command, String cronExpression) { return mock(ScheduledFuture.class); }

Target:
public ScheduledFuture<?> scheduleWithCronExpression(Runnable command, String cronExpression) { ScheduledFuture<?> recurrentTask = decorated.scheduleWithCronExpression(wrap(command), cronExpression); recurrentTasks.add(recurrentTask); return recurrentTask; }
Source:
public void resolve() { if (entry == null) { return; } NetworkBootProtocol bootproto = NetworkBootProtocol.NONE; String ipAddress = fetchIpAddress(); if (bootProtocolDhcp()) { bootproto = NetworkBootProtocol.DHCP; } else if (StringUtils.isNotEmpty(ipAddress)) { bootproto = NetworkBootProtocol.STATIC_IP; } if (bootproto == NetworkBootProtocol.STATIC_IP) { String gateway = fetchGateway(); if (StringUtils.isNotEmpty(gateway)) { VdsBrokerObjectsBuilder.setGatewayIfNecessary(iface, host, gateway.toString()); } } iface.setBootProtocol(bootproto); }

Target:
public void resolve() { if (entry == null) { return; } NetworkBootProtocol bootproto = NetworkBootProtocol.NONE; if (bootProtocolDhcp()) { bootproto = NetworkBootProtocol.DHCP; } else if (StringUtils.isNotEmpty(fetchIpAddress())) { bootproto = NetworkBootProtocol.STATIC_IP; } if (bootproto == NetworkBootProtocol.STATIC_IP) { String gateway = fetchGateway(); if (StringUtils.isNotEmpty(gateway)) { VdsBrokerObjectsBuilder.setGatewayIfNecessary(iface, host, gateway); } } iface.setBootProtocol(bootproto); }
Source:
private void updateLabel(ConnectionState state, ErrorType error) { if (ConnectionStateComposite.this.isDisposed()) return; if (lastConnectionState == ConnectionState.ERROR && state == ConnectionState.NOT_CONNECTED) return; String labelDescription = null; if (accountStore.isEmpty()) { labelDescription = Messages.ConnectionStateComposite_info_add_jabber_account; } else if (state != null) { labelDescription = getDescription(state, error); } else if (lastConnectionState != null) { labelDescription = getDescription(lastConnectionState, lastError); } if (labelDescription == null) return; stateLabel.setText(labelDescription); stateLabel.setToolTipText( state == ConnectionState.CONNECTED ? String.format(CONNECTED_TOOLTIP, version) : null); layout(); if (state != null) { lastConnectionState = state; lastError = error; } }

Target:
private void updateLabel(ConnectionState state, ErrorType error) { if (isDisposed()) return; if (lastConnectionState == ConnectionState.ERROR && state == ConnectionState.NOT_CONNECTED) return; String labelDescription = null; if (accountStore.isEmpty()) { labelDescription = Messages.ConnectionStateComposite_info_add_jabber_account; } else if (state != null) { labelDescription = getDescription(state, error); } else if (lastConnectionState != null) { labelDescription = getDescription(lastConnectionState, lastError); } if (labelDescription == null) return; stateLabel.setText(labelDescription); stateLabel.setToolTipText( state == ConnectionState.CONNECTED ? String.format(CONNECTED_TOOLTIP, version) : null); layout(); if (state != null) { lastConnectionState = state; lastError = error; } }
Source:
void applyTo(final HtsgetBAMFileReader underlyingReader, final SamReader reader) { logDebugIgnoringOption(reader, this); }

Target:
void applyTo(final HtsgetBAMFileReader underlyingReader, final SamReader reader) { underlyingReader.enableFileSource(reader, true); }
Source:
public static JPAAttachment from(Attachment attachment) { return new JPAAttachment(attachment.getAttachmentId().getId(), attachment.getBytes(), attachment.getType(), new ArrayList<>(), new ArrayList<>(), "", false); }

Target:
public static JPAAttachment from(Attachment attachment) { return new JPAAttachment(attachment.getAttachmentId().getId(), attachment.getBytes(), attachment.getType(), ImmutableList.<String>builder().build(), ImmutableList.<String>builder().build(), "", false); }
Source:
public static BasicAuthenticatorMetadataStorageUpdater createAuthenticatorStorageUpdater(final Injector injector) { if (isCoordinator(injector)) { return injector.getInstance(CoordinatorBasicAuthenticatorMetadataStorageUpdater.class); } else { return injector.getInstance(NoopBasicAuthenticatorMetadataStorageUpdater.class); } }

Target:
public static BasicAuthenticatorMetadataStorageUpdater createAuthenticatorStorageUpdater(final Injector injector) { if (isCoordinator(injector)) { return injector.getInstance(CoordinatorBasicAuthenticatorMetadataStorageUpdater.class); } else { return null; } }
Source:
public void peerStateChanged(final CallPeerChangeEvent evt) { CallPeerState callPeerState = (CallPeerState)evt.getNewValue(); String stateString = callPeerState.getStateString(); logger.info( (callContext == null ? "no-call-ctx" : callContext.getCallResource()) + " SIP peer state: " + stateString); if (jvbConference != null) jvbConference.setPresenceStatus(stateString); if (CallPeerState.BUSY.equals(callPeerState)) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } CallManager.hangupCall( evt.getSourceCallPeer().getCall()); } }).start(); } if (CallPeerState.CONNECTED.equals(callPeerState)) { if (currentRecordingStatus.equals(JibriIq.Status.ON)) { Util.injectSoundFile(call, "sounds/RecordingOn.opus"); } } }

Target:
public void peerStateChanged(final CallPeerChangeEvent evt) { CallPeerState callPeerState = (CallPeerState)evt.getNewValue(); String stateString = callPeerState.getStateString(); logger.info( (callContext == null ? "no-call-ctx" : callContext.getCallResource()) + " SIP peer state: " + stateString); if (jvbConference != null) jvbConference.setPresenceStatus(stateString); if (CallPeerState.BUSY.equals(callPeerState)) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } CallManager.hangupCall( evt.getSourceCallPeer().getCall()); } }).start(); } if (CallPeerState.CONNECTED.equals(callPeerState)) { if (currentRecordingStatus.equals(JibriIq.Status.ON)) { Util.injectSoundFile(call, REC_ON_SOUND); } } }
Source:
private boolean isRegisterHealthIndicator(RateLimiter rateLimiter) { return rateLimiterProperties.findRateLimiterProperties(rateLimiter.getName()) .map(InstanceProperties::getRegisterHealthIndicator) .orElse(true); }

Target:
private boolean isRegisterHealthIndicator(RateLimiter rateLimiter) { return rateLimiterProperties.findRateLimiterProperties(rateLimiter.getName()) .map(InstanceProperties::getRegisterHealthIndicator) .orElse(false); }
Source:
private IType[] getTypes() throws JavaModelException { IEditorInput input= fEditor.getEditorInput(); if (input instanceof IClassFileEditorInput) { ITypeRoot classFile= ((IClassFileEditorInput)input).getClassFile(); if (classFile instanceof IOrdinaryClassFile) return new IType[] { ((IOrdinaryClassFile) classFile).getType() }; return new IType[0]; } else { return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(input).getAllTypes(); } }

Target:
private IType[] getTypes() throws JavaModelException { IEditorInput input= fEditor.getEditorInput(); if (input instanceof IClassFileEditorInput) { IClassFile classFile= ((IClassFileEditorInput)input).getClassFile(); if (classFile instanceof IOrdinaryClassFile) return new IType[] { ((IOrdinaryClassFile) classFile).getType() }; return new IType[0]; } else { return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(input).getAllTypes(); } }
Source:
private void onDistanceEvent(DistanceEvent event) { assert adminExecutor.inEventLoop(); this.lastDistanceEvents.put(event.node, event); if (event.distance == NodeDistance.IGNORED && channel != null && !channel.closeFuture().isDone() && event.node.getConnectAddress().equals(channel.remoteAddress())) { LOG.debug("[{}] Control node became IGNORED, reconnecting", logPrefix, event.node); reconnectNow(); } }

Target:
private void onDistanceEvent(DistanceEvent event) { assert adminExecutor.inEventLoop(); this.lastDistanceEvents.put(event.node, event); if (event.distance == NodeDistance.IGNORED && channel != null && !channel.closeFuture().isDone() && event.node.getConnectAddress().equals(channel.remoteAddress())) { LOG.debug( "[{}] Control node became IGNORED, reconnecting to a different node", logPrefix, event.node); reconnectNow(); } }
Source:
public static void main(String[] args) throws InterruptedException { Microservices seed = Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(ServiceTransports::rsocketServiceTransport) .startAwait(); Microservices.builder() .discovery( serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint) .options(opts -> opts.seedMembers(toAddress(seed.discovery().address())))) .transport(ServiceTransports::rsocketServiceTransport) .services(new GreetingServiceImpl()) .startAwait(); GreetingsService service = seed.call().api(GreetingsService.class); service .sayHello("joe") .subscribe( consumer -> { System.out.println(consumer.message()); }); Thread.currentThread().join(); }

Target:
public static void main(String[] args) { Microservices seed = Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(ServiceTransports::rsocketServiceTransport) .startAwait(); Microservices ms = Microservices.builder() .discovery( serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint) .options(opts -> opts.seedMembers(toAddress(seed.discovery().address())))) .transport(ServiceTransports::rsocketServiceTransport) .services(new GreetingServiceImpl()) .startAwait(); GreetingsService service = seed.call().api(GreetingsService.class); service .sayHello("joe") .subscribe( consumer -> { System.out.println(consumer.message()); }); seed.onShutdown().block(); ms.onShutdown().block(); }
Source:
private void saveContributors(HashMap<?, ?> contributors) throws IOException { FileOutputStream fosContributors = new FileOutputStream(contributorsFile); DataOutputStream outputContributors = new DataOutputStream(new BufferedOutputStream(fosContributors)); Collection<?> entries = contributors.values(); outputContributors.writeInt(entries.size()); for (Object name : entries) { RegistryContributor contributor = (RegistryContributor) name; writeStringOrNull(contributor.getActualId(), outputContributors); writeStringOrNull(contributor.getActualName(), outputContributors); writeStringOrNull(contributor.getId(), outputContributors); writeStringOrNull(contributor.getName(), outputContributors); } outputContributors.flush(); fosContributors.getFD().sync(); outputContributors.close(); }

Target:
private void saveContributors(HashMap<?, ?> contributors) throws IOException { FileOutputStream fosContributors = new FileOutputStream(contributorsFile); DataOutputStream outputContributors = new DataOutputStream(new BufferedOutputStream(fosContributors)); Collection<?> entries = contributors.values(); outputContributors.writeInt(entries.size()); for (Object entry : entries) { RegistryContributor contributor = (RegistryContributor) entry; writeStringOrNull(contributor.getActualId(), outputContributors); writeStringOrNull(contributor.getActualName(), outputContributors); writeStringOrNull(contributor.getId(), outputContributors); writeStringOrNull(contributor.getName(), outputContributors); } outputContributors.flush(); fosContributors.getFD().sync(); outputContributors.close(); }
Source:
public TerminalSession createTerminalSession(TtyConnector ttyConnector) { setTtyConnector(ttyConnector); new TtyConnectorWaitFor(ttyConnector, Executors.newSingleThreadExecutor()).setTerminationCallback(x -> { for (TerminalWidgetListener listener : myListeners) { listener.allSessionsClosed(this); } return true; }); return this; }

Target:
public TerminalSession createTerminalSession(TtyConnector ttyConnector) { setTtyConnector(ttyConnector); return this; }
Source:
public void testAddAlreadyExistingKey() throws Exception { new Context() {{ runTest( () -> { leaderCallbackGrantLeadership(); final KubernetesStateHandleStore<Long> store = new KubernetesStateHandleStore<>( flinkKubeClient, LEADER_CONFIGMAP_NAME, longStateStorage, filter, LOCK_IDENTITY); store.add(key, state); try { store.add(key, state); fail("Exception should be thrown."); } catch (StateHandleStore.AlreadyExistException ex) { final String msg = String.format( "%s already exists in ConfigMap %s", key, LEADER_CONFIGMAP_NAME); assertThat(ex.getMessage(), containsString(msg)); } assertThat(longStateStorage.getStateHandles().size(), is(2)); assertThat(longStateStorage.getStateHandles().get(1).getNumberOfDiscardCalls(), is(1)); }); }}; }

Target:
public void testAddAlreadyExistingKey() throws Exception { new Context() {{ runTest( () -> { leaderCallbackGrantLeadership(); getLeaderConfigMap().getData().put(key, "existing data"); final KubernetesStateHandleStore<Long> store = new KubernetesStateHandleStore<>( flinkKubeClient, LEADER_CONFIGMAP_NAME, longStateStorage, filter, LOCK_IDENTITY); try { store.addAndLock(key, state); fail("Exception should be thrown."); } catch (StateHandleStore.AlreadyExistException ex) { final String msg = String.format( "%s already exists in ConfigMap %s", key, LEADER_CONFIGMAP_NAME); assertThat(ex, FlinkMatchers.containsMessage(msg)); } assertThat(longStateStorage.getStateHandles().size(), is(1)); assertThat(longStateStorage.getStateHandles().get(0).getNumberOfDiscardCalls(), is(1)); }); }}; }
Source:
public void processPlotLevelData(final AdvancingSource source, final MeasurementRow row) { if (source.getStudyType().equals(StudyType.T) && StringUtils.isBlank(source.getSeason()) && source.getTrailInstanceObservation() != null && source.getTrailInstanceObservation().getDataList() != null) { final Map<Integer, String> measurementVariablesValues = new HashMap<Integer, String>(); for (final MeasurementData measurementData : source.getTrailInstanceObservation().getDataList()) { if (StringUtils.isNotBlank(measurementData.getValue())) { final int termId = measurementData.getMeasurementVariable().getTermId(); final List<ValueReference> possibleValues = measurementData.getMeasurementVariable().getPossibleValues(); if(termId == TermId.SEASON_VAR.getId() && StringUtils.isNumeric(measurementData.getValue()) && !possibleValues.isEmpty()){ String seasonVarValue = this.getSeasonVarValue(measurementData.getValue(), possibleValues); measurementVariablesValues.put(termId, seasonVarValue); } else { measurementVariablesValues.put(termId, measurementData.getValue()); } } } source.setSeason(this.getValueOfPrioritySeasonVariable(measurementVariablesValues)); } }

Target:
public void processPlotLevelData(final AdvancingSource source, final MeasurementRow row) { if (source.getStudyType().equals(StudyType.T) && StringUtils.isBlank(source.getSeason()) && source.getTrailInstanceObservation() != null && source.getTrailInstanceObservation().getDataList() != null) { final Map<Integer, String> measurementVariablesValues = new HashMap<Integer, String>(); for (final MeasurementData measurementData : source.getTrailInstanceObservation().getDataList()) { final int termId = measurementData.getMeasurementVariable().getTermId(); final List<ValueReference> possibleValues = measurementData.getMeasurementVariable().getPossibleValues(); this.addValueToMeasurementVariablesValues(measurementData.getValue(), possibleValues, termId, measurementVariablesValues); } source.setSeason(this.getValueOfPrioritySeasonVariable(measurementVariablesValues)); } }
Source:
private static boolean isBinaryFile(String fullPath) { byte[] firstBytes = new byte[8]; try (FileInputStream input = new FileInputStream(fullPath)) { input.read(firstBytes); } catch (IOException e) { Activator.getDefault().logError("Cannot read the file "+fullPath+" ", e); } for (byte[] header : BINARY_HEADERS) { if (firstBytes.length >= header.length && startsWith(header, firstBytes)) { return true; } } return false; }

Target:
private static boolean isBinaryFile(String fullPath) { byte[] firstBytes = new byte[8]; try (FileInputStream input = new FileInputStream(fullPath)) { input.read(firstBytes); } catch (IOException e) { Activator.getDefault().logError("Cannot read the file"+fullPath, e); } for (byte[] header : BINARY_HEADERS) { if (firstBytes.length >= header.length && startsWith(header, firstBytes)) { return true; } } return false; }
Source:
long getDifference(Offset o1, Offset o2) { if (!segmentsByName.containsKey(o1.getName()) || !segmentsByName.containsKey(o2.getName())) { throw new IllegalArgumentException("One of the log segments provided [" + o1.getName() + ", " + o2.getName() + "] does not belong to this log"); } LogSegment firstSegment = segmentsByName.get(o1.getName()); LogSegment secondSegment = segmentsByName.get(o2.getName()); if (o1.getOffset() > firstSegment.getEndOffset() || o2.getOffset() > secondSegment.getEndOffset()) { throw new IllegalArgumentException("One of the offsets provided [" + o1.getOffset() + ", " + o2.getOffset() + "] is out of range of the segment it refers to [" + firstSegment.getEndOffset() + ", " + secondSegment.getEndOffset() + "]"); } if (o1.getName().equals(o2.getName())) { return o1.getOffset() - o2.getOffset(); } Offset higher = o1.compareTo(o2) > 0 ? o1 : o2; Offset lower = higher == o1 ? o2 : o1; LogSegment segment = segmentsByName.higherEntry(lower.getName()).getValue(); long difference = segment.getCapacityInBytes() - lower.getOffset(); while (!segment.getName().equals(higher.getName())) { difference += segment.getCapacityInBytes(); segment = segmentsByName.higherEntry(segment.getName()).getValue(); } difference += higher.getOffset(); return o1.compareTo(o2) * difference; }

Target:
long getDifference(Offset o1, Offset o2) { LogSegment firstSegment = segmentsByName.get(o1.getName()); LogSegment secondSegment = segmentsByName.get(o2.getName()); if (firstSegment == null || secondSegment == null) { throw new IllegalArgumentException( "One of the log segments provided [" + o1.getName() + ", " + o2.getName() + "] does not belong to this log"); } if (o1.getOffset() > firstSegment.getCapacityInBytes() || o2.getOffset() > secondSegment.getCapacityInBytes()) { throw new IllegalArgumentException("One of the offsets provided [" + o1.getOffset() + ", " + o2.getOffset() + "] is out of range of the segment it refers to [" + firstSegment.getCapacityInBytes() + ", " + secondSegment .getCapacityInBytes() + "]"); } if (o1.getName().equals(o2.getName())) { return o1.getOffset() - o2.getOffset(); } Offset higher = o1.compareTo(o2) > 0 ? o1 : o2; Offset lower = higher == o1 ? o2 : o1; int interveningSegmentsCount = segmentsByName.subMap(lower.getName(), false, higher.getName(), false).size(); long segmentCapacity = firstSegment.getCapacityInBytes(); long difference = segmentCapacity - lower.getOffset() + segmentCapacity * interveningSegmentsCount + higher.getOffset(); return o1.compareTo(o2) * difference; }