auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static <O extends JavaSource<O>> int getBasicArrayDimension(String name) { int count = 0; if (name != null) { for (char c : name.toCharArray()) { if (c == '[') { count++; } } } return count; }

Target:
public static int getBasicArrayDimension(String name) { int count = 0; if (name != null) { for (char c : name.toCharArray()) { if (c == '[') { count++; } } } return count; }
Source:
public String toString() { return "AffinityEnforcerThreadInterceptor{" + "type='" + group + '\'' + ", cores=" + cores + '}'; }

Target:
public String toString() { return "ThreadAffinityController{" + "group='" + group + '\'' + ", cores=" + cores + '}'; }
Source:
private boolean validateAntHome() { ClasspathModel model = getModel(); IClasspathEntry userEntry = model.getUserEntry(); for (IClasspathEntry entrie : userEntry.getEntries()) { ClasspathEntry entry = (ClasspathEntry) entrie; IRuntimeClasspathEntry runtimeEntry = entry.getDelegate(); if (runtimeEntry instanceof AntHomeClasspathEntry) { try { ((AntHomeClasspathEntry) runtimeEntry).resolveAntHome(); } catch (CoreException ce) { setErrorMessage(ce.getStatus().getMessage()); return false; } break; } } return true; }

Target:
private boolean validateAntHome() { ClasspathModel model = getModel(); IClasspathEntry userEntry = model.getUserEntry(); for (IClasspathEntry entry : userEntry.getEntries()) { IRuntimeClasspathEntry runtimeEntry = ((ClasspathEntry) entry).getDelegate(); if (runtimeEntry instanceof AntHomeClasspathEntry) { try { ((AntHomeClasspathEntry) runtimeEntry).resolveAntHome(); } catch (CoreException ce) { setErrorMessage(ce.getStatus().getMessage()); return false; } break; } } return true; }
Source:
public void setTopics(String[] topics) { ArrayList<String> temp = new ArrayList<>(); for (String topic: Arrays.asList(topics)) { if (topic != null && topic.length() != 0) { temp.add(topic); } } temp.toArray(this.topics); }

Target:
public void setTopics(String[] topics) { List<String> temp = new ArrayList<>(); for (String topic: topics) { if (topic != null && topic.length() != 0) { temp.add(topic); } } this.topics = temp.toArray(new String[temp.size()]); }
Source:
public static PageViewAvroRecord buildPageViewRecord(PageView pageView) { PageViewAvroRecord record = new PageViewAvroRecord(); record.put(0, pageView.userId); record.put(1, pageView.country); record.put(2, pageView.pageId); return record; }

Target:
public static PageViewAvroRecord buildPageViewRecord(PageView pageView) { PageViewAvroRecord record = new PageViewAvroRecord(); record.userId = pageView.userId; record.country = pageView.country; record.pageId = pageView.pageId; return record; }
Source:
public MessageChannel bindDynamicPubSubProducer(String name) { MessageChannel channel = this.directChannelProvider.lookupSharedChannel(name); if (channel == null) { channel = this.directChannelProvider.createAndRegisterChannel(name); bindPubSubProducer(name, channel); } return channel; }

Target:
public synchronized MessageChannel bindDynamicPubSubProducer(String name) { MessageChannel channel = this.directChannelProvider.lookupSharedChannel(name); if (channel == null) { channel = this.directChannelProvider.createAndRegisterChannel(name); bindPubSubProducer(name, channel); } return channel; }
Source:
public QueryRequest process(Source source, QueryRequest input) throws PluginExecutionException, StopProcessingException { String methodName = "process"; LOGGER.trace(ENTERING, methodName); QueryRequest newQueryRequest = input; if (input != null) { Query query = input.getQuery(); if (query != null) { Subject subject = getSubject(input); HashMap<String, Set<String>> securityMap = new HashMap<>(); for (Map.Entry<String, List<String>> attributeMapping : attributeMap.entrySet()) { securityMap.put(attributeMapping.getKey(), new HashSet<>(attributeMapping.getValue())); } Attribute attr = new AttributeImpl(Metacard.SECURITY, securityMap); boolean subjectCanViewInvalidData = securityMap.isEmpty() ? false : checkPermissions(attr, subject, CollectionPermission.READ_ACTION); List<Filter> filters = new ArrayList<>(); if (!subjectCanViewInvalidData || !showErrors) { filters.add(filterBuilder.attribute(Validation.VALIDATION_ERRORS).is().empty()); } if (!subjectCanViewInvalidData || !showWarnings) { filters.add(filterBuilder.attribute(Validation.VALIDATION_WARNINGS).is().empty()); } if (!filters.isEmpty()) { QueryImpl newQuery = new QueryImpl( filterBuilder.allOf(filterBuilder.allOf(filters), query), query.getStartIndex(), query.getPageSize(), query.getSortBy(), query.requestsTotalResultsCount(), query.getTimeoutMillis()); newQueryRequest = new QueryRequestImpl( newQuery, input.isEnterprise(), input.getSourceIds(), input.getProperties()); } } } LOGGER.trace(EXITING, methodName); return newQueryRequest; }

Target:
public QueryRequest process(Source source, QueryRequest input) throws StopProcessingException { String methodName = "process"; LOGGER.trace(ENTERING, methodName); QueryRequest newQueryRequest = input; if (input != null) { Query query = input.getQuery(); if (query != null) { boolean subjectCanViewInvalidData = canViewInvalidData(input); List<Filter> filters = new ArrayList<>(); if (!subjectCanViewInvalidData || !showErrors) { filters.add(filterBuilder.attribute(Validation.VALIDATION_ERRORS).is().empty()); } if (!subjectCanViewInvalidData || !showWarnings) { filters.add(filterBuilder.attribute(Validation.VALIDATION_WARNINGS).is().empty()); } if (!filters.isEmpty()) { QueryImpl newQuery = new QueryImpl( filterBuilder.allOf(filterBuilder.allOf(filters), query), query.getStartIndex(), query.getPageSize(), query.getSortBy(), query.requestsTotalResultsCount(), query.getTimeoutMillis()); newQueryRequest = new QueryRequestImpl( newQuery, input.isEnterprise(), input.getSourceIds(), input.getProperties()); } } } LOGGER.trace(EXITING, methodName); return newQueryRequest; }
Source:
public static ValidationResult setAndValidateCpuProfile(VmBase vmBase, Guid userId) { if (vmBase.getCpuProfileId() == null) { return assignFirstCpuProfile(vmBase, userId); } CpuProfileValidator validator = new CpuProfileValidator(vmBase.getCpuProfileId()); ValidationResult result = validator.isParentEntityValid(vmBase.getClusterId()); if (!result.isValid()) { return result; } if (!checkPermissions(vmBase.getCpuProfileId(), userId)) { return new ValidationResult(EngineMessage.ACTION_TYPE_NO_PERMISSION_TO_ASSIGN_CPU_PROFILE, String.format("$cpuProfileId %s", vmBase.getCpuProfileId()), String.format("$cpuProfileName %s", validator.getProfile().getName())); } return ValidationResult.VALID; }

Target:
public static ValidationResult setAndValidateCpuProfile(VmBase vmBase, Guid userId) { if (vmBase.getCpuProfileId() == null) { return assignFirstCpuProfile(vmBase, userId); } CpuProfileValidator validator = new CpuProfileValidator(vmBase.getCpuProfileId()); ValidationResult result = validator.isParentEntityValid(vmBase.getClusterId()); if (!result.isValid()) { return result; } if (!isProfilePermitted(vmBase.getCpuProfileId(), userId)) { return new ValidationResult(EngineMessage.ACTION_TYPE_NO_PERMISSION_TO_ASSIGN_CPU_PROFILE, String.format("$cpuProfileId %s", vmBase.getCpuProfileId()), String.format("$cpuProfileName %s", validator.getProfile().getName())); } return ValidationResult.VALID; }
Source:
public void run() { while (true) { LOG.info("Sync loop"); try { msgCountDown.await(); } catch (final InterruptedException e) { throw new RuntimeException(e); } for (final String slaveId : slaveIds) { LOG.log(Level.INFO, "Sending a message to {0}", slaveId); aggregationMaster.send(RemoteEMDriver.AGGREGATION_CLIENT_ID, slaveId, codec.encode(MSG_FROM_DRIVER)); } msgCountDown = new CountDownLatch(RemoteEMDriver.EVAL_NUM); } }

Target:
public void run() { while (true) { try { msgCountDown.await(); } catch (final InterruptedException e) { throw new RuntimeException(e); } for (final String slaveId : workerIds) { LOG.log(Level.INFO, "Sending a message to {0}", slaveId); aggregationMaster.send(RemoteEMDriver.AGGREGATION_CLIENT_ID, slaveId, codec.encode(MSG_FROM_DRIVER)); } msgCountDown = new CountDownLatch(RemoteEMDriver.EVAL_NUM); } }
Source:
public Resource filter(ApiRequest request, Object original, Resource converted) { IdFormatter idFormatter = ApiContext.getContext().getIdFormatter(); Identity identity = null; if (original instanceof Account) { Account account = (Account) original; if (AccountConstants.PROJECT_KIND.equalsIgnoreCase(account.getKind())) { return converted; } if (account.getExternalId() != null && account.getExternalIdType() != null) { identity = identityManager.getIdentity( new Identity(account.getExternalIdType(), account.getExternalId()).getId()); } else { if (!AccountConstants.PROJECT_KIND.equalsIgnoreCase(account.getKind())) { identity = identityManager.getIdentity( new Identity(ProjectConstants.RANCHER_ID, String.valueOf(account.getId())).getId()); } } } if (identity != null) { if (idFormatter != null) { converted.getFields().put("identity", idFormatter.formatId("identity", identity.getId())); } else { converted.getFields().put("identity", identity.getId()); } } return converted; }

Target:
public Resource filter(ApiRequest request, Object original, Resource converted) { IdFormatter idFormatter = ApiContext.getContext().getIdFormatter(); Identity identity = null; if (original instanceof Account) { Account account = (Account) original; if (AccountConstants.PROJECT_KIND.equalsIgnoreCase(account.getKind())) { return converted; } if (account.getExternalId() != null && account.getExternalIdType() != null) { identity = new Identity(account.getExternalIdType(), account.getExternalId()); } else { if (!AccountConstants.PROJECT_KIND.equalsIgnoreCase(account.getKind())) { identity = new Identity(ProjectConstants.RANCHER_ID, String.valueOf(account.getId())); } } } if (identity != null) { if (idFormatter != null) { converted.getFields().put("identity", idFormatter.formatId("identity", identity.getId())); } else { converted.getFields().put("identity", identity.getId()); } } return converted; }
Source:
private void startConsumer() throws ShutdownSignalException, IOException { connection = getConnection(); if (channel == null || !channel.isOpen()) { channel = connection.createChannel(); log.debug("Channel is not open. Creating a new channel for inbound " + inboundName); } if (queueingConsumer == null) { workerState = STATE_STOPPED; return; } while (isActive()) { RabbitMQMessage message; try { if (!channel.isOpen()) { channel = queueingConsumer.getChannel(); } message = getConsumerDelivery(queueingConsumer); } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { log.warn("Exception occurred while consuming the message", e); continue; } if (message != null) { idle = false; RabbitMQAckStates ackState = RabbitMQAckStates.REJECT_AND_REQUEUE; boolean mediationError = false; try { ackState = injectHandler.invokeAndReturnAckState(message, inboundName); } catch (Exception e) { ackState = RabbitMQAckStates.REJECT_AND_REQUEUE; mediationError = true; log.error("Error while mediating message", e); } finally { if (!autoAck) { if (ackState == RabbitMQAckStates.ACK) { try { channel.basicAck(message.getDeliveryTag(), false); } catch (IOException e) { log.error("Error while sending an ack to the message", e); } } else { try { channel.basicReject(message.getDeliveryTag(), ackState == RabbitMQAckStates.REJECT_AND_REQUEUE); } catch (IOException e) { log.error("Error while rejecting the unacked message", e); } } } } if (mediationError) { try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } else { idle = true; } } }

Target:
private void startConsumer() throws ShutdownSignalException, IOException { connection = getConnection(); if (channel == null || !channel.isOpen()) { channel = connection.createChannel(); log.debug("Channel is not open. Creating a new channel for inbound " + inboundName); } if (queueingConsumer == null) { workerState = STATE_STOPPED; return; } while (isActive()) { RabbitMQMessage message; try { if (!channel.isOpen()) { channel = queueingConsumer.getChannel(); } message = getConsumerDelivery(queueingConsumer); } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { log.warn("Exception occurred while consuming the message", e); continue; } if (message != null) { idle = false; RabbitMQAckStates ackState = RabbitMQAckStates.REJECT_AND_REQUEUE; States states; boolean mediationError; try { states = injectHandler.invokeAndReturnAckState(message, inboundName); ackState = states.ackState; mediationError = states.mediationError; } finally { if (!autoAck) { if (ackState == RabbitMQAckStates.ACK) { try { channel.basicAck(message.getDeliveryTag(), false); } catch (IOException e) { log.error("Error while acknowledging the message", e); } } else { try { channel.basicReject(message.getDeliveryTag(), ackState == RabbitMQAckStates.REJECT_AND_REQUEUE); } catch (IOException e) { log.error("Error while rejecting the unacked message", e); } } } } if (mediationError) { try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } else { idle = true; } } }
Source:
public Void call() throws Exception { try (ScmClient scmClient = parent.createScmClient()) { if (isNullOrEmpty(factor) && isNullOrEmpty(state)) { System.out.println("No filter. List all."); scmClient.listPipelines().forEach(System.out::println); } else { scmClient.listPipelines().stream() .filter(p -> ((isNullOrEmpty(factor) || (p.getFactor().toString().compareToIgnoreCase(factor) == 0)) && (isNullOrEmpty(state) || (p.getPipelineState().toString().compareToIgnoreCase(state) == 0)))) .forEach(System.out::println); } return null; } }

Target:
public Void call() throws Exception { try (ScmClient scmClient = parent.createScmClient()) { if (isNullOrEmpty(factor) && isNullOrEmpty(state)) { scmClient.listPipelines().forEach(System.out::println); } else { scmClient.listPipelines().stream() .filter(p -> ((isNullOrEmpty(factor) || (p.getFactor().toString().compareToIgnoreCase(factor) == 0)) && (isNullOrEmpty(state) || (p.getPipelineState().toString().compareToIgnoreCase(state) == 0)))) .forEach(System.out::println); } return null; } }
Source:
public static Map<storage_domains, Integer> getSpaceRequirementsForStorageDomains(Map<DiskImage, storage_domains> imageToDomainMap) { Map<storage_domains, Integer> map = new HashMap<storage_domains, Integer>(); if (!imageToDomainMap.isEmpty()) { for(Map.Entry<DiskImage, storage_domains> entry : imageToDomainMap.entrySet()) { storage_domains domain = entry.getValue(); int size = (int) entry.getKey().getActualDiskWithSnapshotsSize(); if (map.containsKey(domain)) { map.put(domain, map.get(domain) + size); } else { map.put(domain, size); } } } return map; }

Target:
public static Map<storage_domains, Long> getSpaceRequirementsForStorageDomains(Map<DiskImage, storage_domains> imageToDomainMap) { Map<storage_domains, Long> map = new HashMap<storage_domains, Long>(); for(Map.Entry<DiskImage, storage_domains> entry : imageToDomainMap.entrySet()) { storage_domains domain = entry.getValue(); long size = Math.round(entry.getKey().getActualDiskWithSnapshotsSize()); if (map.containsKey(domain)) { map.put(domain, map.get(domain) + size); } else { map.put(domain, size); } } return map; }
Source:
public final void onInit() throws Exception { super.onInit(); if (this.executor != null) { Assert.state(getDispatcher().getHandlerCount() == 0, "When providing an Executor, you cannot subscribe() until the channel " + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition"); if (!(this.executor instanceof ErrorHandlingTaskExecutor)) { if (this.errorHandler == null) { this.errorHandler = new MessagePublishingErrorHandler( new BeanFactoryChannelResolver(this.getBeanFactory())); } this.executor = new ErrorHandlingTaskExecutor(this.executor, this.errorHandler); } this.dispatcher = new BroadcastingDispatcher(this.executor); getDispatcher().setIgnoreFailures(this.ignoreFailures); getDispatcher().setApplySequence(this.applySequence); getDispatcher().setMinSubscribers(this.minSubscribers); } else if (this.errorHandler != null) { logger.warn("When 'executor' is not provided the 'errorHandler' is ignored and " + "exceptions are thrown directly within the sending Thread"); } if (this.maxSubscribers == null) { Integer maxSubscribers = getIntegrationProperty(IntegrationProperties.CHANNELS_MAX_BROADCAST_SUBSCRIBERS, Integer.class); this.setMaxSubscribers(maxSubscribers); } getDispatcher().setBeanFactory(this.getBeanFactory()); getDispatcher().setMessageHandlingTaskDecorator(task -> { if (PublishSubscribeChannel.this.executorInterceptorsSize > 0) { return new MessageHandlingTask(task); } else { return task; } }); }

Target:
public final void onInit() throws Exception { super.onInit(); if (this.executor != null) { Assert.state(getDispatcher().getHandlerCount() == 0, "When providing an Executor, you cannot subscribe() until the channel " + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition"); if (!(this.executor instanceof ErrorHandlingTaskExecutor)) { if (this.errorHandler == null) { this.errorHandler = new MessagePublishingErrorHandler( new BeanFactoryChannelResolver(this.getBeanFactory())); } this.executor = new ErrorHandlingTaskExecutor(this.executor, this.errorHandler); } this.dispatcher = new BroadcastingDispatcher(this.executor); getDispatcher().setIgnoreFailures(this.ignoreFailures); getDispatcher().setApplySequence(this.applySequence); getDispatcher().setMinSubscribers(this.minSubscribers); } else if (this.errorHandler != null) { if (this.logger.isWarnEnabled()) { this.logger.warn("The 'errorHandler' is ignored for the '" + getComponentName() + "' (an 'executor' is not provided) and exceptions will be thrown " + "directly within the sending Thread"); } } if (this.maxSubscribers == null) { Integer maxSubscribers = getIntegrationProperty(IntegrationProperties.CHANNELS_MAX_BROADCAST_SUBSCRIBERS, Integer.class); this.setMaxSubscribers(maxSubscribers); } getDispatcher().setBeanFactory(this.getBeanFactory()); getDispatcher().setMessageHandlingTaskDecorator(task -> { if (PublishSubscribeChannel.this.executorInterceptorsSize > 0) { return new MessageHandlingTask(task); } else { return task; } }); }
Source:
private ArrayList<DataChangedEvent> getReuseChangedEvents( Set<IComponentNamePO> reuseChangedCompNames) { ArrayList<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : reuseChangedCompNames) { events.add(new DataChangedEvent(compName, DataState.ReuseChanged, UpdateState.all)); } return events; }

Target:
private List<DataChangedEvent> getReuseChangedEvents( Set<IComponentNamePO> reuseChangedCompNames) { List<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : reuseChangedCompNames) { events.add(new DataChangedEvent(compName, DataState.ReuseChanged, UpdateState.all)); } return events; }
Source:
public Iterable<Directive> process(final XML xml) throws IOException { final String rebase = this.profile.text( "/p/entry[@key='merge']/entry[@key='rebase']", "false" ); if ("true".equals(rebase)) { final Issue.Smart issue = new TalkIssues(this.github, xml).get(); issue.close(); issue.comments().post("Closed manually because of rebase mode"); } return new Directives(); }

Target:
public Iterable<Directive> process(final XML xml) throws IOException { final String rebase = this.profile.text( "/p/entry[@key='merge']/entry[@key='rebase']", "false" ); if ("true".equals(rebase)) { final Issue.Smart issue = new TalkIssues(this.github, xml).get(); issue.close(); issue.comments().post( ClosePullRequest.PHRASES.getString( "ClosePullRequest.explanation" ) ); } return new Directives(); }
Source:
protected Vector<URL> searchResourcesInBundles(String name) { Vector<URL> urlList = new Vector<URL>(); for (Bundle b : m_bundles) { try { Enumeration resources = b.getResources(name); while (resources != null && resources.hasMoreElements()) { URL url = (URL) resources.nextElement(); urlList.add(url); } } catch (Exception e) { } } return urlList; }

Target:
protected Vector<URL> searchResourcesInBundles(String name) { Vector<URL> urlList = new Vector<URL>(); for (Bundle b : getBundles()) { try { Enumeration resources = b.getResources(name); while (resources != null && resources.hasMoreElements()) { URL url = (URL) resources.nextElement(); urlList.add(url); } } catch (Exception e) { } } return urlList; }
Source:
public void refreshItem(T item) { Objects.requireNonNull(item, NULL_ITEM_ERROR_MESSAGE); getItems().filter(i -> equals(item, i)).findFirst() .ifPresent(i -> dataProviderSupplier.get().refreshItem(i)); }

Target:
public void refreshItem(T item) { Objects.requireNonNull(item, NULL_ITEM_ERROR_MESSAGE); getItems() .filter(i -> equals(item, i)) .findFirst() .ifPresent(i -> dataProviderSupplier.get().refreshItem(item)); }
Source:
public Set<ImmutableBitSet> getUniqueKeys(TableScan rel, RelMetadataQuery mq, boolean ignoreNulls) { final List<ImmutableBitSet> keys = rel.getTable().getKeys(); if (keys.isEmpty()) { return null; } for (ImmutableBitSet key : keys) { assert rel.getTable().isKey(key); } return ImmutableSet.copyOf(keys); }

Target:
public Set<ImmutableBitSet> getUniqueKeys(TableScan rel, RelMetadataQuery mq, boolean ignoreNulls) { final List<ImmutableBitSet> keys = rel.getTable().getKeys(); for (ImmutableBitSet key : keys) { assert rel.getTable().isKey(key); } return ImmutableSet.copyOf(keys); }
Source:
private void setUserName() { View navHeaderView = navigationView.getHeaderView(0); TextView username = navHeaderView.findViewById(R.id.username); AccountManager accountManager = AccountManager.get(this); Account[] allAccounts = accountManager.getAccountsByType(BuildConfig.ACCOUNT_TYPE); if (allAccounts.length != 0) { username.setText(allAccounts[0].name); } ImageView userIcon = navHeaderView.findViewById(R.id.user_icon); userIcon.setOnClickListener(v -> { drawerLayout.closeDrawer(navigationView); AchievementsActivity.startYourself(NavigationBaseActivity.this); }); TextView userName = navHeaderView.findViewById(R.id.username); userName.setOnClickListener(v -> { drawerLayout.closeDrawer(navigationView); AchievementsActivity.startYourself(NavigationBaseActivity.this); }); }

Target:
private void setUserName() { View navHeaderView = navigationView.getHeaderView(0); TextView username = navHeaderView.findViewById(R.id.username); AccountManager accountManager = AccountManager.get(this); Account[] allAccounts = accountManager.getAccountsByType(BuildConfig.ACCOUNT_TYPE); if (allAccounts.length != 0) { username.setText(allAccounts[0].name); } ImageView userIcon = navHeaderView.findViewById(R.id.user_icon); makeClickable(userIcon, NavigationBaseActivity.this, AchievementsActivity.class); TextView userName = navHeaderView.findViewById(R.id.username); makeClickable(userName, NavigationBaseActivity.this, AchievementsActivity.class); }
Source:
void publish(StatsWrapper statsWrapper) throws IOException { if (!statsOutputFile.exists()) { statsOutputFile.createNewFile(); } OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(statsOutputFile)); DatumWriter<StatsWrapper> statsWrapperDatumWriter = new SpecificDatumWriter<StatsWrapper>(StatsWrapper.class); JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(StatsWrapper.getClassSchema(), outputStream, true); try { statsWrapperDatumWriter.write(statsWrapper, jsonEncoder); jsonEncoder.flush(); outputStream.flush(); } finally { outputStream.close(); } }

Target:
void publish(StatsWrapper statsWrapper) throws IOException { File tempFile = new File(statsOutputFile.getAbsolutePath() + ".tmp"); if (tempFile.createNewFile()) { OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile)); DatumWriter<StatsWrapper> statsWrapperDatumWriter = new SpecificDatumWriter<StatsWrapper>(StatsWrapper.class); JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(StatsWrapper.getClassSchema(), outputStream, true); try { statsWrapperDatumWriter.write(statsWrapper, jsonEncoder); jsonEncoder.flush(); outputStream.flush(); } finally { outputStream.close(); } if (!tempFile.renameTo(statsOutputFile)) { throw new IOException( "Failed to rename " + tempFile.getAbsolutePath() + " to " + statsOutputFile.getAbsolutePath()); } } else { throw new IOException("Temporary file creation failed when publishing stats " + tempFile.getAbsolutePath()); } }
Source:
public QueueConfiguration getQueueConfiguration() { return new QueueConfiguration(name) .setAddress(address) .setId(id) .setRoutingType(routingType) .setFilterString(filter == null ? null : filter.getFilterString()) .setDurable(isDurable()) .setUser(user) .setMaxConsumers(maxConsumers) .setExclusive(exclusive) .setGroupRebalance(groupRebalance) .setGroupBuckets(groupBuckets) .setGroupFirstKey(groupFirstKey) .setLastValue(false) .setLastValue(null) .setNonDestructive(nonDestructive) .setPurgeOnNoConsumers(purgeOnNoConsumers) .setConsumersBeforeDispatch(consumersBeforeDispatch) .setDelayBeforeDispatch(delayBeforeDispatch) .setAutoDelete(autoDelete) .setAutoDeleteDelay(autoDeleteDelay) .setAutoDeleteMessageCount(autoDeleteMessageCount) .setRingSize(ringSize) .setConfigurationManaged(configurationManaged) .setTemporary(temporary) .setInternal(internalQueue) .setTransient(refCountForConsumers instanceof TransientQueueManagerImpl) .setAutoCreated(autoCreated); }

Target:
public QueueConfiguration getQueueConfiguration() { return new QueueConfiguration(name) .setAddress(address) .setId(id) .setRoutingType(routingType) .setFilterString(filter == null ? null : filter.getFilterString()) .setDurable(isDurable()) .setUser(user) .setMaxConsumers(maxConsumers) .setExclusive(exclusive) .setGroupRebalance(groupRebalance) .setGroupBuckets(groupBuckets) .setGroupFirstKey(groupFirstKey) .setLastValue(false) .setLastValueKey((String) null) .setNonDestructive(nonDestructive) .setPurgeOnNoConsumers(purgeOnNoConsumers) .setConsumersBeforeDispatch(consumersBeforeDispatch) .setDelayBeforeDispatch(delayBeforeDispatch) .setAutoDelete(autoDelete) .setAutoDeleteDelay(autoDeleteDelay) .setAutoDeleteMessageCount(autoDeleteMessageCount) .setRingSize(ringSize) .setConfigurationManaged(configurationManaged) .setTemporary(temporary) .setInternal(internalQueue) .setTransient(refCountForConsumers instanceof TransientQueueManagerImpl) .setAutoCreated(autoCreated); }
Source:
public PreparedOperationWithReactiveStream<Cursor> prepare() { Checks.checkNotNull(query, "Please specify query"); if (getResolver == null) { getResolver = DefaultGetResolver.INSTANCE; } return new PreparedGetCursor( storIOContentProvider, getResolver, query ); }

Target:
public PreparedOperationWithReactiveStream<Cursor> prepare() { checkNotNull(query, "Please specify query"); if (getResolver == null) { getResolver = DefaultGetResolver.INSTANCE; } return new PreparedGetCursor( storIOContentProvider, getResolver, query ); }
Source:
public void setup() throws TmfTraceException { fTrace = new TmfXmlTraceStubNs(); fTrace.initTrace(null, COUNTER_FILE, ITmfEvent.class); fTrace.addEventAspect(new TmfContentFieldAspect("aspect")); fTrace.addEventAspect(new CounterAspect("counter", "counter")); fTrace.addEventAspect(new CounterAspect("counter", "counter", TmfCpuAspect.class)); fTrace.addEventAspect(new CounterAspect("counter", "counter", TmfCpuAspect.class) { @Override public boolean isCumulative() { return true; } }); assertEquals(8, Iterables.size(fTrace.getEventAspects())); if (fTrace != null) { fStateProvider = CounterStateProvider.create(fTrace); } IStateHistoryBackend backend = StateHistoryBackendFactory.createInMemoryBackend("CounterStateSystem", 0); fSsb = StateSystemFactory.newStateSystem(backend); fStateProvider.assignTargetStateSystem(fSsb); }

Target:
public void setup() throws TmfTraceException { TmfXmlTraceStubNs trace = new TmfXmlTraceStubNs(); trace.initTrace(null, COUNTER_FILE, ITmfEvent.class); trace.addEventAspect(new TmfContentFieldAspect("aspect")); trace.addEventAspect(new CounterAspect("counter", "counter")); trace.addEventAspect(new CounterAspect("counter", "counter", TmfCpuAspect.class)); trace.addEventAspect(new CounterAspect("counter", "counter", TmfCpuAspect.class) { @Override public boolean isCumulative() { return true; } }); assertEquals(8, Iterables.size(trace.getEventAspects())); fStateProvider = CounterStateProvider.create(trace); IStateHistoryBackend backend = StateHistoryBackendFactory.createInMemoryBackend("CounterStateSystem", 0); fSsb = StateSystemFactory.newStateSystem(backend); fStateProvider.assignTargetStateSystem(fSsb); fTrace = trace; }
Source:
private HttpClient getDeleteHttpClient() { return new HttpClient() { @Override public CompletionStage<HttpResponse> execute(final HttpRequest httpRequest) { if (httpRequest.getUrl().contains("version=5")) { return CompletableFuture.completedFuture(HttpResponse.of(409, "{\n" + " \"statusCode\" : 409,\n" + " \"message\" : \"Version mismatch. Concurrent modification.\",\n" + " \"errors\" : [ {\n" + " \"code\" : \"ConcurrentModification\",\n" + " \"message\" : \"Version mismatch. Concurrent modification.\",\n" + " \"currentVersion\" : 7\n" + " } ]\n" + "}")); } else if (httpRequest.getUrl().contains("version=7")) { return CompletableFuture.completedFuture(HttpResponse.of(200, "{\"id\": \"some-id\", \"version\": 7}")); } else { throw new IllegalArgumentException("unexcpected input"); } } @Override public void close() { } }; }

Target:
private HttpClient getDeleteHttpClient() { return new HttpClient() { @Override public CompletionStage<HttpResponse> execute(final HttpRequest httpRequest) { if (httpRequest.getUrl().contains("version=5")) { return CompletableFuture.completedFuture(HttpResponse.of(409, "{\n" + " \"statusCode\" : 409,\n" + " \"message\" : \"Version mismatch. Concurrent modification.\",\n" + " \"errors\" : [ {\n" + " \"code\" : \"ConcurrentModification\",\n" + " \"message\" : \"Version mismatch. Concurrent modification.\",\n" + " \"currentVersion\" : 7\n" + " } ]\n" + "}")); } else if (httpRequest.getUrl().contains("version=7")) { return CompletableFuture.completedFuture(HttpResponse.of(200, "{\"id\": \"some-id\", \"version\": 7}")); } else { throw new IllegalArgumentException("unexpected input"); } } @Override public void close() { } }; }
Source:
public String locateContainer(String alias, List<? extends KieContainerInstance> containerInstances) { if (containerId != null) { logger.debug("Container id has already been found for case and is {}", caseId, containerId); return containerId; } logger.debug("Searching for container id for case id and alias {}", caseId, alias); EntityManager em = EntityManagerFactoryManager.get().getOrCreate("org.jbpm.domain").createEntityManager(); try { containerId = (String)em.createQuery(CONTAINER_ID_QUERY) .setParameter("caseId", caseId) .getSingleResult(); logger.debug("Found container id '{}' for case id {}", containerId, caseId); return containerId; } catch (NoResultException | NonUniqueResultException e) { throw new IllegalArgumentException("Case with id " + caseId + " not found"); } finally { em.close(); } }

Target:
public String locateContainer(String alias, List<? extends KieContainerInstance> containerInstances) { if (containerId != null) { logger.debug("Container id has already been found for case and is {}", caseId, containerId); return containerId; } logger.debug("Searching for container id for case id and alias {}", caseId, alias); EntityManager em = EntityManagerFactoryManager.get().getOrCreate(KieServerConstants.KIE_SERVER_PERSISTENCE_UNIT_NAME).createEntityManager(); try { containerId = (String)em.createQuery(CONTAINER_ID_QUERY) .setParameter("caseId", caseId) .getSingleResult(); logger.debug("Found container id '{}' for case id {}", containerId, caseId); return containerId; } catch (NoResultException | NonUniqueResultException e) { throw new IllegalArgumentException("Case with id " + caseId + " not found"); } finally { em.close(); } }
Source:
public void onReceiveComplete(Delivery delivery) { Message responseMessage; try { responseMessage = Util.readMessageFromDelivery(this.receiveLink, delivery); delivery.disposition(Accepted.getInstance()); delivery.settle(); } catch (Exception e) { TRACE_LOGGER.warn("Reading message from delivery failed with unexpected exception.", e); delivery.disposition(Released.getInstance()); delivery.settle(); return; } final Message finalResponseMessage = responseMessage; try { MessagingFactory.INTERNAL_THREAD_POOL.submit(() -> { String requestMessageId = (String) finalResponseMessage.getCorrelationId(); if (requestMessageId != null) { TRACE_LOGGER.debug("RequestRespnseLink received response for request with id :{}", requestMessageId); this.parent.completeRequestWithResponse(requestMessageId, finalResponseMessage); } else { TRACE_LOGGER.warn("RequestRespnseLink received a message with null correlationId"); } }); } catch (RejectedExecutionException | NullPointerException e) { TRACE_LOGGER.error("RequestRespnseLink error message:" + e.getMessage()); } }

Target:
public void onReceiveComplete(Delivery delivery) { Message responseMessage; try { responseMessage = Util.readMessageFromDelivery(this.receiveLink, delivery); delivery.disposition(Accepted.getInstance()); delivery.settle(); } catch (Exception e) { TRACE_LOGGER.warn("Reading message from delivery failed with unexpected exception.", e); delivery.disposition(Released.getInstance()); delivery.settle(); return; } final Message finalResponseMessage = responseMessage; MessagingFactory.INTERNAL_THREAD_POOL.submit(() -> { String requestMessageId = (String) finalResponseMessage.getCorrelationId(); if (requestMessageId != null) { TRACE_LOGGER.debug("RequestRespnseLink received response for request with id :{}", requestMessageId); this.parent.completeRequestWithResponse(requestMessageId, finalResponseMessage); } else { TRACE_LOGGER.warn("RequestRespnseLink received a message with null correlationId"); } }); }
Source:
public static BatteryObject getMjBattery (Object o) { BatteryField f = getMjBattery (o.getClass()); if (f != null) { if (f.kind == BatteryKind.Value) { BatteryObject obj = new BatteryObject(); obj.o = o; obj.f = f; return obj; } else { try { return getMjBattery(f.field.get(o)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } return null; }

Target:
public static BatteryObject getMjBattery (Object o) { BatteryField f = getMjBattery (o.getClass()); if (f == null) { return null; } else if (f.kind == BatteryKind.Value) { BatteryObject obj = new BatteryObject(); obj.o = o; obj.f = f; return obj; } else { try { return getMjBattery(f.field.get(o)); } catch (IllegalArgumentException e) { e.printStackTrace(); return null; } catch (IllegalAccessException e) { e.printStackTrace(); return null; } } }
Source:
static int getUnusedByte(final byte[] array) { final byte[] usage = new byte[256]; for (final byte b : array) { usage[0xFF & b] = 1; } for (int i = 0; i < 256; i++) { if (usage[i] == 0) return i; } return -1; }

Target:
static int getUnusedByte(final byte[] array) { final byte[] usage = new byte[BYTE_SPACE_SIZE]; for (final byte b : array) { usage[0xFF & b] = 1; } for (int i = 0; i < usage.length; i++) { if (usage[i] == 0) return i; } return ALL_BYTES_USED; }
Source:
public void itPrefersPrimaryConfigForNonMergableFieldsWhenMergingConfigs() { BuildConfigUtils configUtils = new BuildConfigUtils(blazarConfiguration, gitHubHelper); BuildConfig mergedConfig = configUtils.mergeConfig(primaryConfig, secondaryConfig); assertThat(mergedConfig.getSteps()).isEqualTo(primaryConfig.getSteps()); assertThat(mergedConfig.getBefore()).isEqualTo(primaryConfig.getBefore()); assertThat(mergedConfig.getAfter()).isEqualTo(primaryConfig.getAfter()); assertThat(mergedConfig.getBuildpack()).isEqualTo(primaryConfig.getBuildpack()); assertThat(mergedConfig.getUser()).isEqualTo(primaryConfig.getUser()); assertThat(mergedConfig.getBuildResources()).isEqualTo(primaryConfig.getBuildResources()); }

Target:
public void itPrefersPrimaryConfigForNonMergableFieldsWhenMergingConfigs() { BuildConfig mergedConfig = configUtils.mergeConfig(primaryConfig, secondaryConfig); assertThat(mergedConfig.getSteps()).isEqualTo(primaryConfig.getSteps()); assertThat(mergedConfig.getBefore()).isEqualTo(primaryConfig.getBefore()); assertThat(mergedConfig.getAfter()).isEqualTo(primaryConfig.getAfter()); assertThat(mergedConfig.getBuildpack()).isEqualTo(primaryConfig.getBuildpack()); assertThat(mergedConfig.getUser()).isEqualTo(primaryConfig.getUser()); assertThat(mergedConfig.getBuildResources()).isEqualTo(primaryConfig.getBuildResources()); }
Source:
public int hashCode() { return Objects.hash( id, autoStartup, cpuPerSocket, threadsPerCpu, creationDate, defaultBootSequence, description, failBack, initrdUrl, isoPath, kernelParams, kernelUrl, osId, memSizeMb, maxMemorySizeMb, niceLevel, cpuShares, numOfSockets, numOfMonitors, origin, priority, stateless, smartcardEnabled, timeZone, usbPolicy, clusterId, vmType, quotaId, allowConsoleReconnect, dedicatedVmForVdsList, migrationSupport, tunnelMigration, vncKeyboardLayout, createdByUserId, defaultDisplayType, migrationDowntime, serialNumberPolicy, customSerialNumber, bootMenuEnabled, spiceFileTransferEnabled, spiceCopyPasteEnabled, cpuProfileId, numaTuneMode, vNumaNodeList, autoConverge, migrateCompressed, predefinedProperties, userDefinedProperties, customEmulatedMachine, customCpuName, smallIconId, largeIconId, consoleDisconnectAction, customCompatibilityVersion ); }

Target:
public int hashCode() { return Objects.hash( id, autoStartup, cpuPerSocket, threadsPerCpu, creationDate, defaultBootSequence, description, failBack, initrdUrl, isoPath, kernelParams, kernelUrl, osId, memSizeMb, maxMemorySizeMb, niceLevel, cpuShares, numOfSockets, numOfMonitors, origin, priority, stateless, smartcardEnabled, timeZone, usbPolicy, clusterId, vmType, quotaId, allowConsoleReconnect, dedicatedVmForVdsList, migrationSupport, tunnelMigration, vncKeyboardLayout, createdByUserId, defaultDisplayType, migrationDowntime, serialNumberPolicy, customSerialNumber, bootMenuEnabled, spiceFileTransferEnabled, spiceCopyPasteEnabled, cpuProfileId, numaTuneMode, vNumaNodeList, autoConverge, migrateCompressed, predefinedProperties, userDefinedProperties, customEmulatedMachine, customCpuName, smallIconId, largeIconId, consoleDisconnectAction, customCompatibilityVersion, resumeBehavior ); }
Source:
public static String toString(Serializable o) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { if(useJBoss){ oos=new JBossObjectOutputStream(baos); } else{ oos=new ObjectOutputStream(baos); } oos.writeObject(o); } catch (IOException e) { log.error("Serialization exception ", e); throw new TechnicalException(e); } finally { if (oos!=null){ try { oos.close(); } catch (IOException e) { log.warn("Exception during closing OutputStream: ",e); } } } String s = new String(Base64Coder.encode(baos.toByteArray())); if (s.isEmpty()) { log.info("toString({}, '{}', '{}')", new Object[] {toStringCount.getAndIncrement(), s, o}); } try { baos.close(); } catch (IOException e) { log.warn("Exception during closing OutputStream: ",e); } return s; }

Target:
public static String toString(Serializable o) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { if(useJBoss){ oos=new JBossObjectOutputStream(baos); } else{ oos=new ObjectOutputStream(baos); } oos.writeObject(o); } catch (IOException e) { log.error("Serialization exception ", e); throw new TechnicalException(e); } finally { String s = new String(Base64Coder.encode(baos.toByteArray())); if (s.isEmpty()) { log.info("toString({}, '{}', '{}')", new Object[] {toStringCount.getAndIncrement(), s, o}); } Closeables.closeQuietly(oos); return s; } }
Source:
public String getStreamConsumerArn(String stream) { if (this.streamConsumerArns == null) { return null; } return streamConsumerArns.get(stream); }

Target:
public Optional<String> getStreamConsumerArn(String stream) { return Optional.ofNullable(streamConsumerArns).map(arns -> arns.get(stream)); }
Source:
private void initializeDataNodeMetrics() { Gauge<Long> dataNodeCount = new Gauge<Long>() { @Override public Long getValue() { return clusterMapCallback.getDatanodeCount(); } }; registry.register(MetricRegistry.name(HelixClusterManager.class, "dataNodeCount"), dataNodeCount); Gauge<Long> dataNodeDownCount = new Gauge<Long>() { @Override public Long getValue() { return clusterMapCallback.getDownDatanodesCount(); } }; registry.register(MetricRegistry.name(HelixClusterManager.class, "dataNodeDownCount"), dataNodeDownCount); for (final AmbryDataNode datanode : clusterMapCallback.getDatanodes()) { final String metricName = datanode.getHostname() + "-" + datanode.getPort() + "-ResourceState"; Gauge<Long> dataNodeState = new Gauge<Long>() { @Override public Long getValue() { return datanode.getState() == HardwareState.AVAILABLE ? 1L : 0L; } }; registry.register(MetricRegistry.name(HelixClusterManager.class, metricName), dataNodeState); } }

Target:
void initializeDataNodeMetrics() { Gauge<Long> dataNodeCount = new Gauge<Long>() { @Override public Long getValue() { return clusterMapCallback.getDatanodeCount(); } }; registry.register(MetricRegistry.name(HelixClusterManager.class, "dataNodeCount"), dataNodeCount); Gauge<Long> dataNodeDownCount = new Gauge<Long>() { @Override public Long getValue() { return clusterMapCallback.getDownDatanodesCount(); } }; registry.register(MetricRegistry.name(HelixClusterManager.class, "dataNodeDownCount"), dataNodeDownCount); for (final AmbryDataNode datanode : clusterMapCallback.getDatanodes()) { final String metricName = datanode.getHostname() + "-" + datanode.getPort() + "-DataNodeResourceState"; Gauge<Boolean> dataNodeState = new Gauge<Boolean>() { @Override public Boolean getValue() { return datanode.getState() == HardwareState.AVAILABLE; } }; registry.register(MetricRegistry.name(HelixClusterManager.class, metricName), dataNodeState); } }
Source:
public void bindEntity(Class<?> cls) { if (lookupBoundClass(cls) != null) { return; } Class<?> declaredClass = lookupIncludeClass(cls); if (declaredClass == null) { log.trace("Missing include or excluded class {}", cls.getName()); return; } Include include = (Include) getFirstAnnotation(cls, Arrays.asList(Include.class)); Entity entity = (Entity) getFirstAnnotation(cls, Arrays.asList(Entity.class)); String name; if (entity == null || "".equals(entity.name())) { name = StringUtils.uncapitalize(cls.getSimpleName()); } else { name = entity.name(); } String type; if ("".equals(include.type())) { type = name; } else { type = include.type(); } bindJsonApiToEntity.put(type, declaredClass); entityBindings.put(declaredClass, new EntityBinding(this, declaredClass, type, name)); if (include.rootLevel()) { bindEntityRoots.add(declaredClass); } }

Target:
public void bindEntity(Class<?> cls) { if (lookupBoundClass(cls) != null) { return; } Class<?> declaredClass = lookupIncludeClass(cls); if (declaredClass == null) { log.trace("Missing include or excluded class {}", cls.getName()); return; } Include include = (Include) getFirstAnnotation(declaredClass, Arrays.asList(Include.class)); Entity entity = (Entity) getFirstAnnotation(declaredClass, Arrays.asList(Entity.class)); String name; if (entity == null || "".equals(entity.name())) { name = StringUtils.uncapitalize(cls.getSimpleName()); } else { name = entity.name(); } String type; if ("".equals(include.type())) { type = name; } else { type = include.type(); } bindJsonApiToEntity.put(type, declaredClass); entityBindings.put(declaredClass, new EntityBinding(this, declaredClass, type, name)); if (include.rootLevel()) { bindEntityRoots.add(declaredClass); } }
Source:
public static <@NonNull T> Iterable<@NonNull T> getAnalysisModulesOfClass(ITmfTrace trace, Class<T> moduleClass) { Iterable<@NonNull IAnalysisModule> analysisModules = trace.getAnalysisModules(); Set<T> modules = new HashSet<>(); for (IAnalysisModule module : analysisModules) { if (moduleClass.isAssignableFrom(module.getClass())) { modules.add(moduleClass.cast(module)); } } return modules; }

Target:
public static <T> Iterable<@NonNull T> getAnalysisModulesOfClass(ITmfTrace trace, Class<T> moduleClass) { Iterable<IAnalysisModule> analysisModules = trace.getAnalysisModules(); Set<@NonNull T> modules = new HashSet<>(); for (IAnalysisModule module : analysisModules) { if (moduleClass.isAssignableFrom(module.getClass())) { modules.add(moduleClass.cast(module)); } } return modules; }
Source:
public static Map<String, String> CreateStructFromConnection(final storage_server_connections connection, final storage_pool storage_pool) { class ConnParamMap extends HashMap<String, String> { void put(String key, Object value, Object def) { put(key, value != null ? value.toString() : def.toString()); } void putIfNotEmpty(String key, Object value) { if (value != null && !"".equals(value.toString())) { put(key, value.toString()); } } }; ConnParamMap con = new ConnParamMap(); con.put("id", connection.getid(), Guid.Empty.toString()); con.put("connection", connection.getconnection(), ""); con.put("portal", connection.getportal(), ""); con.put("port", connection.getport(), ""); con.put("iqn", connection.getiqn(), ""); con.put("user", connection.getuser_name(), ""); con.put("password", connection.getpassword(), ""); if (storage_pool != null && Config.<Boolean> GetValue(ConfigValues.AdvancedNFSOptionsEnabled, storage_pool.getcompatibility_version().getValue())) { con.putIfNotEmpty("mnt_options", connection.getMountOptions()); con.putIfNotEmpty("vfs_type", connection.getVfsType()); con.put("protocol_version", connection.getNfsVersion(), "auto"); con.putIfNotEmpty("timeout", connection.getNfsTimeo()); con.putIfNotEmpty("retrans", connection.getNfsRetrans()); } return con; }

Target:
public static Map<String, String> CreateStructFromConnection(final storage_server_connections connection, final storage_pool storage_pool) { DefaultValueMap con = new DefaultValueMap(); con.put("id", connection.getid(), Guid.Empty.toString()); con.put("connection", connection.getconnection(), ""); con.put("portal", connection.getportal(), ""); con.put("port", connection.getport(), ""); con.put("iqn", connection.getiqn(), ""); con.put("user", connection.getuser_name(), ""); con.put("password", connection.getpassword(), ""); if (storage_pool == null) { addIfNotNullOrEmpty(con, connection.getVfsType(), "vfs_type"); } else if (Config.<Boolean> GetValue(ConfigValues.AdvancedNFSOptionsEnabled, storage_pool.getcompatibility_version().getValue())) { con.putIfNotEmpty("mnt_options", connection.getMountOptions()); con.putIfNotEmpty("vfs_type", connection.getVfsType()); con.put("protocol_version", connection.getNfsVersion(), "auto"); con.putIfNotEmpty("timeout", connection.getNfsTimeo()); con.putIfNotEmpty("retrans", connection.getNfsRetrans()); } return con; }