auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean include(TreeWalk walker) throws MissingObjectException, IncorrectObjectTypeException, IOException { pointer = null; if (walker.isSubtree()) { return walker.isRecursive(); } ObjectId objectId = walker.getObjectId(0); ObjectLoader object = walker.getObjectReader().open(objectId); if (object.isLarge()) { return false; } ObjectStream stream = object.openStream(); byte[] buffer = new byte[VERSION_LINE.length]; int read = stream.read(buffer); if (read == VERSION_LINE.length && RawParseUtils.match(buffer, 0, VERSION_LINE) < 0) { return false; } int line = 2; int foundKeys = 0; byte[][] values = new byte[REQUIRED_KEYS.length][]; buffer = object.getCachedBytes(); IntList lineMap = RawParseUtils.lineMap(buffer, 0, buffer.length); int lineMapSize = lineMap.size() - 1; for (int r = 0; r < REQUIRED_KEYS.length; r++) { byte[] key = REQUIRED_KEYS[r]; for (; line < lineMapSize; line++) { int lineStart = lineMap.get(line); int match = RawParseUtils.match(buffer, lineStart, key); if (match > 0) { foundKeys++; int len = lineMap.get(line + 1) - match - 1; values[r] = new byte[len]; System.arraycopy(buffer, match, values[r], 0, len); break; } } } if (foundKeys == REQUIRED_KEYS.length) { LongObjectId oid = LongObjectId.fromString(values[OID_INDEX], 0); int size = RawParseUtils.parseBase10(values[SIZE_INDEX], 0, new MutableInteger()); pointer = new LargeObjectPointer(oid, size); return true; } return false; }

Target:
public boolean include(TreeWalk walker) throws MissingObjectException, IncorrectObjectTypeException, IOException { pointer = null; if (walker.isSubtree()) { return walker.isRecursive(); } ObjectId objectId = walker.getObjectId(0); ObjectLoader object = walker.getObjectReader().open(objectId); if (object.isLarge()) { return false; } ObjectStream stream = object.openStream(); byte[] buffer = new byte[VERSION_LINE_LEGACY.length]; int read = stream.read(buffer); if (!validVersionLine(read, buffer)) { return false; } int line = 2; int foundKeys = 0; byte[][] values = new byte[REQUIRED_KEYS.length][]; buffer = object.getCachedBytes(); IntList lineMap = RawParseUtils.lineMap(buffer, 0, buffer.length); int lineMapSize = lineMap.size() - 1; for (int r = 0; r < REQUIRED_KEYS.length; r++) { byte[] key = REQUIRED_KEYS[r]; for (; line < lineMapSize; line++) { int lineStart = lineMap.get(line); int match = RawParseUtils.match(buffer, lineStart, key); if (match > 0) { foundKeys++; int len = lineMap.get(line + 1) - match - 1; values[r] = new byte[len]; System.arraycopy(buffer, match, values[r], 0, len); break; } } } if (foundKeys == REQUIRED_KEYS.length) { LongObjectId oid = LongObjectId.fromString(values[OID_INDEX], 0); int size = RawParseUtils.parseBase10(values[SIZE_INDEX], 0, new MutableInteger()); pointer = new LargeObjectPointer(oid, size); return true; } return false; }
Source:
private void informAppAboutAssignment(TaskRequest request, Container container) { Object task = request.getTask(); if (blacklistedNodes.contains(container.getNodeId()) || task instanceof TaskAttempt && ((TaskAttempt) task).getUnhealthyNodesHistory().contains(container.getNodeId())) { LOG.info("Container allocated for task on blacklisted node {}", container.getId(), container.getNodeId(), task); deallocateContainer(container.getId()); allocateTask(task, request.getCapability(), (request.getNodes() == null ? null : request.getNodes().toArray(new String[request.getNodes().size()])), (request.getRacks() == null ? null : request.getRacks().toArray(new String[request.getRacks().size()])), request.getPriority(), request.getContainerSignature(), request.getCookie()); } else { getContext().taskAllocated(request.getTask(), request.getCookie(), container); } }

Target:
private void informAppAboutAssignment(TaskRequest request, Container container) { if (blacklistedNodes.contains(container.getNodeId())) { Object task = request.getTask(); LOG.info("Container allocated for task on blacklisted node {}", container.getId(), container.getNodeId(), task); deallocateContainer(container.getId()); allocateTask(task, request.getCapability(), (request.getNodes() == null ? null : request.getNodes().toArray(new String[request.getNodes().size()])), (request.getRacks() == null ? null : request.getRacks().toArray(new String[request.getRacks().size()])), request.getPriority(), request.getContainerSignature(), request.getCookie()); } else { getContext().taskAllocated(request.getTask(), request.getCookie(), container); } }
Source:
public static String getPartAtPosition(Iterable<String> parts, int pos) { String part = Iterables.get(parts, pos); if (StringUtils.isNotEmpty(part)) { return part; } return null; }

Target:
public static String getPartAtPosition(Iterable<String> parts, int pos) { String part = Iterables.get(parts, pos); return Strings.emptyToNull(part); }
Source:
public void run() { try { doProcess(); } finally { super.run(); } }

Target:
public void run() { try { doRun(); } finally { super.run(); } }
Source:
private void validate() { assertThat(localCommandBus, Objects::nonNull, () -> new AxonConfigurationException( "The localCommandBus is a hard requirement and should be provided")); assertThat(restOperations, Objects::nonNull, () -> new AxonConfigurationException( "The RestOperations is a hard requirement and should be provided")); assertThat(serializer, Objects::nonNull, () -> new AxonConfigurationException( "The Serializer is a hard requirement and should be provided")); }

Target:
protected void validate() { assertNonNull(localCommandBus, "The local CommandBus is a hard requirement and should be provided"); assertNonNull(restOperations, "The RestOperations is a hard requirement and should be provided"); assertNonNull(serializer, "The Serializer is a hard requirement and should be provided"); }
Source:
private static Map<JdbcQuery, List<Map<String, Object>>> getSqlQueryResults( Set<JdbcQuery> jdbcQueries, BatchLoaderEnvironment context ) { Map<JdbcQuery, List<Map<String, Object>>> allResults = new HashMap<>(); Map<Object, Object> keyContexts = context.getKeyContexts(); for (JdbcQuery jdbcQuery : jdbcQueries) { Connection connection = null; try { DataSource dataSource = ((DataSource) keyContexts.get(jdbcQuery)); connection = dataSource.getConnection(); allResults.put( jdbcQuery, getSqlQueryResult( jdbcQuery, connection ) ); } catch (SQLException e) { throw new RuntimeException(e); } finally { DbUtils.closeQuietly(connection); } } return allResults; }

Target:
private static Map<JdbcQuery, List<Map<String, Object>>> getSqlQueryResults( Set<JdbcQuery> jdbcQueries, BatchLoaderEnvironment context ) { Map<JdbcQuery, List<Map<String, Object>>> allResults = new HashMap<>(); Map<Object, Object> keyContexts = context.getKeyContexts(); List<CombinedQuery> combinedQueries = new ArrayList<>(); for (JdbcQuery jdbcQuery : jdbcQueries) { DataSource dataSource = ((DataSource) keyContexts.get(jdbcQuery)); if (combinedQueries.isEmpty()) { combinedQueries.add(new CombinedQuery(jdbcQuery, dataSource)); continue; } boolean foundOtherQueryToCombineWith = false; for (CombinedQuery combinedQuery : combinedQueries) { if (combinedQuery.combineWith(jdbcQuery)) { foundOtherQueryToCombineWith = true; break; } } if (!foundOtherQueryToCombineWith) { combinedQueries.add(new CombinedQuery(jdbcQuery, dataSource)); } } for (CombinedQuery combinedQuery : combinedQueries) { combinedQuery.executeAndAddToResults(allResults); } return allResults; }
Source:
public boolean match(final ChangeData object) throws OrmException { final Change c = object.change(dbProvider); final ProjectState project = projectCache.get(c.getDest().getParentKey()); if (project == null) { return false; } final LabelType labelType = type(project.getLabelTypes(), type); final Set<Account.Id> allApprovers = new HashSet<Account.Id>(); final Set<Account.Id> approversThatVotedInCategory = new HashSet<Account.Id>(); for (PatchSetApproval p : object.currentApprovals(dbProvider)) { allApprovers.add(p.getAccountId()); if (p.getCategoryId().get().equals(labelType.getId())) { approversThatVotedInCategory.add(p.getAccountId()); if (match(c, p.getValue(), p.getAccountId(), labelType)) { return true; } } } final Set<Account.Id> approversThatDidNotVoteInCategory = new HashSet<Account.Id>(allApprovers); approversThatDidNotVoteInCategory.removeAll(approversThatVotedInCategory); for (Account.Id a : approversThatDidNotVoteInCategory) { if (match(c, 0, a, labelType)) { return true; } } return false; }

Target:
public boolean match(final ChangeData object) throws OrmException { final Change c = object.change(dbProvider); if (c == null) { return false; } final ProjectState project = projectCache.get(c.getDest().getParentKey()); if (project == null) { return false; } final LabelType labelType = type(project.getLabelTypes(), type); final Set<Account.Id> allApprovers = new HashSet<Account.Id>(); final Set<Account.Id> approversThatVotedInCategory = new HashSet<Account.Id>(); for (PatchSetApproval p : object.currentApprovals(dbProvider)) { allApprovers.add(p.getAccountId()); if (p.getCategoryId().get().equals(labelType.getId())) { approversThatVotedInCategory.add(p.getAccountId()); if (match(c, p.getValue(), p.getAccountId(), labelType)) { return true; } } } final Set<Account.Id> approversThatDidNotVoteInCategory = new HashSet<Account.Id>(allApprovers); approversThatDidNotVoteInCategory.removeAll(approversThatVotedInCategory); for (Account.Id a : approversThatDidNotVoteInCategory) { if (match(c, 0, a, labelType)) { return true; } } return false; }
Source:
private String getOvnCentral() { Guid providerId = getParameters().getNetworkProviderId(); if (providerId != null) { Provider provider = providerDao.get(providerId); if (provider.getType() == ProviderType.EXTERNAL_NETWORK) { return NetworkUtils.getIpAddress(provider.getUrl()); } } return null; }

Target:
private String getOvnCentral() { Guid providerId = getParameters().getNetworkProviderId(); if (providerId != null) { Provider provider = providerDao.get(providerId); if (provider.getType() == ProviderType.EXTERNAL_NETWORK) { String ovnCentral = NetworkUtils.getIpAddress(provider.getUrl()); if (ovnCentral == null) { throw new VdsInstallException( VDSStatus.InstallFailed, String.format( "Failed to extract OVN central IP from %1$s", provider.getUrl() ) ); } return ovnCentral; } } return null; }
Source:
public ITestNGMethod getMethodDependingOn(String methodName, ITestNGMethod fromMethod) { List<ITestNGMethod> l = m_dependencies.get(methodName); if (l.isEmpty()) { l = m_dependencies.get(constructMethodNameUsingTestClass(methodName, fromMethod)); } if (l.isEmpty() && fromMethod.ignoreMissingDependencies()){ return fromMethod; } for (ITestNGMethod m : l) { Object fromMethodInstance = fromMethod.getInstance(); Object mInstance = m.getInstance(); if (mInstance != null && fromMethodInstance != null && fromMethodInstance.getClass().isAssignableFrom(mInstance.getClass())) { return m; } else { return m; } } throw new TestNGException("Method \"" + fromMethod + "\" depends on nonexistent method \"" + methodName + "\""); }

Target:
public ITestNGMethod getMethodDependingOn(String methodName, ITestNGMethod fromMethod) { List<ITestNGMethod> l = m_dependencies.get(methodName); if (l.isEmpty()) { l = m_dependencies.get(constructMethodNameUsingTestClass(methodName, fromMethod)); } if (l.isEmpty() && fromMethod.ignoreMissingDependencies()){ return fromMethod; } for (ITestNGMethod m : l) { if (isSameInstance(fromMethod, m) || belongToDifferentClassHierarchy(fromMethod, m) || hasInstance(fromMethod, m)) { return m; } } throw new TestNGException("Method \"" + fromMethod + "\" depends on nonexistent method \"" + methodName + "\""); }
Source:
private DatabaseRow getNextRow() throws SQLException { _numRowsInResult++; try { ResultSetMetaData rsmd = _queryResultSet.getMetaData(); int colCount = rsmd.getColumnCount(); DatabaseRow payloadRecord = new DatabaseRow(); for (int i = 1; i <= colCount; i++) { String colName = rsmd.getColumnName(i); Object column = _queryResultSet.getObject(i); payloadRecord.addField(colName, column, rsmd.getColumnType(i)); if (_chunkingKeys.containsKey(colName)) { if (column == null) { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, colName + " field is not expected to be null"); } _chunkingKeys.put(colName, column); } } return payloadRecord; } catch (SQLException e) { _metrics.updateErrorRate(); if (_skipBadMessagesEnabled) { LOG.warn("Skipping row due to SQL exception", e); _metrics.updateSkipBadMessagesRate(); } else { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, "Failed to interpret row and skipBadMessage not enabled", e); } return null; } }

Target:
private DatabaseRow getNextRow() throws SQLException { _numRowsInResult++; try { ResultSetMetaData rsmd = _queryResultSet.getMetaData(); int colCount = rsmd.getColumnCount(); DatabaseRow payloadRecord = new DatabaseRow(); for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object columnValue = _queryResultSet.getObject(i); payloadRecord.addField(columnName, columnValue, rsmd.getColumnType(i)); if (_chunkingKeys.containsKey(columnName)) { if (columnValue == null) { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, columnName + " field is not expected to be null"); } _chunkingKeys.put(columnName, columnValue); } } return payloadRecord; } catch (SQLException e) { _metrics.updateErrorRate(); if (_skipBadMessagesEnabled) { LOG.warn("Skipping row due to SQL exception", e); _metrics.updateSkipBadMessagesRate(); } else { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, "Failed to interpret row and skipBadMessage not enabled", e); } return null; } }
Source:
protected synchronized void onFirstPeerRegistered() { mDocument.createDomProviderIfNoneExists(); }

Target:
protected synchronized void onFirstPeerRegistered() { mDocument.addRef(); mDocument.addUpdateListener(mListener); }
Source:
protected void addVmToDb() { super.addVmToDb(); if (getVm().getOrigin() == OriginType.KVM) { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), getStoragePool().getCompatibilityVersion()); VmDeviceDao dao = DbFacade.getInstance().getVmDeviceDao(); dao.saveAll(getVm().getStaticData().getManagedDeviceMap().values()); } }

Target:
protected void addVmToDb() { super.addVmToDb(); if (getVm().getOrigin() == OriginType.KVM) { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), getStoragePool().getCompatibilityVersion()); getVmDeviceDao().saveAll(getVm().getStaticData().getManagedDeviceMap().values()); } }
Source:
protected boolean validate() { if (!super.validate()) { return false; } StorageDomain dom = getStorageDomain(); if (dom == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } VDS vds = getVds(); StorageDomainToPoolRelationValidator domainPoolValidator = createDomainToPoolValidator(dom); if (VDSStatus.Maintenance == vds.getStatus()) { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_HOST_IN_MAINTENANCE, String.format("$%1$s %2$s", "hostName", vds.getName())); } if (!checkStorageDomain()) { return false; } boolean localFs = isLocalFs(dom); if (!localFs && !validate(domainPoolValidator.isStorageDomainNotInAnyPool())) { return false; } if (localFs && isDomainAttached(dom) && !canDetachDomain(getParameters().getDestroyingPool(), false)) { return false; } if (getParameters().getDoFormat() && !localFs && isStorageDomainAttached(dom)) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FORMAT_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } if (vds == null) { if (localFs) { if (!initializeVds()) { return false; } } else { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_INVALID_HOST_ID); } } if (dom.getStorageType().isOpenStackDomain()) { return failValidation(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); } return true; }

Target:
protected boolean validate() { if (!super.validate()) { return false; } StorageDomain dom = getStorageDomain(); if (dom == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } VDS vds = getVds(); StorageDomainToPoolRelationValidator domainPoolValidator = createDomainToPoolValidator(dom); if (vds.getStatus() != VDSStatus.Up) { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_HOST_NOT_UP, String.format("$%1$s %2$s", "hostName", vds.getName())); } if (!checkStorageDomain()) { return false; } boolean localFs = isLocalFs(dom); if (!localFs && !validate(domainPoolValidator.isStorageDomainNotInAnyPool())) { return false; } if (localFs && isDomainAttached(dom) && !canDetachDomain(getParameters().getDestroyingPool(), false)) { return false; } if (getParameters().getDoFormat() && !localFs && isStorageDomainAttached(dom)) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FORMAT_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } if (vds == null) { if (localFs) { if (!initializeVds()) { return false; } } else { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_INVALID_HOST_ID); } } if (dom.getStorageType().isOpenStackDomain()) { return failValidation(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); } return true; }
Source:
public boolean isValidUser(String pluginId, String username, SecurityAuthConfig authConfig) { String cacheKey = cacheKeyFor(IS_VALID_USER_CACHE_KEY, pluginId, username, authConfig); Boolean fromCache = isValidUserCache.getIfPresent(cacheKey); if (fromCache == null) { fromCache = authorizationExtension.isValidUser(pluginId, username, authConfig); isValidUserCache.put(cacheKey, fromCache); } return fromCache; }

Target:
public boolean isValidUser(String pluginId, String username, SecurityAuthConfig authConfig) { String cacheKey = cacheKeyFor(pluginId, username, authConfig); Boolean fromCache = isValidUserCache.getIfPresent(cacheKey); if (fromCache == null) { fromCache = authorizationExtension.isValidUser(pluginId, username, authConfig); isValidUserCache.put(cacheKey, fromCache); } return fromCache; }
Source:
private Eh107CacheManager createCacheManager(URI uri, ClassLoader classLoader, CacheManagerBuilder<org.ehcache.CacheManager> builder) { Eh107CacheLoaderWriterProvider cacheLoaderWriterFactory = new Eh107CacheLoaderWriterProvider(); Object[] serviceCreationConfigurations = builder.getServices().toArray(); Jsr107Service jsr107Service = new DefaultJsr107Service(ServiceUtils.findSingletonAmongst(Jsr107Configuration.class, serviceCreationConfigurations)); Collection<Service> services = new ArrayList<>(4); services.add(cacheLoaderWriterFactory); services.add(jsr107Service); if (ServiceUtils.findSingletonAmongst(DefaultSerializationProviderConfiguration.class, serviceCreationConfigurations) == null) { services.add(new DefaultJsr107SerializationProvider()); } InternalCacheManager ehcacheManager = (InternalCacheManager) builder.build(true); return new Eh107CacheManager(this, ehcacheManager, new Properties(), classLoader, uri, new ConfigurationMerger(null, jsr107Service, cacheLoaderWriterFactory)); }

Target:
private Eh107CacheManager createCacheManager(URI uri, ClassLoader classLoader, CacheManagerBuilder<org.ehcache.CacheManager> builder) { Collection<Service> services = builder.getServices(); Collection<ServiceCreationConfiguration<?>> serviceCreationConfigurations = builder.getServiceConfigurations(); Jsr107Configuration jsr107Configuration = ServiceUtils.findSingletonAmongst(Jsr107Configuration.class, serviceCreationConfigurations); Jsr107Service jsr107Service = findOrCreateService(services, Jsr107Service.class, () -> new DefaultJsr107Service(jsr107Configuration)); builder = builder.using(jsr107Service); Eh107CacheLoaderWriterProvider cacheLoaderWriterFactory = findOrCreateService(services, Eh107CacheLoaderWriterProvider.class, Eh107CacheLoaderWriterProvider::new); builder = builder.using(cacheLoaderWriterFactory); SerializationProvider serializationProvider = findOrCreateService(services, SerializationProvider.class, () -> new DefaultSerializationProvider(null)); builder = builder.using(serializationProvider); org.ehcache.CacheManager cacheManager = builder.build(true); return new Eh107CacheManager(this, cacheManager, jsr107Service, new Properties(), classLoader, uri, new ConfigurationMerger(null, jsr107Service, cacheLoaderWriterFactory)); }
Source:
public void testGetCachedDatanodeReport() throws Exception { final DatanodeInfo[] datanodeReport = routerProtocol.getDatanodeReport(DatanodeReportType.ALL); assertEquals(12, datanodeReport.length); DatanodeInfo[] datanodeReport1 = routerProtocol.getDatanodeReport(DatanodeReportType.ALL); assertArrayEquals(datanodeReport1, datanodeReport); getCluster().getCluster().startDataNodes(getCluster().getCluster().getConfiguration(0), 1, true, null, null, null); GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { DatanodeInfo[] dn = null; try { dn = routerProtocol.getDatanodeReport(DatanodeReportType.ALL); } catch (IOException ex) { LOG.error("Error on getDatanodeReport"); } return !Arrays.equals(datanodeReport, dn); } }, 500, 5 * 1000); final DatanodeInfo[] datanodeReport2 = routerProtocol.getDatanodeReport(DatanodeReportType.ALL); assertFalse(Arrays.equals(datanodeReport, datanodeReport2)); }

Target:
public void testGetCachedDatanodeReport() throws Exception { RouterRpcServer rpcServer = router.getRouter().getRpcServer(); final DatanodeInfo[] datanodeReport = rpcServer.getCachedDatanodeReport(DatanodeReportType.LIVE); assertEquals(12, datanodeReport.length); DatanodeInfo[] datanodeReport1 = rpcServer.getCachedDatanodeReport(DatanodeReportType.LIVE); assertArrayEquals(datanodeReport1, datanodeReport); MiniDFSCluster miniDFSCluster = getCluster().getCluster(); DataNodeProperties dnprop = miniDFSCluster.stopDataNode(0); GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { DatanodeInfo[] dn = null; try { dn = rpcServer.getCachedDatanodeReport(DatanodeReportType.LIVE); } catch (IOException ex) { LOG.error("Error on getCachedDatanodeReport"); } return !Arrays.equals(datanodeReport, dn); } }, 500, 5 * 1000); final DatanodeInfo[] datanodeReport2 = rpcServer.getCachedDatanodeReport(DatanodeReportType.LIVE); assertEquals(datanodeReport.length - 1, datanodeReport2.length); miniDFSCluster.restartDataNode(dnprop); miniDFSCluster.waitActive(); GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { DatanodeInfo[] dn = null; try { dn = rpcServer.getCachedDatanodeReport(DatanodeReportType.LIVE); } catch (IOException ex) { LOG.error("Error on getCachedDatanodeReport"); } return datanodeReport.length == dn.length; } }, 500, 5 * 1000); final DatanodeInfo[] datanodeReport3 = rpcServer.getCachedDatanodeReport(DatanodeReportType.LIVE); assertEquals(datanodeReport.length, datanodeReport3.length); }
Source:
public void dispose(String taskName) { checkNotStaleTask(taskName); log(FINEST, taskName, "Disposing"); ScheduledTaskDescriptor descriptor = tasks.get(taskName); taskLifecycleHook.preTaskDestroy(name, descriptor.getDefinition()); try { descriptor.cancel(true); } finally { tasks.remove(taskName); taskLifecycleHook.postTaskDestroy(name, descriptor.getDefinition()); } }

Target:
public void dispose(String taskName) { checkNotStaleTask(taskName); log(FINEST, taskName, "Disposing"); ScheduledTaskDescriptor descriptor = tasks.remove(taskName); if (descriptor.isActive()) { releasePermit(); } descriptor.cancel(true); }
Source:
private Class loadGroovyClass(final Resource groovyScript, final GroovyClassLoader loader) throws IOException { if ("jar".equals(groovyScript.getURI().getScheme())) { return loader.parseClass(new BufferedReader(new InputStreamReader(groovyScript.getInputStream(), StandardCharsets.UTF_8)), groovyScript.getFilename()); } else { val groovyFile = groovyScript.getFile(); if (groovyFile.exists()) { return loader.parseClass(groovyFile); } } throw new FileNotFoundException("Groovy script at [" + groovyScript + "] does not exist"); }

Target:
private Class loadGroovyClass(final Resource groovyScript, final GroovyClassLoader loader) throws IOException { if (ResourceUtils.isJarResource(groovyScript)) { try (val groovyReader = new BufferedReader(new InputStreamReader(groovyScript.getInputStream(), StandardCharsets.UTF_8))) { return loader.parseClass(groovyReader, groovyScript.getFilename()); } } val groovyFile = groovyScript.getFile(); if (groovyFile.exists()) { return loader.parseClass(groovyFile); } return null; }
Source:
private void writeAck(ChannelHandlerContext ctx, byte protocol, int sequence) { ByteBuf buffer = ctx.alloc().buffer(6); buffer.writeByte(protocol); buffer.writeByte('A'); buffer.writeInt(sequence); ctx.writeAndFlush(buffer); }

Target:
private void writeAck(ChannelHandlerContext ctx, byte protocol, int sequence) { ctx.write(new Ack(protocol, sequence)); }
Source:
public void testOlsonTimeZoneConversion() { final String[] timeZoneIds = TimeZone.getAvailableIDs(); for (final String timeZoneId : timeZoneIds) { if(timeZoneId.startsWith("America") || timeZoneId.startsWith("Europe") || timeZoneId.startsWith("Africa")) { final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId); final OlsonTimeZoneDefinition olsonTimeZone = new OlsonTimeZoneDefinition(timeZone); final String olsonTimeZoneId = olsonTimeZone.getId(); Assert.assertFalse(StringUtils.isBlank(olsonTimeZoneId)); } } }

Target:
public void testOlsonTimeZoneConversion() { final Map<String, String> olsonTimeZoneToMsMap = TimeZoneUtils.createOlsonTimeZoneToMsMap(); final String[] timeZoneIds = TimeZone.getAvailableIDs(); for (final String timeZoneId : timeZoneIds) { final boolean america = timeZoneId.startsWith("America"); final boolean europe = timeZoneId.startsWith("Europe"); final boolean africa = timeZoneId.startsWith("Africa"); if (america || europe || africa) { final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId); final OlsonTimeZoneDefinition olsonTimeZone = new OlsonTimeZoneDefinition(timeZone); final String olsonTimeZoneId = olsonTimeZone.getId(); Assert.assertFalse(StringUtils.isBlank(olsonTimeZoneId)); Assert.assertEquals(olsonTimeZoneToMsMap.get(timeZoneId), olsonTimeZoneId); } } }
Source:
public void testForLoopInstrumentation() { CompilerOptions options = createCompilerOptions(); String source = lines( "for(var i = 0 ; i < 10 ; ++i) {", " console.log('*');", "}"); String[] sourceArr = {instrumentCodeSource, source}; String expected = lines( "for(var i = 0 ; i < 10 ; ++i) {", getInstrumentCodeLine("C", 1, 0), ";", " console.log('*');", "}", getInstrumentCodeLine("E", 1, 0), ";"); String[] expectedArr = {instrumentCodeExpected, expected}; test(options, sourceArr, expectedArr); }

Target:
public void testForLoopInstrumentation() { CompilerOptions options = createCompilerOptions(); String source = lines( "for(var i = 0 ; i < 10 ; ++i) {", " console.log('*');", "}"); String[] sourceArr = {instrumentCodeSource, source}; String expected = lines( "for(var i = 0 ; i < 10 ; ++i) {", getInstrumentCodeLine("C", 1, 0), ";", " console.log('*');", "}"); String[] expectedArr = {instrumentCodeExpected, expected}; test(options, sourceArr, expectedArr); }
Source:
public static Boolean isZip(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(ZIP_SUFFIX); }

Target:
public static boolean isZip(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(ZIP_SUFFIX); }
Source:
private AffMatchOrganizationAltNameFiller createAffMatchOrganizationAltNameFiller() throws IOException { AffMatchOrganizationAltNameFiller altNameFiller = new AffMatchOrganizationAltNameFiller(); List<String> altNamesCountryCodes = of( "at", "be", "bg", "cy", "cz", "de", "dk", "ee", "es", "fi", "fr", "gr", "hr", "hu", "it", "lt", "lu", "lv", "nl", "pl", "pt", "ro", "se", "si", "sk" ); List<String> alternativeNamesResources = altNamesCountryCodes.stream() .map(code -> "/eu/dnetlib/iis/wf/affmatching/universities/universities_" + code + ".csv").collect(toList()); List<List<String>> alternativeNamesDictionary = new CsvOrganizationAltNamesDictionaryFactory().createAlternativeNamesDictionary(alternativeNamesResources); altNameFiller.setAlternativeNamesDictionary(alternativeNamesDictionary); return altNameFiller; }

Target:
private AffMatchOrganizationAltNameFiller createAffMatchOrganizationAltNameFiller() throws IOException { AffMatchOrganizationAltNameFiller altNameFiller = new AffMatchOrganizationAltNameFiller(); List<Set<String>> alternativeNamesDictionary = new CsvOrganizationAltNamesDictionaryFactory() .createAlternativeNamesDictionary(OrganizationAltNameConst.CLASSPATH_ALTERNATIVE_NAMES_CSV_FILES); altNameFiller.setAlternativeNamesDictionary(alternativeNamesDictionary); return altNameFiller; }
Source:
private MutateRowsRequest createRetryRequest(List<Integer> indiciesToRetry) { MutateRowsRequest.Builder updatedRequest = MutateRowsRequest.newBuilder() .setTableName(originalRequest.getTableName()); mapToOriginalIndex = toIntArray(indiciesToRetry); for (int i = 0; i < indiciesToRetry.size(); i++) { updatedRequest.addEntries(originalRequest.getEntries(indiciesToRetry.get(i))); } return updatedRequest.build(); }

Target:
private MutateRowsRequest createRetryRequest(List<Integer> indiciesToRetry) { MutateRowsRequest.Builder updatedRequest = MutateRowsRequest.newBuilder() .setTableName(originalRequest.getTableName()); mapToOriginalIndex = new int[indiciesToRetry.size()]; for (int i = 0; i < indiciesToRetry.size(); i++) { mapToOriginalIndex[i] = indiciesToRetry.get(i); updatedRequest.addEntries(originalRequest.getEntries(indiciesToRetry.get(i))); } return updatedRequest.build(); }
Source:
private boolean isAdmin(Set<String> entities) { String adminRole = conf.getString(ConfVars.ZEPPELIN_OWNER_ROLE); if (adminRole.isEmpty()) { return false; } return entities.contains(adminRole); }

Target:
private boolean isAdmin(Set<String> entities) { String adminRole = conf.getString(ConfVars.ZEPPELIN_OWNER_ROLE); if (StringUtils.isBlank(adminRole)) { return false; } return entities.contains(adminRole); }
Source:
private void checkValue(V valueObject) { CheckerUtil.checkKey(valueType, valueObject); }

Target:
private void checkValue(V valueObject) { CheckerUtil.checkValue(valueType, valueObject); }
Source:
public Mono<Instant> renewMessageLock(MessageLockToken lockToken) { if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (Objects.isNull(lockToken)) { return monoError(logger, new NullPointerException("'receivedMessage' cannot be null.")); } else if (CoreUtils.isNullOrEmpty(lockToken.getLockToken())) { return monoError(logger, new NullPointerException("'receivedMessage.lockToken' cannot be null.")); } UUID lockTokenUUID; try { lockTokenUUID = UUID.fromString(lockToken.getLockToken()); } catch (IllegalArgumentException ex) { return monoError(logger, new IllegalStateException( String.format(INVALID_LOCK_TOKEN_STRING, lockToken.getLockToken()))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockTokenUUID)) .map(instant -> { if (lockToken instanceof ServiceBusReceivedMessage) { ((ServiceBusReceivedMessage) lockToken).setLockedUntil(instant); } return instant; }); }

Target:
public Mono<Instant> renewMessageLock(MessageLockToken lockToken) { if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (Objects.isNull(lockToken)) { return monoError(logger, new NullPointerException("'receivedMessage' cannot be null.")); } else if (Objects.isNull(lockToken.getLockToken())) { return monoError(logger, new NullPointerException("'receivedMessage.lockToken' cannot be null.")); } else if (lockToken.getLockToken().isEmpty()) { return monoError(logger, new IllegalArgumentException("'message.lockToken' cannot be empty.")); } UUID lockTokenUuid = null; try { lockTokenUuid = UUID.fromString(lockToken.getLockToken()); } catch (IllegalArgumentException ex) { monoError(logger, ex); } UUID finalLockTokenUuid = lockTokenUuid; return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(finalLockTokenUuid)) .map(instant -> { if (lockToken instanceof ServiceBusReceivedMessage) { ((ServiceBusReceivedMessage) lockToken).setLockedUntil(instant); } return instant; }); }
Source:
private void prepareGuestAgentNetworkDevicesForUpdate() { for (VmInternalData vmInternalData : _runningVms.values()) { VmDynamic vmDynamic = vmInternalData.getVmDynamic(); if (vmDynamic != null) { VM vm = _vmDict.get(vmDynamic.getId()); if (vm != null) { List<VmGuestAgentInterface> vmGuestAgentInterfaces = vmInternalData.getVmGuestAgentInterfaces(); int guestAgentNicHash = vmGuestAgentInterfaces == null ? 0 : vmGuestAgentInterfaces.hashCode(); if (guestAgentNicHash != vmDynamic.getGuestAgentNicHash()) { vmGuestAgentNics.put(vmDynamic.getId(), vmGuestAgentInterfaces); if (_vmDynamicToSave.containsKey(vm.getId())) { _vmDynamicToSave.get(vm.getId()).setGuestAgentNicHash(guestAgentNicHash); _vmDynamicToSave.get(vm.getId()) .setvm_ip(extractVmIpsFromGuestAgentInterfaces(vmGuestAgentInterfaces)); } else { AddVmDynamicToList(vmDynamic); } } } } } }

Target:
private void prepareGuestAgentNetworkDevicesForUpdate() { for (VmInternalData vmInternalData : _runningVms.values()) { VmDynamic vmDynamic = vmInternalData.getVmDynamic(); if (vmDynamic != null) { VM vm = _vmDict.get(vmDynamic.getId()); if (vm != null) { List<VmGuestAgentInterface> vmGuestAgentInterfaces = vmInternalData.getVmGuestAgentInterfaces(); int guestAgentNicHash = vmGuestAgentInterfaces == null ? 0 : vmGuestAgentInterfaces.hashCode(); if (guestAgentNicHash != vmDynamic.getGuestAgentNicsHash()) { vmGuestAgentNics.put(vmDynamic.getId(), vmGuestAgentInterfaces); if (_vmDynamicToSave.containsKey(vm.getId())) { updateGuestAgentInterfacesChanges(_vmDynamicToSave.get(vm.getId()), vmGuestAgentInterfaces, guestAgentNicHash); } else { updateGuestAgentInterfacesChanges(vmDynamic, vmGuestAgentInterfaces, guestAgentNicHash); AddVmDynamicToList(vmDynamic); } } } } } }
Source:
public void getKeys(IPointable result) throws SystemException { try { abvs.reset(); slots.clear(); dataArea.reset(); int dataAreaOffset = getDataAreaOffset(bytes, start); int entryCount = getEntryCount(); int s; for (int i = 0; i < entryCount; i++) { s = dataAreaOffset + getRelativeEntryStartOffset(i); dataArea.getDataOutput().write(ValueTag.XS_STRING_TAG); dataArea.getDataOutput().write(bytes, s, getKeyLength(bytes, s)); slots.append(dataArea.getLength()); } finishSequenceBuild(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001); } }

Target:
public void getKeys(IPointable result) throws IOException { abvs.reset(); sb.reset(abvs); int dataAreaOffset = getDataAreaOffset(bytes, start); int entryCount = getEntryCount(); int s; for (int i = 0; i < entryCount; i++) { s = dataAreaOffset + getRelativeEntryStartOffset(i); key1.set(bytes, s, getKeyLength(bytes, s)); sb.addItem(ValueTag.XS_STRING_TAG, key1); } sb.finish(); result.set(abvs); }
Source:
public void testCTAWithCampaignMetadata() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_message_id", "1"); intent.putExtra("mp_campaign_id", "2"); intent.putExtra("mp", "some_extra_data"); intent.putExtra("mp_cta", "<LINK_0>"); MixpanelPushNotification.PushTapAction fakeOnTap = new MixpanelPushNotification.PushTapAction(MixpanelPushNotification.PushTapTarget.fromString("browser"), "<LINK_0>"); PushTapActionMatcher matcher = new PushTapActionMatcher(fakeOnTap); mpPushSpy.createNotification(intent); verify(mpPushSpy).getRoutingIntent(argThat(matcher)); }

Target:
public void testCTAWithCampaignMetadata() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_message_id", "1"); intent.putExtra("mp_campaign_id", "2"); intent.putExtra("mp", "some_extra_data"); intent.putExtra("mp_cta", "<LINK_0>"); MixpanelNotificationData.PushTapAction fakeOnTap = new MixpanelNotificationData.PushTapAction(MixpanelNotificationData.PushTapTarget.fromString("browser"), "<LINK_0>"); PushTapActionMatcher matchesFakeOnTap = new PushTapActionMatcher(fakeOnTap); mpPushSpy.createNotification(intent); verify(mpPushSpy).getRoutingIntent(argThat(matchesFakeOnTap)); verify(mpPushSpy).buildBundle(argThat(matchesFakeOnTap)); }
Source:
@Test public void rule_can_be_changed_to_strict() { Result result = runner.run(MutableStrictJUnitTestRuleTest.LenientByDefault.class); JUnitResultAssert.assertThat(result) .succeeds(1) .fails(1, RuntimeException.class); }

Target:
@Test public void rule_can_be_changed_to_strict() { Result result = runner.run(StrictByDefault.class); JUnitResultAssert.assertThat(result) .succeeds(1) .fails(1, RuntimeException.class); }
Source:
public void equal_shouldReturnFalseIfOnlyEndDateOfOneObjectIsNull() { CohortMembership cohortMembershipOne = new CohortMembership(13); CohortMembership cohortMembershipTwo = new CohortMembership(12); long timestmap = 1577836801; Date startDate1 = new Date(timestmap); Date endDate1 = null; Date startDate2 = new Date(timestmap); Date endDate2 = null; cohortMembershipOne.setEndDate(endDate1); cohortMembershipOne.setStartDate(startDate1); cohortMembershipTwo.setStartDate(startDate2); cohortMembershipTwo.setEndDate(endDate2); assertFalse(cohortMembershipOne.equals(cohortMembershipTwo)); }

Target:
public void equal_shouldReturnFalseIfOnlyEndDateOfOneObjectIsNull() { final int PATIENT_ID = 13; CohortMembership cohortMembershipOne = new CohortMembership(PATIENT_ID); CohortMembership cohortMembershipTwo = new CohortMembership(PATIENT_ID); final int TIMESTAMP = 1577836801; Date startDate1 = new Date(TIMESTAMP); Date endDate1 = null; Date startDate2 = new Date(TIMESTAMP); Date endDate2 = new Date(TIMESTAMP); cohortMembershipOne.setEndDate(endDate1); cohortMembershipOne.setStartDate(startDate1); cohortMembershipTwo.setStartDate(startDate2); cohortMembershipTwo.setEndDate(endDate2); assertFalse(cohortMembershipOne.equals(cohortMembershipTwo)); }
Source:
public void runInToolingApi(CancellationTokenSource tokenSource, IProgressMonitor monitor) throws Exception { try { SubMonitor progress = SubMonitor.convert(monitor, 5); progress.setTaskName((String.format("Synchronizing Gradle build at %s with workspace", this.gradleBuild.getBuildConfig().getRootProjectDirectory()))); new ImportRootProjectOperation(this.gradleBuild.getBuildConfig(), this.newProjectHandler).run(progress.newChild(1)); Set<EclipseProject> allProjects = ModelProviderUtil.fetchAllEclipseProjects(this.gradleBuild, tokenSource, FetchStrategy.FORCE_RELOAD, progress.newChild(1)); new ValidateProjectLocationOperation(allProjects).run(progress.newChild(1)); new RunOnImportTasksOperation(allProjects, this.gradleBuild.getBuildConfig()).run(progress.newChild(1), tokenSource); this.failures = new SynchronizeGradleBuildOperation(allProjects, this.gradleBuild, this.newProjectHandler, ProjectConfigurators.create(this.gradleBuild, CorePlugin.extensionManager().loadConfigurators())).run(progress.newChild(1)); } finally { this.gradleBuild.projectConnectionCache.clear(); } }

Target:
public void runInToolingApi(CancellationTokenSource tokenSource, IProgressMonitor monitor) throws Exception { try { SubMonitor progress = SubMonitor.convert(monitor, 5); progress.setTaskName((String.format("Synchronizing Gradle build at %s with workspace", this.gradleBuild.getBuildConfig().getRootProjectDirectory()))); new ImportRootProjectOperation(this.gradleBuild.getBuildConfig(), this.newProjectHandler).run(progress.newChild(1)); Set<EclipseProject> allProjects = ModelProviderUtil.fetchAllEclipseProjects(this.gradleBuild, tokenSource, FetchStrategy.FORCE_RELOAD, progress.newChild(1)); new ValidateProjectLocationOperation(allProjects).run(progress.newChild(1)); new RunOnImportTasksOperation(allProjects, this.gradleBuild.getBuildConfig()).run(progress.newChild(1), tokenSource); this.failures = new SynchronizeGradleBuildOperation(allProjects, this.gradleBuild, this.newProjectHandler, ProjectConfigurators.create(this.gradleBuild, CorePlugin.extensionManager().loadConfigurators())).run(progress.newChild(1)); } finally { this.gradleBuild.projectConnectionCache.invalidateAll(); } }
Source:
public Collection<DrugReferenceMap> getDrugReferenceMaps() { if (drugReferenceMaps == null) { drugReferenceMaps = Collections.EMPTY_LIST; } return drugReferenceMaps; }

Target:
public Set<DrugReferenceMap> getDrugReferenceMaps() { if (drugReferenceMaps == null) { drugReferenceMaps = new HashSet<DrugReferenceMap>(); } return drugReferenceMaps; }
Source:
public PostComment updateComment(long id, String body, long branchId) throws NotFoundException { PostComment comment = get(id); checkHasUpdatePermission(comment, branchId); comment.setBody(body); comment.setUserChanged(userService.getCurrentUser()); comment.setModificationDate(new DateTime(System.currentTimeMillis())); getDao().saveOrUpdate(comment); return comment; }

Target:
public PostComment updateComment(long id, String body, long branchId) throws NotFoundException { PostComment comment = get(id); checkHasUpdatePermission(comment, branchId); comment.setBody(body); comment.setUserChanged(userService.getCurrentUser()); comment.setModificationDate(DateTime.now()); getDao().saveOrUpdate(comment); return comment; }
Source:
synchronized void receiveState(Address sender, int topologyId, Collection<StateChunk> stateChunks) { if (topologyId < topology.getTopologyId()) { if (trace) log.tracef("Discarding state response with old topology id %d for cache %s, the smallest allowed topology id is %d", topologyId, topology.getTopologyId(), cacheName); return; } InboundTransferTask transferTask = transferTaskMap.remove(sender); if (transferTask == null) { if (trace) log.tracef("State received for an unknown request. No record of a state request exists for node %s", sender); return; } if (trace) log.tracef("State chunks received from %s, with topologyId %s, statechunks %s", sender, topologyId, stateChunks); for (StateChunk chunk : stateChunks) { chunk.getCacheEntries().forEach(ice -> addKeyToReplicaMap(sender, ice)); transferTask.onStateReceived(chunk.getSegmentId(), chunk.isLastChunk()); } }

Target:
synchronized void receiveState(Address sender, int topologyId, Collection<StateChunk> stateChunks) { if (topologyId < topology.getTopologyId()) { if (trace) log.tracef("Discarding state response with old topology id %d for cache %s, the smallest allowed topology id is %d", topologyId, topology.getTopologyId(), cacheName); return; } InboundTransferTask transferTask = transferTaskMap.get(sender); if (transferTask == null) { if (trace) log.tracef("State received for an unknown request. No record of a state request exists for node %s", sender); return; } if (trace) log.tracef("State chunks received from %s, with topologyId %s, statechunks %s", sender, topologyId, stateChunks); for (StateChunk chunk : stateChunks) { boolean isLastChunk = chunk.isLastChunk(); chunk.getCacheEntries().forEach(ice -> addKeyToReplicaMap(sender, ice)); transferTask.onStateReceived(chunk.getSegmentId(), isLastChunk); if (isLastChunk) transferTaskMap.remove(sender); } }
Source:
public String checkBoxIndeterminateIconColor() { return "#707070"; }

Target:
public String checkBoxIndeterminateIconColor() { return this.getDisabledMenuColor(); }
Source:
public void testDeleteNotification() { Notification notification = curationApiAdmin.createNotification(testNotification()); long id = notification.getId(); boolean userCanDelete = true; try { curationApiUser.deleteNotification(id); } catch (ApiException e) { userCanDelete = false; } assertFalse(userCanDelete); curationApiAdmin.deleteNotification(id); int count = testingPostgres.runSelectStatement(String.format("select count(id) from notification where id = '%s'", id), int.class); assertEquals(0, count); }

Target:
public void testDeleteNotification() { Notification notification = curationApiAdmin.createNotification(testNotification()); long id = notification.getId(); boolean userCanDelete = true; try { curationApiUser.deleteNotification(id); } catch (ApiException e) { userCanDelete = false; assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), e.getCode()); } assertFalse(userCanDelete); curationApiAdmin.deleteNotification(id); int count = testingPostgres.runSelectStatement(String.format("select count(id) from notification where id = '%s'", id), int.class); assertEquals(0, count); }
Source:
public QuorumUtil(int n, int syncLimit) throws RuntimeException { try { ClientBase.setupTestEnv(); JMXEnv.setUp(); N = n; ALL = 2 * N + 1; tickTime = 2000; initLimit = 5; this.syncLimit = syncLimit; connectToLearnerMasterLimit = 3; electionAlg = 3; hostPort = ""; for (int i = 1; i <= ALL; ++i) { PeerStruct ps = new PeerStruct(); ps.id = i; ps.dataDir = ClientBase.createTmpDir(); ps.clientPort = PortAssignment.unique(); peers.put(i, ps); peersView.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", ps.clientPort), LearnerType.PARTICIPANT)); hostPort += "127.0.0.1:" + ps.clientPort + ((i == ALL) ? "" : ","); } for (int i = 1; i <= ALL; ++i) { PeerStruct ps = peers.get(i); LOG.info("Creating QuorumPeer {}; public port {}", i, ps.clientPort); ps.peer = new QuorumPeer(peersView, ps.dataDir, ps.dataDir, ps.clientPort, electionAlg, ps.id, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit); assertEquals(ps.clientPort, ps.peer.getClientPort()); } } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public QuorumUtil(int n, int syncLimit) throws RuntimeException { try { ClientBase.setupTestEnv(); JMXEnv.setUp(); N = n; ALL = 2 * N + 1; tickTime = 2000; initLimit = 3; this.syncLimit = syncLimit; connectToLearnerMasterLimit = 3; electionAlg = 3; hostPort = ""; for (int i = 1; i <= ALL; ++i) { PeerStruct ps = new PeerStruct(); ps.id = i; ps.dataDir = ClientBase.createTmpDir(); ps.clientPort = PortAssignment.unique(); peers.put(i, ps); peersView.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", ps.clientPort), LearnerType.PARTICIPANT)); hostPort += "127.0.0.1:" + ps.clientPort + ((i == ALL) ? "" : ","); } for (int i = 1; i <= ALL; ++i) { PeerStruct ps = peers.get(i); LOG.info("Creating QuorumPeer {}; public port {}", i, ps.clientPort); ps.peer = new QuorumPeer(peersView, ps.dataDir, ps.dataDir, ps.clientPort, electionAlg, ps.id, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit); assertEquals(ps.clientPort, ps.peer.getClientPort()); } } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private void validateHaemoglobinCount(DonationBackingForm donationBackingForm, Errors errors) { Integer haemoglobinCount = null; Integer hbMin = Integer.parseInt(utilController.getGeneralConfigValueByName("donation.donor.hbMin")); Integer hbMax = Integer.parseInt(utilController.getGeneralConfigValueByName("donation.donor.hbMax")); if (donationBackingForm.getHaemoglobinCount() != null) haemoglobinCount = donationBackingForm.getHaemoglobinCount().intValue(); if (haemoglobinCount != null){ if (haemoglobinCount == null || !(haemoglobinCount >= hbMin && haemoglobinCount <= hbMax)) errors.rejectValue("donation.haemoglobinCount", "400", "Enter a value between "+ hbMin + " to " + hbMax); } }

Target:
private void validateHaemoglobinCount(DonationBackingForm donationBackingForm, Errors errors) { Integer haemoglobinCount = null; Integer hbMin = Integer.parseInt(utilController.getGeneralConfigValueByName("donation.donor.hbMin")); Integer hbMax = Integer.parseInt(utilController.getGeneralConfigValueByName("donation.donor.hbMax")); if (donationBackingForm.getHaemoglobinCount() != null) haemoglobinCount = donationBackingForm.getHaemoglobinCount().intValue(); if (haemoglobinCount != null && (haemoglobinCount < hbMin || haemoglobinCount > hbMax)) { errors.rejectValue("donation.haemoglobinCount", "400", "Enter a value between "+ hbMin + " to " + hbMax); } }