auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void createProfiles() throws ConfigurationException { List<ExtensionEntry> authnExtensions = ConfigurationLoader.getInstance().getExtensionsByService(AUTHN_SERVICE); for (ExtensionEntry authnExtension: authnExtensions) { String pluginName = authnExtension.getConfig().getString(AUTHN_AUTHZ_PLUGIN); ExtensionEntry authzExtension = ConfigurationLoader.getInstance().getExtensionByName(pluginName); if (authzExtension == null) { throw new ConfigurationException("The authentication extension " + authnExtension.getName() + " does not have a matching authorization extension"); } Directory directory = DirectoryManager.getInstance().parseDirectory(authzExtension.getConfig()); Authenticator authenticator = AuthenticatorManager.getInstance().parseAuthenticator(authzExtension.getConfig()); if (directory == null) { throw new ConfigurationException("No directory could be obtained for authorization plugin " + authzExtension.getName()); } if (authenticator == null) { throw new ConfigurationException("No authenticator could be obtained for authentication plugin " + authnExtension.getName()); } String profileName = authnExtension.getConfig().getString(AUTHN_PROFILE); if (profileName == null) { throw new ConfigurationException("Profile name could not be obtained from configuration of authentication plugin " + authnExtension.getName()); } AuthenticationProfile profile = new AuthenticationProfile(profileName, authenticator, directory); profiles.put(profileName, profile); } }

Target:
public void createProfiles() throws ConfigurationException { for (ExtensionEntry authnExtension : ConfigurationLoader.getInstance().getExtensionsByService(AUTHN_SERVICE)) { AuthenticationProfile profile = new AuthenticationProfile(AuthenticatorManager.getInstance() .parseAuthenticator(authnExtension.getConfig()), DirectoryManager.getInstance() .parseDirectory(ConfigurationLoader.getInstance() .getExtensionByName(authnExtension.getConfig().getString(AUTHN_AUTHZ_PLUGIN)) .getConfig())); profiles.put(profile.getName(), profile); } }
Source:
public void nullable_matcher() throws Exception { mock.oneArg((Character) null); mock.oneArg((Character) 'x'); verify(mock, times(2)).oneArg(nullable(Character.class)); }

Target:
public void nullable_matcher() throws Exception { mock.oneArg((Character) null); mock.oneArg(Character.valueOf('€')); verify(mock, times(2)).oneArg(nullable(Character.class)); }
Source:
protected void subscribe() { messageBusConnection = project.getMessageBus().connect(); }

Target:
private void subscribe() { messageBusConnection = project.getMessageBus().connect(); registerListeners(messageBusConnection); }
Source:
public String toString(){ return String.format(" Host name: %s%n, Domain name: %s%n, DNS servers: %s%n, IPv4 Gateway: %s%n, IPv6 Gateway: %s%n" ,this.getHostName(),this.getDomainName(),this.getDnsServers(),this.getIpv4DefaultGateway(),this.getIpv6DefaultGateway()); }

Target:
public String toString(){ return String.format("Host name: %s, Domain name: %s, DNS servers: %s, IPv4 Gateway: %s, IPv6 Gateway: %s" ,this.getHostName(),this.getDomainName(),Arrays.toString(this.getDnsServers()),this.getIpv4DefaultGateway(),this.getIpv6DefaultGateway()); }
Source:
public void rewritesOnSubqueryWithoutProjection() { tester().assertThat(rule) .on(p -> p.lateral( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.enforceSingleRow( p.filter( p.expression("1 = a"), p.values(p.symbol("a")))))) .matches( project( filter( ensureScalarSubquery(), markDistinct( "is_distinct", ImmutableList.of("unique"), lateral( ImmutableList.of("corr"), assignUniqueId( "unique", values("corr")), filter( "1 = a", values("a"))))))); }

Target:
public void rewritesOnSubqueryWithoutProjection() { tester().assertThat(rule) .on(p -> p.lateral( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.enforceSingleRow( p.filter( p.expression("1 = a"), p.values(ImmutableList.of(p.symbol("a")), TWO_ROWS))))) .matches( project( filter( ensureScalarSubquery(), markDistinct( "is_distinct", ImmutableList.of("unique"), lateral( ImmutableList.of("corr"), assignUniqueId( "unique", values("corr")), filter( "1 = a", values("a"))))))); }
Source:
public void snapshotIndexes(GridH2QueryContext qctx, int segment) { if (!snapshotEnabled) return; Object[] segmentSnapshot; for (long waitTime = 200; ; waitTime *= 2) { segmentSnapshot = actualSnapshot.get(segment); if (segmentSnapshot != null) { segmentSnapshot = doSnapshotIndexes(segmentSnapshot, qctx); if (segmentSnapshot != null) return; } if (tryLock(true, waitTime)) break; } try { ensureNotDestroyed(); segmentSnapshot = actualSnapshot.get(segment); if (segmentSnapshot != null) segmentSnapshot = doSnapshotIndexes(segmentSnapshot, qctx); if (segmentSnapshot == null) { segmentSnapshot = doSnapshotIndexes(null, qctx); assert segmentSnapshot != null; actualSnapshot.set(segment, segmentSnapshot); } } finally { unlock(true); } }

Target:
public void snapshotIndexes(GridH2QueryContext qctx, int segment) { if (!snapshotEnabled) return; Object[] segmentSnapshot; for (long waitTime = 200; ; waitTime *= 2) { segmentSnapshot = actualSnapshot.get(segment); if (segmentSnapshot != null) { segmentSnapshot = doSnapshotIndexes(segment, segmentSnapshot, qctx); if (segmentSnapshot != null) return; } if (tryLock(true, waitTime)) break; } try { ensureNotDestroyed(); segmentSnapshot = actualSnapshot.get(segment); if (segmentSnapshot != null) segmentSnapshot = doSnapshotIndexes(segment, segmentSnapshot, qctx); if (segmentSnapshot == null) { segmentSnapshot = doSnapshotIndexes(segment,null, qctx); assert segmentSnapshot != null; actualSnapshot.set(segment, segmentSnapshot); } } finally { unlock(true); } }
Source:
@Test public void callAdapterFactoryNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; NonMatchingCallAdapterFactory nonMatchingFactory = new NonMatchingCallAdapterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addCallAdapterFactory(nonMatchingFactory) .build(); try { retrofit.callAdapter(type, annotations); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("" + "Could not locate call adapter for class java.lang.String.\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingCallAdapterFactory\n" + " * retrofit2.DefaultCallAdapterFactory"); } assertThat(nonMatchingFactory.called).isTrue(); }

Target:
@Test public void callAdapterFactoryNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; NonMatchingCallAdapterFactory nonMatchingFactory = new NonMatchingCallAdapterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addCallAdapterFactory(nonMatchingFactory) .build(); try { retrofit.callAdapter(type, annotations); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("" + "Could not locate call adapter for class java.lang.String.\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingCallAdapterFactory\n" + " * retrofit2.DefaultCallAdapterFactory"); } assertThat(nonMatchingFactory.called).isTrue(); }
Source:
public static boolean removeActionBlocker(ZooKeeper zk, String node, VoltLogger log) { try { zk.delete(node, -1); } catch (KeeperException e) { if (e.code() != KeeperException.Code.NONODE) { if (log != null) { log.error("Failed to remove action blocker: " + node + "\n" + e.getMessage(), e); } return false; } } catch (InterruptedException e) { log.error("Failed to remove action blocker: " + node + "\n" + e.getMessage(), e); return false; } return true; }

Target:
public static boolean removeActionBlocker(ZooKeeper zk, String node, VoltLogger log) { try { zk.delete(node, -1); } catch (KeeperException e) { if (e.code() != KeeperException.Code.NONODE) { if (log != null) { log.error("Failed to remove action blocker: " + node + "\n" + e.getMessage(), e); } return false; } } catch (InterruptedException e) { return false; } return true; }
Source:
public void clusterMapInterface() throws JSONException { TestUtils.TestHardwareLayout testHardwareLayout = new TestUtils.TestHardwareLayout("Alpha"); TestUtils.TestPartitionLayout testPartitionLayout = new TestUtils.TestPartitionLayout(testHardwareLayout); ClusterMapManager clusterMapManager = new ClusterMapManager(testPartitionLayout.getPartitionLayout()); for (String metricName : clusterMapManager.getMetricRegistry().getNames()) { System.out.println(metricName); } List<? extends PartitionId> partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), testPartitionLayout.getPartitionCount()); for (int i = 0; i < partitionIds.size(); i++) { PartitionId partitionId = partitionIds.get(i); assertEquals(partitionId.getReplicaIds().size(), testPartitionLayout.getReplicaCount()); DataInputStream partitionStream = new DataInputStream(new ByteBufferInputStream(ByteBuffer.wrap(partitionId.getBytes()))); try { PartitionId fetchedPartitionId = clusterMapManager.getPartitionIdFromStream(partitionStream); assertEquals(partitionId, fetchedPartitionId); } catch (IOException e) { assertEquals(true, false); } } for (Datacenter datacenter : testHardwareLayout.getHardwareLayout().getDatacenters()) { for (DataNode dataNode : datacenter.getDataNodes()) { DataNodeId dataNodeId = clusterMapManager.getDataNodeId(dataNode.getHostname(), dataNode.getPort()); assertEquals(dataNodeId, dataNode); for (ReplicaId replicaId : clusterMapManager.getReplicaIds(dataNodeId)) { assertEquals(dataNodeId, replicaId.getDataNodeId()); } } } }

Target:
public void clusterMapInterface() throws JSONException { TestUtils.TestHardwareLayout testHardwareLayout = new TestUtils.TestHardwareLayout("Alpha"); TestUtils.TestPartitionLayout testPartitionLayout = new TestUtils.TestPartitionLayout(testHardwareLayout); ClusterMapManager clusterMapManager = new ClusterMapManager(testPartitionLayout.getPartitionLayout()); for (String metricName : clusterMapManager.getMetricRegistry().getNames()) { System.out.println(metricName); } List<PartitionId> partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), testPartitionLayout.getPartitionCount()); for (int i = 0; i < partitionIds.size(); i++) { PartitionId partitionId = partitionIds.get(i); assertEquals(partitionId.getReplicaIds().size(), testPartitionLayout.getReplicaCount()); DataInputStream partitionStream = new DataInputStream(new ByteBufferInputStream(ByteBuffer.wrap(partitionId.getBytes()))); try { PartitionId fetchedPartitionId = clusterMapManager.getPartitionIdFromStream(partitionStream); assertEquals(partitionId, fetchedPartitionId); } catch (IOException e) { assertEquals(true, false); } } for (Datacenter datacenter : testHardwareLayout.getHardwareLayout().getDatacenters()) { for (DataNode dataNode : datacenter.getDataNodes()) { DataNodeId dataNodeId = clusterMapManager.getDataNodeId(dataNode.getHostname(), dataNode.getPort()); assertEquals(dataNodeId, dataNode); for (ReplicaId replicaId : clusterMapManager.getReplicaIds(dataNodeId)) { assertEquals(dataNodeId, replicaId.getDataNodeId()); } } } }
Source:
protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) { boolean valid = super.processCustomRouteDocumentBusinessRules(document); if (doesAccountGlobalHaveAccountRestrictionCodeAndNoSubFUndGroupCode()) { valid = isTheNewRestrictionCodeValidForEachAccount() && valid; } return valid; }

Target:
protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) { boolean valid = super.processCustomRouteDocumentBusinessRules(document); if (doesAccountGlobalHaveAccountRestrictionCodeAndNoSubFundGroupCode()) { valid = isTheNewRestrictionCodeValidForEachAccount() && valid; } return valid; }
Source:
void handleLostAll() { log.debug("Closing lost active tasks as zombies."); final Iterator<Task> iterator = tasks.values().iterator(); while (iterator.hasNext()) { final Task task = iterator.next(); if (task.isActive()) { cleanupTask(task); task.closeDirty(); iterator.remove(); } } }

Target:
void handleLostAll() { log.debug("Closing lost active tasks as zombies."); final Iterator<Task> iterator = tasks.values().iterator(); while (iterator.hasNext()) { final Task task = iterator.next(); final Set<TopicPartition> inputPartitions = task.inputPartitions(); if (task.isActive()) { task.closeDirty(); changelogReader.remove(task.changelogPartitions()); } for (final TopicPartition inputPartition : inputPartitions) { partitionToTask.remove(inputPartition); } iterator.remove(); } }
Source:
protected ValidationInfo doValidate() { final String resourceName = getResourceName(); final Module selectedModule = getModule(); final List<String> directoryNames = getDirNames(); final String fileName = getFileName(); if (resourceName.length() == 0) { return new ValidationInfo("specify resource name", myNameField); } else if (!AndroidResourceUtil.isCorrectAndroidResourceName(resourceName)) { return new ValidationInfo(resourceName + " is not correct resource name", myNameField); } else if (fileName.length() == 0) { return new ValidationInfo("specify file name", myFileNameCombo); } else if (selectedModule == null) { return new ValidationInfo("specify module", myModuleCombo); } else if (directoryNames.size() == 0) { return new ValidationInfo("choose directories", myDirectoriesList); } else if (resourceName.equals(ResourceHelper.prependResourcePrefix(myModule, null))) { return new ValidationInfo("specify more than resource prefix", myNameField); } final ValidationInfo info = CreateXmlResourceDialog.checkIfResourceAlreadyExists(selectedModule, resourceName, myResourceType, directoryNames, fileName); if (info != null) { return info; } return null; }

Target:
protected ValidationInfo doValidate() { final String resourceName = getResourceName(); final Module selectedModule = getModule(); final List<String> directoryNames = getDirNames(); final String fileName = getFileName(); if (resourceName.isEmpty()) { return new ValidationInfo("specify resource name", myNameField); } else if (!AndroidResourceUtil.isCorrectAndroidResourceName(resourceName)) { return new ValidationInfo(resourceName + " is not correct resource name", myNameField); } else if (fileName.isEmpty()) { return new ValidationInfo("specify file name", myFileNameCombo); } else if (selectedModule == null) { return new ValidationInfo("specify module", myModuleCombo); } else if (directoryNames.isEmpty()) { return new ValidationInfo("choose directories", myDirectoriesList); } else if (resourceName.equals(ResourceHelper.prependResourcePrefix(myModule, null))) { return new ValidationInfo("specify more than resource prefix", myNameField); } return CreateXmlResourceDialog.checkIfResourceAlreadyExists(selectedModule, resourceName, myResourceType, directoryNames, fileName); }
Source:
public ZKConfig(File configFile) throws ConfigException { init(); addConfiguration(configFile); }

Target:
public ZKConfig(File configFile) throws ConfigException { this(); addConfiguration(configFile); }
Source:
protected final Cluster getRuntimeCluster(String host, int port) throws Exception { try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(host, port), getClass().getSimpleName(), OP_TIMEOUT, OP_TIMEOUT, null)) { return diagnosticService.getProxy(TopologyService.class).getRuntimeNodeContext().getCluster(); } }

Target:
protected final Cluster getRuntimeCluster(String host, int port) throws Exception { try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(host, port), getClass().getSimpleName(), getConnectionTimeout(), getConnectionTimeout(), null)) { return diagnosticService.getProxy(TopologyService.class).getRuntimeNodeContext().getCluster(); } }
Source:
public void setClientAuthenticationMethodAsString(String auth) { this.clientAuthenticationMethod.parse(auth); }

Target:
public void setClientAuthenticationMethodAsString(String auth) { this.clientAuthenticationMethod = ClientAuthenticationMethod.parse(auth); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkUpgradePreferences(this); ((SyncthingActivity) getActivity()).registerOnServiceConnectedListener(this); mIsCreate = ((SettingsActivity) getActivity()).getIsCreate(); setHasOptionsMenu(true); if (mIsCreate) { addPreferencesFromResource(R.xml.device_settings_create); } else { addPreferencesFromResource(R.xml.device_settings_edit); } mDeviceId = findPreference("device_id"); mDeviceId.setOnPreferenceChangeListener(this); mName = (EditTextPreference) findPreference("name"); mName.setOnPreferenceChangeListener(this); mAddresses = (EditTextPreference) findPreference("addresses"); mAddresses.setOnPreferenceChangeListener(this); mCompression = (ListPreference) findPreference("compression"); mCompression.setOnPreferenceChangeListener(this); mIntroducer = (CheckBoxPreference) findPreference("introducer"); mIntroducer.setOnPreferenceChangeListener(this); if (!mIsCreate) { mVersion = findPreference("version"); mVersion.setSummary("?"); mCurrentAddress = findPreference("current_address"); mCurrentAddress.setSummary("?"); } if (mIsCreate) { if (savedInstanceState != null) { mDevice = (RestApi.Device) savedInstanceState.getSerializable("device"); } else { mDevice = new RestApi.Device(); mDevice.Name = ""; mDevice.DeviceID = ""; mDevice.Addresses = "dynamic"; mDevice.Compression = "always"; ((EditTextPreference) mDeviceId).setText(mDevice.DeviceID); } } }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((SyncthingActivity) getActivity()).registerOnServiceConnectedListener(this); mIsCreate = ((SettingsActivity) getActivity()).getIsCreate(); setHasOptionsMenu(true); if (mIsCreate) { addPreferencesFromResource(R.xml.device_settings_create); } else { addPreferencesFromResource(R.xml.device_settings_edit); } mDeviceId = findPreference("device_id"); mDeviceId.setOnPreferenceChangeListener(this); mName = (EditTextPreference) findPreference("name"); mName.setOnPreferenceChangeListener(this); mAddresses = (EditTextPreference) findPreference("addresses"); mAddresses.setOnPreferenceChangeListener(this); mCompression = (ListPreference) findPreference("compression"); mCompression.setOnPreferenceChangeListener(this); mIntroducer = (CheckBoxPreference) findPreference("introducer"); mIntroducer.setOnPreferenceChangeListener(this); if (!mIsCreate) { mVersion = findPreference("version"); mVersion.setSummary("?"); mCurrentAddress = findPreference("current_address"); mCurrentAddress.setSummary("?"); } if (mIsCreate) { if (savedInstanceState != null) { mDevice = (RestApi.Device) savedInstanceState.getSerializable("device"); } else { mDevice = new RestApi.Device(); mDevice.Name = ""; mDevice.DeviceID = ""; mDevice.Addresses = "dynamic"; mDevice.Compression = "always"; ((EditTextPreference) mDeviceId).setText(mDevice.DeviceID); } } }
Source:
public String getValue(TreeItem object) { if (webClientProperties.isUserCommentAvailable()) { if ((object.get(NAME).equals(USER_COMMENT)||object.get(NAME).equals(SESSION_TAGS)) && !field.equals(NAME)) { String toShow = object.get(field).replaceAll("\n", "<br>"); return "<img src=\"" + JaggerResources.INSTANCE.getPencilImage().getSafeUri().asString() + "\" height=\"15\" width=\"15\">" + "<ins font-size='10px'>double click to edit</ins><br><br>" + toShow; } } return object.get(field); }

Target:
public String getValue(TreeItem object) { String penImageResource = "<img src=\"" + JaggerResources.INSTANCE.getPencilImage().getSafeUri().asString() + "\" height=\"15\" width=\"15\">" + "<ins font-size='10px'>double click to edit</ins><br><br>"; String toShow; if (webClientProperties.isUserCommentAvailable()) { if (object.get(NAME).equals(USER_COMMENT) && !field.equals(NAME)) { toShow = object.get(field).replaceAll("\n", "<br>"); return penImageResource+toShow; } } if (webClientProperties.isTagsAvailable()) { if (object.get(NAME).equals(SESSION_TAGS) && !field.equals(NAME)) { toShow = object.get(field).replaceAll("\n", "<br>"); return penImageResource+toShow; } } return object.get(field); }
Source:
private void initTicket() { for (Event event : eventDao.list()) { for (Category category : event.getCategories()) { int numberOfTickets = category.getNumberOfTickets(); while (numberOfTickets > 0) { String strSection = ""; int seat = -1; if (category.getType() == CategoryType.SEAT) { strSection = "Niveau " + (new Random().nextInt(2) + 1) * 100; seat = numberOfTickets; } Ticket ticket = new Ticket(event.getId(), category.getId(), strSection, seat); ticketDao.create(ticket); numberOfTickets--; } } } }

Target:
private void initTicket() { for (Event event : eventDao.list()) { for (Category category : event.getCategories()) { int numberOfTickets = category.getNumberOfTickets(); while (numberOfTickets > 0) { Ticket ticket; if (category.getType() == CategoryType.SEAT) { ticket = TicketFactory.createAvailableSeatTicket( event.getId(), category.getId(), (numberOfTickets % 2 == 0) ? "Niveau 100" : "Niveau 200", numberOfTickets); } else { ticket = TicketFactory.createAvailableGeneralAdmissionTicket( event.getId(), category.getId()); } ticketDao.create(ticket); numberOfTickets--; } } } }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search, container, false); this.setHasOptionsMenu(true); ButterKnife.inject(this, view); apiClient = new MITAPIClient(getActivity()); recentSearches = new ArrayList<>(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); Set<String> set = sharedPreferences.getStringSet(NEWS_SEARCH_HISTORY, null); if (set != null) { recentSearches.addAll(set); mitSearchAdapter = new MITSearchAdapter(getActivity().getApplicationContext(), recentSearches, this); recentSearchListView.setAdapter(mitSearchAdapter); } return view; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search, container, false); this.setHasOptionsMenu(true); ButterKnife.inject(this, view); apiClient = new MITAPIClient(getActivity()); recentSearches = new ArrayList<>(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); Set<String> set = sharedPreferences.getStringSet(NEWS_SEARCH_HISTORY, null); if (set != null) { recentSearches.addAll(set); } mitSearchAdapter = new MITSearchAdapter(getActivity().getApplicationContext(), recentSearches, this); recentSearchListView.setAdapter(mitSearchAdapter); return view; }
Source:
public String simplifyHostname(String hostname) { for (String domainName : domainNamesToRemove) { if (domainName != null && !domainName.isEmpty()) { if (domainName.charAt(0) != '.') { domainName = "." + domainName; } hostname = hostname.replace(domainName, ""); } } return String.format("%s_%d", hostname, port); }

Target:
public String simplifyHostname(String hostname) { for (String domainName : domainNamesToRemove) { if (domainName != null && !(domainName = domainName.trim()).isEmpty()) { if (domainName.charAt(0) != '.') { domainName = "." + domainName; } hostname = hostname.replace(domainName, ""); } } return String.format("%s_%d", hostname, port); }
Source:
public Tracer createTracer(String serviceName) { Configuration.SenderConfiguration senderConfiguration = reporterConfig.getSenderConfiguration(); if(outboundSocketBindingSupplier.get() != null) { senderConfiguration.withAgentHost(outboundSocketBindingSupplier.get().getUnresolvedDestinationAddress()) .withAgentPort(outboundSocketBindingSupplier.get().getDestinationPort()); } return new Configuration(serviceName) .withCodec(codecConfig) .withReporter(reporterConfig) .withSampler(samplerConfig) .withTraceId128Bit(traceId128Bit) .withTracerTags(tracerTags) .getTracerBuilder() .withManualShutdown() .build(); }

Target:
public Tracer createTracer(String serviceName) { Configuration.SenderConfiguration senderConfiguration = reporterConfig.getSenderConfiguration(); OutboundSocketBinding outboundSocketBinding = outboundSocketBindingSupplier.get(); if(outboundSocketBinding != null) { senderConfiguration.withAgentHost(outboundSocketBinding.getUnresolvedDestinationAddress()) .withAgentPort(outboundSocketBinding.getDestinationPort()); } return new Configuration(serviceName) .withCodec(codecConfig) .withReporter(reporterConfig) .withSampler(samplerConfig) .withTraceId128Bit(traceId128Bit) .withTracerTags(tracerTags) .getTracerBuilder() .withManualShutdown() .build(); }
Source:
public void registered(final ExecutorDriver driver, final ExecutorInfo executorInfo, final FrameworkInfo frameworkInfo, final SlaveInfo slaveInfo) { if (LOGGER.isDebugEnabled()) LOGGER.debug("registered(driver : {}, executorInfo : {}, frameworkInfo : {}, slaveInfo : {})", driver, protoToString(executorInfo), protoToString(frameworkInfo), protoToString(slaveInfo)); this.executorInfo = executorInfo; }

Target:
public void registered(final ExecutorDriver driver, final ExecutorInfo executorInfo, final FrameworkInfo frameworkInfo, final SlaveInfo slaveInfo) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("registered(driver : {}, executorInfo : {}, frameworkInfo : {}, slaveInfo : {})", driver, protoToString(executorInfo), protoToString(frameworkInfo), protoToString(slaveInfo)); } this.executorInfo = executorInfo; }
Source:
public Iterable<DBObject> getComplianceForTimespan(Date startDate, Date endDate, List<String> consumerIds, List<String> owners) { BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start(); if (owners != null && !owners.isEmpty()) { queryBuilder.add("consumer.owner.key", new BasicDBObject("$in", owners)); } BasicDBObjectBuilder dateQueryBuilder = BasicDBObjectBuilder.start(); if (startDate != null) { dateQueryBuilder.add("$gt", startDate); } if (endDate != null) { dateQueryBuilder.add("$lte", endDate); } if (startDate != null || endDate != null) { queryBuilder.add("status.date", dateQueryBuilder.get()); } BasicDBObject projections = new BasicDBObject(); projections.put("consumer", 1); projections.put("status", 1); projections.put("_id", 0); BasicDBObject project = new BasicDBObject("$project", projections); DBObject query = new BasicDBObject("$match", queryBuilder.get()); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("status.date", 1)); AggregationOutput output = collection.aggregate(Arrays.asList( query, project, sort )); return output.results(); }

Target:
public DBCursor getComplianceForTimespan(Date startDate, Date endDate, List<String> consumerIds, List<String> owners) { BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start(); if (owners != null && !owners.isEmpty()) { queryBuilder.add("consumer.owner.key", new BasicDBObject("$in", owners)); } BasicDBObjectBuilder dateQueryBuilder = BasicDBObjectBuilder.start(); if (startDate != null) { dateQueryBuilder.add("$gt", startDate); } if (endDate != null) { dateQueryBuilder.add("$lte", endDate); } if (startDate != null || endDate != null) { queryBuilder.add("status.date", dateQueryBuilder.get()); } BasicDBObject projections = new BasicDBObject("_id", 1); BasicDBObject project = new BasicDBObject("$project", projections); DBObject query = new BasicDBObject("$match", queryBuilder.get()); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("status.date", 1)); AggregationOutput output = collection.aggregate(Arrays.asList( query, project, sort )); List<ObjectId> resultIds = getObjectIds(output.results()); return collection.find(new BasicDBObject("_id", new BasicDBObject("$in", resultIds))); }
Source:
public void update(SpriteBase sprite) { int plaats = sprites.indexOf(sprite); if (plaats >= 0) { ImageView image = images.get(sprites.indexOf(sprite)); image.relocate(sprite.getX(), sprite.getY()); if (sprite.getSpriteChanged()) { image.setImage(new Image( getClass().getResource(sprite.getImagePath()).toExternalForm())); sprite.setSpriteChanged(false); } image.setRotate(sprite.getR()); } }

Target:
public void update(SpriteBase sprite) { int place = sprites.indexOf(sprite); if (place >= 0) { ImageView image = images.get(sprites.indexOf(sprite)); image.relocate(sprite.getX(), sprite.getY()); if (sprite.getSpriteChanged()) { image.setImage(new Image( getClass().getResource(sprite.getImagePath()).toExternalForm())); sprite.setSpriteChanged(false); } image.setRotate(sprite.getR()); } }
Source:
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { this.processedDocCount ++; if (this.isCheckpointNeeded()) { return context.checkpoint() .onErrorResume(throwable -> { logger.warn("Checkpoint failed; this worker will be killed", throwable); return Mono.error(throwable); }) .doOnSuccess( (Void) -> { this.processedDocCount = 0; this.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }) .then(); } return Mono.empty(); }

Target:
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { this.processedDocCount ++; if (this.isCheckpointNeeded()) { return context.checkpoint() .doOnError(throwable -> { logger.warn("Checkpoint failed; this worker will be killed", throwable); }) .doOnSuccess( (Void) -> { this.processedDocCount = 0; this.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }) .then(); } return Mono.empty(); }
Source:
public List<ClientModel> getClients() { return cacheSession.getClients(this, 0, cacheSession.getClientsCount(this).intValue()); }

Target:
public List<ClientModel> getClients() { return cacheSession.getClients(this); }
Source:
public Optional<WetData> from(DataHolder dataHolder) { if (this.supports(dataHolder)) { SpongeWetData wetData = new SpongeWetData(dataHolder.get(Keys.IS_WET).get()); return Optional.<WetData>of(wetData); } return Optional.absent(); }

Target:
public Optional<WetData> from(DataHolder dataHolder) { if (this.supports(dataHolder)) { if (dataHolder instanceof EntityWolf) { EntityWolf wolf = (EntityWolf) dataHolder; SpongeWetData data = new SpongeWetData(wolf.isWet()); return Optional.<WetData>of(data); } else if ((dataHolder instanceof ItemStack)) { ItemStack stack = (ItemStack) dataHolder; if (stack.getItem().equals(ItemTypes.SPONGE)) { SpongeWetData data = new SpongeWetData(stack.getItemDamage() == 1); return Optional.<WetData>of(data); } } } return Optional.empty(); }
Source:
private AsyncRetryMetrics(Iterable<AsyncRetry> retries) { this(retries, DEFAULT_PREFIX); }

Target:
private AsyncRetryMetrics(Iterable<AsyncRetry> retries) { this(retries, DEFAULT_PREFIX_ASYNC); }
Source:
public boolean hasAllOutputs(TableScanNode node) { Optional<List<ColumnHandle>> columns = layout.getColumns(); if (!columns.isPresent()) { return true; } Set<ColumnHandle> nodeColumnHandles = node.getOutputSymbols().stream() .map(node.getAssignments()::get) .collect(toImmutableSet()); return nodeColumnHandles.containsAll(columns.get()); }

Target:
public boolean hasAllOutputs(TableScanNode node) { if (!layout.getColumns().isPresent()) { return true; } Set<ColumnHandle> columns = ImmutableSet.copyOf(layout.getColumns().get()); List<ColumnHandle> nodeColumnHandles = node.getOutputSymbols().stream() .map(node.getAssignments()::get) .collect(toImmutableList()); return columns.containsAll(nodeColumnHandles); }
Source:
protected SourceFileStore findSourceFileStoreForValidator(final ValidatorSourceRepositorySotre validatorSourceStore, final String validatorId, final ValidatorDescriptor descriptor) { final AbstractFileStore child = validatorSourceStore.getChild(descriptor.getClassName()); if (child == null) { throw new RuntimeException("Validator class " + descriptor.getClassName() + " not found for validator definition " + validatorId + "!"); } if (!(child instanceof SourceFileStore)) { throw new RuntimeException("Invalid validator definition " + validatorId + "!"); } return (SourceFileStore) child; }

Target:
protected SourceFileStore findSourceFileStoreForValidator(final ValidatorSourceRepositorySotre validatorSourceStore, final String validatorId, final ValidatorDescriptor descriptor) throws FileNotFoundException { final AbstractFileStore child = validatorSourceStore.getChild(descriptor.getClassName()); if (child == null) { throw new FileNotFoundException("Validator class " + descriptor.getClassName() + " not found for validator definition " + validatorId + "!"); } if (!(child instanceof SourceFileStore)) { throw new RuntimeException("Invalid validator definition " + validatorId + "!"); } return (SourceFileStore) child; }
Source:
void doPaint(GC gc, ILineRange visibleLines) { Display display= fCachedTextWidget.getDisplay(); int y= -JFaceTextUtil.getHiddenTopLinePixels(fCachedTextWidget); boolean isWrapActive= fCachedTextWidget.getWordWrap(); int lastLine= end(visibleLines); if (fCachedNumberOfLines < lastLine) { int digits= computeNumberOfDigits(lastLine); if (fCachedNumberOfDigits < digits) { if (updateNumberOfDigits()) { computeIndentations(); layout(true); return; } } } for (int line= visibleLines.getStartLine(); line < lastLine; line++) { int widgetLine= JFaceTextUtil.modelLineToWidgetLine(fCachedTextViewer, line); if (widgetLine == -1) continue; final int offsetAtLine= fCachedTextWidget.getOffsetAtLine(widgetLine); int lineHeight= fCachedTextWidget.getLineHeight(offsetAtLine); paintLine(line, y, lineHeight, gc, display); if (!isWrapActive) { y+= lineHeight; } else { int charCount= fCachedTextWidget.getCharCount(); if (offsetAtLine == charCount) continue; final int offsetEnd= offsetAtLine + fCachedTextWidget.getLine(widgetLine).length(); if (offsetEnd == charCount) continue; y+= fCachedTextWidget.getTextBounds(offsetAtLine, offsetEnd).height; } } }

Target:
void doPaint(GC gc, ILineRange visibleLines) { Display display= fCachedTextWidget.getDisplay(); int y= -JFaceTextUtil.getHiddenTopLinePixels(fCachedTextWidget); boolean isWrapActive= fCachedTextWidget.getWordWrap(); int lastLine= end(visibleLines); for (int line= visibleLines.getStartLine(); line < lastLine; line++) { int widgetLine= JFaceTextUtil.modelLineToWidgetLine(fCachedTextViewer, line); if (widgetLine == -1) continue; final int offsetAtLine= fCachedTextWidget.getOffsetAtLine(widgetLine); int lineHeight= fCachedTextWidget.getLineHeight(offsetAtLine); paintLine(line, y, lineHeight, gc, display); if (!isWrapActive) { y+= lineHeight; } else { int charCount= fCachedTextWidget.getCharCount(); if (offsetAtLine == charCount) continue; final int offsetEnd= offsetAtLine + fCachedTextWidget.getLine(widgetLine).length(); if (offsetEnd == charCount) continue; y+= fCachedTextWidget.getTextBounds(offsetAtLine, offsetEnd).height; } } }
Source:
public void refresh() { try { if (workItem.getCreatedBy() == null) { origLabel.setText("Error: No originator identified."); origLabel.setForeground(Displays.getSystemColor(SWT.COLOR_RED)); } else { User origUser = AtsClientService.get().getUserServiceClient().getOseeUser(workItem.getCreatedBy()); userIconLabel.setImage(FrameworkArtifactImageProvider.getUserImage(Arrays.asList(origUser))); origLabel.setText(workItem.getCreatedBy().getName()); origLabel.setForeground(Displays.getSystemColor(SWT.COLOR_BLACK)); } if (workItem.isCancelled() || workItem.isCompleted()) { origLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); } origLabel.getParent().getParent().layout(); } catch (OseeCoreException ex) { Label errorLabel = editor.getToolkit().createLabel(this, "Error: " + ex.getLocalizedMessage()); errorLabel.setForeground(Displays.getSystemColor(SWT.COLOR_RED)); OseeLog.log(Activator.class, Level.SEVERE, ex); } }

Target:
public void refresh() { try { if (workItem.getCreatedBy() == null) { origLabel.setText("Error: No originator identified."); origLabel.setForeground(Displays.getSystemColor(SWT.COLOR_RED)); } else { User origUser = AtsClientService.get().getUserServiceClient().getOseeUser(workItem.getCreatedBy()); userIconLabel.setImage(FrameworkArtifactImageProvider.getUserImage(Arrays.asList(origUser))); origLabel.setText(workItem.getCreatedBy().getName()); origLabel.setForeground(Displays.getSystemColor(SWT.COLOR_BLACK)); } origLabel.getParent().getParent().layout(); } catch (OseeCoreException ex) { Label errorLabel = editor.getToolkit().createLabel(this, "Error: " + ex.getLocalizedMessage()); errorLabel.setForeground(Displays.getSystemColor(SWT.COLOR_RED)); OseeLog.log(Activator.class, Level.SEVERE, ex); } }
Source:
private String buildConflictingMessage(MergeResult mergeResult) { final StringBuilder messageBuildder = new StringBuilder(); final Integer returnCode; for (String conflictingFile : mergeResult.getConflicts().keySet()) { messageBuildder.append("Auto-merging failed in ").append(conflictingFile).append(EOL); messageBuildder.append("Automatic merge failed; fix conflicts and then commit the result.") .append(conflictingFile).append(EOL); } return messageBuildder.toString(); }

Target:
private String buildConflictingMessage(MergeResult mergeResult) { final StringBuilder messageBuildder = new StringBuilder(); for (String conflictingFile : mergeResult.getConflicts().keySet()) { messageBuildder.append("Auto-merging failed in ").append(conflictingFile).append(EOL); messageBuildder.append("Automatic merge failed; fix conflicts and then commit the result.") .append(conflictingFile).append(EOL); } return messageBuildder.toString(); }
Source:
private String currentDateAndTime() { LocalDateTime rightNow = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.UK); return dateTimeFormatter.format(rightNow).replaceAll("[- .:]", "_"); }

Target:
private String currentDateAndTime() { LocalDateTime rightNow = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.getDefault()); return dateTimeFormatter.format(rightNow).replaceAll("[- .:,]", "_"); }
Source:
public InfiniteIncrementNumberPublisher(final Executor executor) { super(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { private int at = 0; @Override public boolean hasNext() { return true; } @Override public Integer next() { return at++; } }; } }, executor); }

Target:
public InfiniteIncrementNumberPublisher(final Executor executor) { super(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { private int at = 0; @Override public boolean hasNext() { return true; } @Override public Integer next() { return at++; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }, executor); }
Source:
public QueryResponse getBrowsableStudies(@RequestParam("species") String species) throws IllegalOpenCGACredentialsException, IOException { MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); List<VariantStudySummary> uniqueStudies = variantStudySummaryRepository.findBy(); QueryResult<VariantStudySummary> result = new QueryResult<>(); result.setResult(uniqueStudies); result.setNumResults(uniqueStudies.size()); result.setNumTotalResults(uniqueStudies.size()); return setQueryResponse(result); }

Target:
public QueryResponse getBrowsableStudies(@RequestParam("species") String species) throws IllegalOpenCGACredentialsException, IOException { MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); List<VariantStudySummary> uniqueStudies = variantStudySummaryRepository.findBy(); QueryResult<VariantStudySummary> result = Utils.buildQueryResult(uniqueStudies); return setQueryResponse(result); }
Source:
@Override public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { boolean clusterPermitted = clusterSemaphore.tryAcquire(timeout, unit); boolean poolPermitted = false; if (clusterPermitted) { poolPermitted = poolSemaphore.tryAcquire(timeout, unit); } if (poolPermitted) { return true; } else { clusterSemaphore.release(); return false; } }

Target:
@Override public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { boolean clusterPermitted = clusterSemaphore.tryAcquire(timeout, unit); boolean poolPermitted = false; if (clusterPermitted) { try { poolPermitted = poolSemaphore.tryAcquire(timeout, unit); } catch(InterruptedException e) { clusterSemaphore.release(); throw e; } } if (poolPermitted) { return true; } else if (clusterPermitted) { clusterSemaphore.release(); } return false; }
Source:
private void checkDataIntegrity() throws StoreException { byte[] byteArray; if (serEntries.hasArray()) { byteArray = serEntries.array(); } else { serEntries.position(0); byteArray = new byte[serEntries.capacity()]; serEntries.get(byteArray, 0, serEntries.capacity()); } Crc32 crc = new Crc32(); crc.update(byteArray, 0, byteArray.length - CRC_FIELD_LENGTH); ByteBuffer bb = ByteBuffer.wrap(Arrays.copyOfRange(byteArray, byteArray.length - CRC_FIELD_LENGTH, byteArray.length)); if (crc.getValue() != bb.getLong()) { throw new StoreException("IndexSegment : " + indexFile.getAbsolutePath() + " crc check does not match", StoreErrorCodes.Index_Creation_Failure); } }

Target:
private void checkDataIntegrity() throws StoreException { serEntries.position(0); serEntries.limit(serEntries.capacity() - CRC_FIELD_LENGTH); Crc32 crc = new Crc32(); crc.update(serEntries.slice()); serEntries.limit(serEntries.capacity()); if (crc.getValue() != serEntries.getLong(serEntries.capacity() - CRC_FIELD_LENGTH)) { throw new StoreException("IndexSegment : " + indexFile.getAbsolutePath() + " crc check does not match", StoreErrorCodes.Index_Creation_Failure); } }
Source:
public List<RichMember> call(ApiCaller ac, Deserializer parms) throws PerunException { if(parms.contains("vo")) { if(parms.contains("allowedStatuses")) { return ac.getMembersManager().findCompleteRichMembers(ac.getSession(), ac.getVoById(parms.readInt("vo")), parms.readList("attrsNames", String.class), parms.readList("allowedStatuses", String.class), parms.readString("searchString")); } else { boolean onlySponsored = false; if(parms.contains("onlySponsored")) onlySponsored = parms.readBoolean("onlySponsored"); return ac.getMembersManager().findCompleteRichMembers(ac.getSession(), ac.getVoById(parms.readInt("vo")), parms.readList("attrsNames", String.class), parms.readString("searchString"), onlySponsored); } } else { if(parms.contains("allowedStatuses")) { if(parms.contains("group")) { return ac.getMembersManager().findCompleteRichMembers(ac.getSession(), ac.getGroupById(parms.readInt("group")), parms.readList("attrsNames", String.class), parms.readList("allowedStatuses", String.class), parms.readString("searchString"), parms.readBoolean("lookingInParentGroup")); } else { return ac.getMembersManager().findCompleteRichMembers(ac.getSession(), parms.readList("attrsNames", String.class), parms.readList("allowedStatuses", String.class), parms.readString("searchString")); } } else { return ac.getMembersManager().findCompleteRichMembers(ac.getSession(), ac.getGroupById(parms.readInt("group")), parms.readList("attrsNames", String.class), parms.readString("searchString"), parms.readBoolean("lookingInParentGroup")); } } }

Target:
public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getMembersManager().deleteMember(ac.getSession(), ac.getMemberById(parms.readInt("member"))); return null; }
Source:
public void visit( long relationshipId, int typeId, long startNodeId, long endNodeId ) throws RuntimeException { setId( relationshipId ); setType( typeId ); setFirstNode( startNodeId ); setSecondNode( endNodeId ); }

Target:
public void visit( long relationshipId, int typeId, long startNodeId, long endNodeId ) { setId( relationshipId ); initialize( true, NO_ID, startNodeId, endNodeId, typeId, NO_ID, NO_ID, NO_ID, NO_ID, false, false ); }
Source:
public CharSequence apply(Object upstream, Options options) { if (upstream instanceof String) { String address = ((String) upstream); LOG.trace("Trying to resolve a String upstream of {}", address); String resolved = resolver.resolveUpstreamDNS(address).or(address); LOG.trace("Resolved to {}", address, resolved); return resolved; } else if (upstream instanceof UpstreamInfo) { UpstreamInfo upstreamInfo = ((UpstreamInfo) upstream); LOG.trace("Trying to resolve an UpstreamInfo upstream of with upstreamInfo.getResolvedUpstream() = {}, resolver.resolveUpstreamDNS(upstreamInfo.getUpstream()) = {}, upstreamInfo.getUpstream() = {}", upstreamInfo, upstreamInfo .getResolvedUpstream(), resolver.resolveUpstreamDNS(upstreamInfo.getUpstream()), upstreamInfo.getUpstream()); String resolved = upstreamInfo.getResolvedUpstream().or(resolver.resolveUpstreamDNS(upstreamInfo.getUpstream())).or(upstreamInfo.getUpstream()); LOG.trace("Resolved to {}", upstreamInfo, resolved); return resolved; } else { LOG.error("resolveHostname called with invalid context and options {}", upstream, options); throw new IllegalArgumentException(String.format("Don't know how to process upstream %s", upstream.toString())); } }

Target:
public CharSequence apply(Object upstream, Options options) { if (upstream instanceof String) { String address = ((String) upstream); LOG.trace("Trying to resolve a String upstream of {}", address); String resolved = resolver.resolveUpstreamDNS(address).or(address); LOG.trace("Resolved to {}", address, resolved); return resolved; } else if (upstream instanceof UpstreamInfo) { UpstreamInfo upstreamInfo = ((UpstreamInfo) upstream); final Optional<String> maybeResolvedUpstream = resolver.resolveUpstreamDNS(upstreamInfo.getUpstream()); LOG.trace( "Trying to resolve an UpstreamInfo upstream of with upstreamInfo.getResolvedUpstream() = {}, resolver.resolveUpstreamDNS(upstreamInfo.getUpstream()) = {}, upstreamInfo.getUpstream() = {}", upstreamInfo, upstreamInfo.getResolvedUpstream(), maybeResolvedUpstream, upstreamInfo.getUpstream() ); String resolved = upstreamInfo.getResolvedUpstream().or(maybeResolvedUpstream).or(upstreamInfo.getUpstream()); LOG.trace("Resolved to {}", upstreamInfo, resolved); return resolved; } else { LOG.error("resolveHostname called with invalid context and options {}", upstream, options); throw new IllegalArgumentException(String.format("Don't know how to process upstream %s", upstream.toString())); } }
Source:
private void computeAndApplyCharge(final ContainerStartData startData, long endTime, boolean remove) throws IOException { synchronized (startData) { Long quotaTime = new Long(0); if (remove) { quotaTime = containerQuotaTime.remove(startData.getContainerId()); if (endTime - startData.getStartTime() < minRunTime) { endTime = startData.getStartTime() + minRunTime - quotaTime; } } else { quotaTime = containerQuotaTime.get(startData.getContainerId()); } if (quotaTime == null) { LOG.error("No container should reach this point without having a quotaTime"); return; } final Map<String, Long> resourcesMap = new HashMap<>(); long usedMillis = endTime - quotaTime; Resource resource = startData.getAllocatedResource(); for (ResourceInformation entry : resource.getResources()) { resourcesMap.put(entry.getName(), entry.getValue()); } LightWeightRequestHandler quotaSchedulerHandler = new LightWeightRequestHandler(YARNOperationType.OTHER) { @Override public Object performTask() throws IOException { connector.beginTransaction(); connector.writeLock(); computeAndApplyChargeInt(startData.getContainerId(), resourcesMap, usedMillis); connector.commit(); return null; } }; quotaSchedulerHandler.handle(); if (!remove) { containerQuotaTime.put(startData.getContainerId(), endTime); } } }

Target:
private void computeAndApplyCharge(final ContainerStartData startData, long endTime, boolean remove) throws IOException { Long quotaTime = new Long(0); if (remove) { quotaTime = containerQuotaTime.remove(startData.getContainerId()); if (endTime - startData.getStartTime() < minRunTime) { endTime = startData.getStartTime() + minRunTime - quotaTime; } } else { quotaTime = containerQuotaTime.get(startData.getContainerId()); } if (quotaTime == null) { LOG.error("No container should reach this point without having a quotaTime"); return; } final Map<String, Long> resourcesMap = new HashMap<>(); long usedMillis = endTime - quotaTime; Resource resource = startData.getAllocatedResource(); for (ResourceInformation entry : resource.getResources()) { resourcesMap.put(entry.getName(), entry.getValue()); } LightWeightRequestHandler quotaSchedulerHandler = new LightWeightRequestHandler(YARNOperationType.OTHER) { @Override public Object performTask() throws IOException { connector.beginTransaction(); connector.writeLock(); computeAndApplyChargeInt(startData.getContainerId(), resourcesMap, usedMillis); connector.commit(); return null; } }; quotaSchedulerHandler.handle(); if (!remove) { containerQuotaTime.put(startData.getContainerId(), endTime); } }