auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldNotCreateNewAutoGenerationOptionWithNullParameters() throws Exception { long originalCount = getAllCount(); SimpleObject autoGenerationOption = new SimpleObject(); autoGenerationOption.add("identifierType", null); autoGenerationOption.add("location", null); autoGenerationOption.add("source", null); autoGenerationOption.add("automaticGenerationEnabled", null); autoGenerationOption.add("manualEntryEnabled", null); String json = new ObjectMapper().writeValueAsString(autoGenerationOption); MockHttpServletRequest req = request(RequestMethod.POST, getURI()); req.setContent(json.getBytes()); SimpleObject newAutoGenerationOption = deserialize(handle(req)); assertNull(PropertyUtils.getProperty(newAutoGenerationOption, "uuid")); assertEquals(originalCount, getAllCount()); }

Target:
public void shouldNotCreateNewAutoGenerationOptionWithNullParameters() throws Exception { SimpleObject autoGenerationOption = new SimpleObject(); autoGenerationOption.add("identifierType", null); autoGenerationOption.add("location", null); autoGenerationOption.add("source", null); autoGenerationOption.add("automaticGenerationEnabled", null); autoGenerationOption.add("manualEntryEnabled", null); String json = new ObjectMapper().writeValueAsString(autoGenerationOption); MockHttpServletRequest req = request(RequestMethod.POST, getURI()); req.setContent(json.getBytes()); handle(req); }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null) { return false; } if (!(o instanceof Organisation)) { return false; } final Organisation other = (Organisation) o; return Objects.equals(this.organisationIdentification, other.organisationIdentification); }

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Organisation)) { return false; } final Organisation other = (Organisation) o; return Objects.equals(this.organisationIdentification, other.organisationIdentification); }
Source:
public String moveObjects(AgentPrincipals agent, PID destinationPid, List<PID> pids) { if (destinationPid == null || pids == null || pids.isEmpty()) { throw new IllegalArgumentException("Must provide a destination and at least one object to move."); } if (agent == null || agent.getUsername() == null || agent.getPrincipals() == null) { throw new IllegalArgumentException("Must provide agent identification information"); } MoveObjectsJob job = new MoveObjectsJob(agent, destinationPid, pids, proxyService); job.setAclService(aclService); job.setFcrepoClient(fcrepoClient); job.setRepositoryObjectLoader(repositoryObjectLoader); job.setSparqlQueryService(sparqlQueryService); job.setTransactionManager(transactionManager); job.setOperationsMessageSender(operationsMessageSender); job.setObjectPathFactory(objectPathFactory); job.setOperationMetrics(operationMetrics); if (asynchronous) { log.info("User is queueing move operation of objects to destination {}", new Object[] { agent.getUsername(), job.getMoveId(), pids.size(), destinationPid }); moveExecutor.submit(job); } else { job.run(); } return job.getMoveId(); }

Target:
public String moveObjects(AgentPrincipals agent, PID destinationPid, List<PID> pids) { if (destinationPid == null || pids == null || pids.isEmpty()) { throw new IllegalArgumentException("Must provide a destination and at least one object to move."); } if (agent == null || agent.getUsername() == null || agent.getPrincipals() == null) { throw new IllegalArgumentException("Must provide agent identification information"); } MoveObjectsJob job = new MoveObjectsJob(agent, destinationPid, pids); job.setAclService(aclService); job.setRepositoryObjectLoader(repositoryObjectLoader); job.setTransactionManager(transactionManager); job.setOperationsMessageSender(operationsMessageSender); job.setObjectPathFactory(objectPathFactory); job.setOperationMetrics(operationMetrics); job.setProxyService(proxyService); if (asynchronous) { log.info("User is queueing move operation of objects to destination {}", new Object[] { agent.getUsername(), job.getMoveId(), pids.size(), destinationPid }); moveExecutor.submit(job); } else { job.run(); } return job.getMoveId(); }
Source:
void testGetAllInspectedTypes() { Set<Class<?>> expectedInspectedTypes = Sets.newSet(pA.class, A.class, B.class, C.class, D.class); inspector.getAllInspectedTypes() .forEach(inspectedType -> assertTrue(expectedInspectedTypes.contains(inspectedType))); }

Target:
void testGetAllInspectedTypes() { Set<Class<?>> expectedInspectedTypes = Sets.newSet(pA.class, A.class, B.class, C.class, D.class); Set<Class<?>> resultInspectedTypes = inspector.getAllInspectedTypes(); resultInspectedTypes.forEach(resultType -> assertTrue(expectedInspectedTypes.contains(resultType))); expectedInspectedTypes.forEach(expectedType -> assertTrue(resultInspectedTypes.contains(expectedType))); }
Source:
private List<SkippedLine> checkAndAddSkip(List<SkippedLine> list, SkippedLine toAdd) { if (toAdd.getSize() > 1) { list.add(toAdd); } return list; }

Target:
private void checkAndAddSkip(List<SkippedLine> list, SkippedLine toAdd) { if (toAdd.getSize() > 1) { list.add(toAdd); } }
Source:
public void set(String field, final String value) { if (!"".equals(field)) { if (isUserDefinedField(field)) { userDefinedFields.put(field, value); String fieldName = getUserDefinedFieldName(field); if (fieldName != null) { userDefinedFieldNames.add(new ControlField(fieldName)); } field = fieldName; } if (field != null) { values.put(field, value); } } }

Target:
public void set(String field, final String value) { if (field != null && isUserDefinedField(field)) { userDefinedFields.put(field, value); String fieldName = getUserDefinedFieldName(field); if (fieldName != null) { userDefinedFieldNames.add(new ControlField(fieldName)); } field = fieldName; } if (field != null && !"".equals(field)) { values.put(field, value); } }
Source:
public void testPutIfAbsentNoStoreEntryHasCacheWriterEntry() throws Exception { final FakeStore realStore = new FakeStore(Collections.<String, String>emptyMap()); this.store = spy(realStore); final FakeCacheWriter realCache = new FakeCacheWriter(Collections.singletonMap("key", "oldValue")); final Ehcache<String, String> ehcache = this.getEhcache(realCache); assertThat(ehcache.putIfAbsent("key", "value"), is(nullValue())); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(realStore.getEntryMap().get("key"), equalTo("value")); assertThat(realCache.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.PUT)); }

Target:
public void testPutIfAbsentNoStoreEntryHasCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.<String, String>emptyMap()); this.store = spy(fakeStore); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "oldValue")); final Ehcache<String, String> ehcache = this.getEhcache(fakeWriter); assertThat(ehcache.putIfAbsent("key", "value"), is(nullValue())); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); assertThat(fakeWriter.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.PUT)); }
Source:
public void requestDispose() { if (mH.getLooper().isCurrentThread()) { dispose(); } else { mH.post(new Runnable() { public void run() { dispose(); } }); } mDisposed = true; }

Target:
public void requestDispose() { mDragStateDisposed = true; if (mH.getLooper().isCurrentThread()) { dispose(); } else { mH.post(new Runnable() { public void run() { dispose(); } }); } }
Source:
private void updateContext(String resourceName, ZNRecord record) { if (record != null && _initialContextMapHashcode.containsKey(resourceName) && _initialContextMapHashcode.get(resourceName) .equals(Objects.hashCode(record.toString()))) { return; } _contextMap.put(resourceName, record); _contextToUpdate.add(resourceName); }

Target:
private void updateContext(String resourceName, ZNRecord record) { _contextMap.put(resourceName, record); _contextToUpdate.add(resourceName); }
Source:
public void registerMetricsCaptor(MetricsCaptor metricsCaptor) { super.registerMetricsCaptor(metricsCaptor); this.sizeGauge = metricsCaptor.gaugeBuilder("spring.integration.channel.queue.size", this, (channel) -> getQueueSize()) .tag("name", getComponentName() == null ? "unknown" : getComponentName()) .tag("type", "channel") .description("The size of queue channel") .build(); this.remainingCapacityGauge = metricsCaptor.gaugeBuilder("spring.integration.channel.queue.remaining.capacity", this, (channel) -> getRemainingCapacity()) .tag("name", getComponentName() == null ? "unknown" : getComponentName()) .tag("type", "channel") .description("The remaining.capacity of queue channel") .build(); }

Target:
public void registerMetricsCaptor(MetricsCaptor metricsCaptor) { super.registerMetricsCaptor(metricsCaptor); this.sizeGauge = metricsCaptor.gaugeBuilder("spring.integration.channel.queue.size", this, (channel) -> getQueueSize()) .tag("name", getComponentName() == null ? "unknown" : getComponentName()) .tag("type", "channel") .description("The size of the queue channel") .build(); this.remainingCapacityGauge = metricsCaptor.gaugeBuilder("spring.integration.channel.queue.remaining.capacity", this, (channel) -> getRemainingCapacity()) .tag("name", getComponentName() == null ? "unknown" : getComponentName()) .tag("type", "channel") .description("The remaining capacity of the queue channel") .build(); }
Source:
VmDeviceUtils(VmStaticDao vmStaticDao, VmDeviceDao vmDeviceDao, ClusterDao clusterDao, VmTemplateDao vmTemplateDao, VmHandler vmHandler, MacPoolPerCluster macPoolPerCluster, RngDeviceUtils rngDeviceUtils, VideoDeviceSettings videoDeviceSettings, OsRepository osRepository) { this.vmStaticDao = vmStaticDao; this.vmDeviceDao = vmDeviceDao; this.clusterDao = clusterDao; this.vmTemplateDao = vmTemplateDao; this.vmHandler = vmHandler; this.macPoolPerCluster = macPoolPerCluster; this.rngDeviceUtils = rngDeviceUtils; this.videoDeviceSettings = videoDeviceSettings; this.osRepository = osRepository; this.compensationContext = null; }

Target:
VmDeviceUtils(VmStaticDao vmStaticDao, VmDeviceDao vmDeviceDao, ClusterDao clusterDao, VmTemplateDao vmTemplateDao, VmHandler vmHandler, MacPoolPerCluster macPoolPerCluster, RngDeviceUtils rngDeviceUtils, VideoDeviceSettings videoDeviceSettings, OsRepository osRepository) { this.vmStaticDao = vmStaticDao; this.vmDeviceDao = vmDeviceDao; this.clusterDao = clusterDao; this.vmTemplateDao = vmTemplateDao; this.vmHandler = vmHandler; this.macPoolPerCluster = macPoolPerCluster; this.rngDeviceUtils = rngDeviceUtils; this.videoDeviceSettings = videoDeviceSettings; this.osRepository = osRepository; }
Source:
private void handleFinishedContext(final String contextId, final Optional<ActiveContext> parentContext) { if (contextIdToWorkerContexts.containsKey(contextId)) { handleFinishedWorkerContext(contextId); } else if (contextIdToServerContexts.containsKey(contextId)) { handleFinishedServerContext(contextId); } else if (contextIdToRootContexts.remove(contextId) != null) { LOG.log(Level.INFO, "Root context {0} is closed. Its evaluator will be released soon.", contextId); } else if (deletedWorkerContextIds.remove(contextId) || deletedServerContextIds.remove(contextId)) { LOG.log(Level.INFO, "The context {0} is closed by EM's Delete.", contextId); final String rootContextId = parentContext.get().getId(); final ActiveContext rootContext = contextIdToRootContexts.remove(rootContextId); rootContext.close(); } else { LOG.log(Level.WARNING, "Untracked context: {0}", contextId); if (parentContext.isPresent()) { LOG.log(Level.INFO, "Close a context {0}, which is a parent of the finished context whose id is {1}", new Object[]{parentContext, contextId}); parentContext.get().close(); } } }

Target:
private void handleFinishedContext(final String contextId, final Optional<ActiveContext> parentContext) { if (contextIdToWorkerContexts.containsKey(contextId)) { handleFinishedWorkerContext(contextId); } else if (contextIdToServerContexts.containsKey(contextId)) { handleFinishedServerContext(contextId); } else if (contextIdToRootContexts.remove(contextId) != null) { LOG.log(Level.INFO, "Root context {0} is closed. Its evaluator will be released soon.", contextId); } else if (deletedWorkerContextIds.remove(contextId) || deletedServerContextIds.remove(contextId)) { LOG.log(Level.INFO, "The context {0} is closed by EM's Delete.", contextId); if (!parentContext.isPresent()) { throw new RuntimeException("Root context of the deleted worker/server context does not exist"); } final String rootContextId = parentContext.get().getId(); final ActiveContext rootContext = contextIdToRootContexts.remove(rootContextId); rootContext.close(); } else { LOG.log(Level.WARNING, "Untracked context: {0}", contextId); if (parentContext.isPresent()) { LOG.log(Level.INFO, "Close a context {0}, which is a parent of the finished context whose id is {1}", new Object[]{parentContext, contextId}); parentContext.get().close(); } } }
Source:
protected RemoteOperationResult<ArrayList<RemoteFile>> run(OwnCloudClient client) { RemoteOperationResult<ArrayList<RemoteFile>> result; mLocalFolder = getStorageManager().getFileByPath(mLocalFolder.getRemotePath()); if (OCFile.ROOT_PATH.equals(mLocalFolder.getRemotePath()) && syncVersionAndProfileEnabled) { OwnCloudVersion serverVersion = syncCapabilitiesAndGetServerVersion(); syncUserProfile(); } SynchronizeFolderOperation syncOp = new SynchronizeFolderOperation( mContext, mLocalFolder.getRemotePath(), mAccount, System.currentTimeMillis(), false, false, false ); result = syncOp.execute(client, getStorageManager()); sendLocalBroadcast( EVENT_SINGLE_FOLDER_CONTENTS_SYNCED, mLocalFolder.getRemotePath(), result); if (result.isSuccess()) { updateShareIconsInFiles(client); } sendLocalBroadcast( EVENT_SINGLE_FOLDER_SHARES_SYNCED, mLocalFolder.getRemotePath(), result); return result; }

Target:
protected RemoteOperationResult<ArrayList<RemoteFile>> run(OwnCloudClient client) { RemoteOperationResult<ArrayList<RemoteFile>> result; mLocalFolder = getStorageManager().getFileByPath(mLocalFolder.getRemotePath()); if (OCFile.ROOT_PATH.equals(mLocalFolder.getRemotePath()) && syncVersionAndProfileEnabled) { syncUserProfile(); } SynchronizeFolderOperation syncOp = new SynchronizeFolderOperation( mContext, mLocalFolder.getRemotePath(), mAccount, System.currentTimeMillis(), false, false, false ); result = syncOp.execute(client, getStorageManager()); sendLocalBroadcast( EVENT_SINGLE_FOLDER_CONTENTS_SYNCED, mLocalFolder.getRemotePath(), result); if (result.isSuccess()) { updateShareIconsInFiles(client); } sendLocalBroadcast( EVENT_SINGLE_FOLDER_SHARES_SYNCED, mLocalFolder.getRemotePath(), result); return result; }
Source:
private void acquireRemoteIfNeeded(InvocationContext ctx, AbstractDataCommand command, boolean localNodeIsLockOwner) throws Throwable { if (hasSkipLocking(command)) return; Object key = command.getKey(); boolean needBackupLocks = ctx.isOriginLocal() && (!localNodeIsLockOwner | isStateTransferInProgress()); if (needBackupLocks && !command.hasFlag(Flag.CACHE_MODE_LOCAL)) { final TxInvocationContext txContext = (TxInvocationContext) ctx; LocalTransaction localTransaction = (LocalTransaction) txContext.getCacheTransaction(); final boolean alreadyLocked = localTransaction.getAffectedKeys().contains(key); if (alreadyLocked) { log.tracef("We already have lock for key %s, skip remote lock acquisition", key); return; } else { LockControlCommand lcc = cf.buildLockControlCommand( key, command.getFlags(), txContext.getGlobalTransaction()); invokeNextInterceptor(ctx, lcc); } } ((TxInvocationContext) ctx).addAffectedKey(key); }

Target:
private void acquireRemoteIfNeeded(InvocationContext ctx, AbstractDataCommand command, boolean localNodeIsLockOwner) throws Throwable { Object key = command.getKey(); boolean needBackupLocks = ctx.isOriginLocal() && (!localNodeIsLockOwner || isStateTransferInProgress()); if (needBackupLocks && !command.hasFlag(Flag.CACHE_MODE_LOCAL)) { final TxInvocationContext txContext = (TxInvocationContext) ctx; LocalTransaction localTransaction = (LocalTransaction) txContext.getCacheTransaction(); final boolean alreadyLocked = localTransaction.getAffectedKeys().contains(key); if (alreadyLocked) { log.tracef("We already have lock for key %s, skip remote lock acquisition", key); return; } else { LockControlCommand lcc = cf.buildLockControlCommand( key, command.getFlags(), txContext.getGlobalTransaction()); invokeNextInterceptor(ctx, lcc); } } ((TxInvocationContext) ctx).addAffectedKey(key); }
Source:
private void getImageList(String inputHTML, StringBuffer imageFileList) { String outputHTML = inputHTML; String Lower = outputHTML.toLowerCase(); int img = Lower.indexOf("img "); imageFileList.setLength(0); boolean first = true; while (img != -1) { int src = Lower.indexOf("src=", img); if (src != -1) { src += 4; char qte = Lower.charAt(src); int iEnd = Lower.indexOf(qte, src + 1); if (first) { imageFileList.append(inputHTML.substring(src + 1, iEnd)); first = false; } else { imageFileList.append("," + outputHTML.substring(src + 1, iEnd)); } img = Lower.indexOf("img ", src); } else { img = -1; } } }

Target:
private void getImageList(String inputHTML, StringBuffer imageFileList) { String outputHtml = inputHTML; String Lower = outputHtml.toLowerCase(); int img = Lower.indexOf("img "); imageFileList.setLength(0); boolean first = true; while (img != -1) { int src = Lower.indexOf("src=", img); if (src != -1) { src += 4; char qte = Lower.charAt(src); int iEnd = Lower.indexOf(qte, src + 1); if (first) { imageFileList.append(inputHTML.substring(src + 1, iEnd)); first = false; } else { imageFileList.append("," + outputHtml.substring(src + 1, iEnd)); } img = Lower.indexOf("img ", src); } else { img = -1; } } }
Source:
public static <V1, V2> Set<V2> transformSetLazily(Set<V1> original, Function<V1, V2> function) { Set<V2> transformed = Sets.newLinkedHashSetWithExpectedSize(original .size()); LazyTransformSet<V1, V2> lazyTransformSet = (new Transformers()). new LazyTransformSet<>(original, function); Iterator<V2> iterator = lazyTransformSet.iterator(); while(iterator.hasNext()) { transformed.add(iterator.next()); } return transformed; }

Target:
public static <V1, V2> Set<V2> transformSetLazily(Set<V1> original, Function<V1, V2> function) { return new LazyTransformSet<V1, V2>(original, function); }
Source:
protected void cacheForever(final HttpServletResponse rsp) { final long now = System.currentTimeMillis(); rsp.setHeader("Cache-Control", "max-age=31536000,public"); rsp.setDateHeader("Expires", now + 31536000000L); rsp.setDateHeader("Date", now); }

Target:
protected void cacheForever(final HttpServletResponse rsp) { final long now = System.currentTimeMillis(); rsp.setHeader("Cache-Control", "public, max-age=31536000"); rsp.setDateHeader("Expires", now + 31536000000L); rsp.setDateHeader("Date", now); }
Source:
final Object getValue(ValueNode value) { if (value.isNull()) { return null; } if (value.numberType() != null) { switch (value.numberType()) { case LONG: return value.longValue(); case DOUBLE: return value.doubleValue(); case FLOAT: return value.floatValue(); case INT: return value.intValue(); case BIG_DECIMAL: return value.decimalValue(); case BIG_INTEGER: return value.bigIntegerValue(); default: return value.asText(); } } if (value.isBoolean()) { return value.asBoolean(); } if (value.canConvertToInt()) { return value.asInt(); } if (value.canConvertToLong()) { return value.asLong(); } return value.asText(); }

Target:
private Object getValue(ValueNode value) { if (value.isNull()) { return null; } if (value.numberType() != null) { switch (value.numberType()) { case LONG: return value.longValue(); case DOUBLE: return value.doubleValue(); case FLOAT: return value.floatValue(); case INT: return value.intValue(); case BIG_DECIMAL: return value.decimalValue(); case BIG_INTEGER: return value.bigIntegerValue(); default: return value.asText(); } } if (value.isBoolean()) { return value.asBoolean(); } return value.asText(); }
Source:
private AudioFocusRequestCompat( int focusGain, OnAudioFocusChangeListener onAudioFocusChangeListener, Handler focusChangeHandler, AudioAttributesCompat audioFocusRequestCompat, boolean pauseOnDuck, boolean acceptsDelayedFocusGain) { mFocusGain = focusGain; mFocusChangeHandler = focusChangeHandler; mAudioAttributesCompat = audioFocusRequestCompat; mPauseOnDuck = pauseOnDuck; mAcceptsDelayedFocusGain = acceptsDelayedFocusGain; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O && mFocusChangeHandler.getLooper() != Looper.getMainLooper()) { mOnAudioFocusChangeListener = new OnAudioFocusChangeListenerHandlerCompat( onAudioFocusChangeListener, focusChangeHandler); } else { mOnAudioFocusChangeListener = onAudioFocusChangeListener; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mPlatformAudioFocusRequest = new AudioFocusRequest.Builder(mFocusGain) .setAudioAttributes(getAudioAttributes()) .setAcceptsDelayedFocusGain(mAcceptsDelayedFocusGain) .setWillPauseWhenDucked(mPauseOnDuck) .setOnAudioFocusChangeListener( mOnAudioFocusChangeListener, mFocusChangeHandler) .build(); } else { mPlatformAudioFocusRequest = null; } }

Target:
private AudioFocusRequestCompat( int focusGain, OnAudioFocusChangeListener onAudioFocusChangeListener, Handler focusChangeHandler, AudioAttributesCompat audioFocusRequestCompat, boolean pauseOnDuck, boolean acceptsDelayedFocusGain) { mFocusGain = focusGain; mFocusChangeHandler = focusChangeHandler; mAudioAttributesCompat = audioFocusRequestCompat; mPauseOnDuck = pauseOnDuck; mAcceptsDelayedFocusGain = acceptsDelayedFocusGain; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O && mFocusChangeHandler.getLooper() != Looper.getMainLooper()) { mOnAudioFocusChangeListener = new OnAudioFocusChangeListenerHandlerCompat( onAudioFocusChangeListener, focusChangeHandler); } else { mOnAudioFocusChangeListener = onAudioFocusChangeListener; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mFrameworkAudioFocusRequest = new AudioFocusRequest.Builder(mFocusGain) .setAudioAttributes(getAudioAttributes()) .setAcceptsDelayedFocusGain(mAcceptsDelayedFocusGain) .setWillPauseWhenDucked(mPauseOnDuck) .setOnAudioFocusChangeListener( mOnAudioFocusChangeListener, mFocusChangeHandler) .build(); } else { mFrameworkAudioFocusRequest = null; } }
Source:
public Object getChild(String id) { Iterator<RegistryPageContributor> iterator = subPages.iterator(); while (iterator.hasNext()) { RegistryPageContributor next = iterator.next(); if (next.getPageId().equals(id)) { return next; } } return null; }

Target:
public Object getChild(String id) { return subPages.stream().filter(c -> c.getPageId().equals(id)).findFirst().orElse(null); }
Source:
public List<PoolQuantityDTO> getDryRun(Consumer consumer, String serviceLevelOverride) { List<PoolQuantity> poolQuantities = new ArrayList<PoolQuantity>(); try { Owner owner = consumer.getOwner(); if (consumer.isDev()) { if (config.getBoolean(ConfigProperties.STANDALONE) || !poolCurator.hasActiveEntitlementPools(consumer.getOwner(), null)) { throw new ForbiddenException(i18n.tr( "Development units may only be used on hosted servers" + " and with orgs that have active subscriptions." )); } String sku = consumer.getFact("dev_sku"); Pool devPool = poolCurator.findDevPool(consumer); if (devPool != null) { poolManager.deletePool(devPool); } devPool = poolManager.createPool(assembleDevPool(consumer, sku)); poolQuantities.add(new PoolQuantity(devPool, 1)); } else { poolQuantities = poolManager.getBestPools( consumer, null, null, owner, serviceLevelOverride, null); } log.debug("Created Pool Quantity list: {}", poolQuantities); } catch (EntitlementRefusedException e) { if (log.isDebugEnabled()) { log.debug("consumer dry-run errors:", consumer.getUuid()); for (Entry<String, ValidationResult> entry : e.getResults().entrySet()) { log.debug("errors for pool id: {}", entry.getKey()); for (ValidationError error : entry.getValue().getErrors()) { log.debug(error.getResourceKey()); } } } } List<PoolQuantityDTO> result = new ArrayList<PoolQuantityDTO>(); for (PoolQuantity pq : poolQuantities) { result.add(this.modelTranslator.translate(pq, PoolQuantityDTO.class)); } return result; }

Target:
public List<PoolQuantity> getDryRun(Consumer consumer, String serviceLevelOverride) { List<PoolQuantity> result = new ArrayList<PoolQuantity>(); try { Owner owner = consumer.getOwner(); if (consumer.isDev()) { if (config.getBoolean(ConfigProperties.STANDALONE) || !poolCurator.hasActiveEntitlementPools(consumer.getOwner(), null)) { throw new ForbiddenException(i18n.tr( "Development units may only be used on hosted servers" + " and with orgs that have active subscriptions." )); } String sku = consumer.getFact("dev_sku"); Pool devPool = poolCurator.findDevPool(consumer); if (devPool != null) { poolManager.deletePool(devPool); } devPool = poolManager.createPool(assembleDevPool(consumer, sku)); result.add(new PoolQuantity(devPool, 1)); } else { result = poolManager.getBestPools( consumer, null, null, owner, serviceLevelOverride, null); } log.debug("Created Pool Quantity list: {}", result); } catch (EntitlementRefusedException e) { if (log.isDebugEnabled()) { log.debug("consumer dry-run errors:", consumer.getUuid()); for (Entry<String, ValidationResult> entry : e.getResults().entrySet()) { log.debug("errors for pool id: {}", entry.getKey()); for (ValidationError error : entry.getValue().getErrors()) { log.debug(error.getResourceKey()); } } } } return result; }
Source:
public Transceiver read(final String journalKey, final String slug) { return new EntityTransceiver() { @Override protected ArticleCollection fetchEntity() { ArticleCollection result = DataAccessUtils.uniqueResult(hibernateTemplate.execute(new HibernateCallback<List<ArticleCollection>>() { @Override public List<ArticleCollection> doInHibernate(Session session) { Query query = session.createQuery("" + "select c " + "from ArticleCollection as c inner join c.journal as j " + "where c.slug=:slug and j.journalKey=:journalKey"); query.setString("slug", slug); query.setString("journalKey", journalKey); return query.list(); } })); if (result == null) { String message = String.format("No collection exists in journal=%s with slug=%s", journalKey, slug); throw new RestClientException(message, HttpStatus.NOT_FOUND); } return result; } @Override protected Object getView(AmbraEntity entity) { return entity; } }; }

Target:
public Transceiver read(final String journalKey, final String slug) { return new EntityTransceiver() { @Override protected ArticleCollection fetchEntity() { ArticleCollection result = getCollection(journalKey, slug); if (result == null) { String message = String.format("No collection exists in journal=%s with slug=%s", journalKey, slug); throw new RestClientException(message, HttpStatus.NOT_FOUND); } return result; } @Override protected Object getView(AmbraEntity entity) { return entity; } }; }
Source:
private static BoundedContextAction aggregateRepositoryDispatch() { return new BoundedContextAction() { @Override public void perform(BoundedContext context) { final AggregateRepository<?, ?> repository = Given.aggregateRepo(context); repository.initStorage(InMemoryStorageFactory.getInstance()); try { repository.dispatch(Given.validCommand()); } catch (IllegalStateException e) { Assert.assertTrue(e.getMessage().contains("No record found for command ID: EMPTY")); } } }; }

Target:
private static BoundedContextAction aggregateRepositoryDispatch() { return new BoundedContextAction() { @Override public void perform(BoundedContext context) { final AggregateRepository<?, ?> repository = Given.aggregateRepo(context); repository.initStorage(InMemoryStorageFactory.getInstance()); try { repository.dispatch(Given.validCommand()); } catch (IllegalStateException e) { if (!e.getMessage() .contains("No record found for command ID: EMPTY")) { throw e; } } } }; }
Source:
public void userAuthDevIdResult() throws Exception { DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.isUserAuthorized(deviceIds); Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 5, "Expected 5 authorized devices for admin user"); Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0, "Expected 0 un-authorized devices for admin user"); }

Target:
public void userAuthDevIdResult() throws Exception { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER); DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService. isUserAuthorized(deviceIds); Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 5, "Expected 5 authorized devices for admin user"); Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0, "Expected 0 un-authorized devices for admin user"); }
Source:
private HttpServletRequest createWebRequest(String uri, String... parameters) { WebRequest request = new PostMethodWebRequest("http://localhost" + uri); if (Const.SystemParams.PAGES_REQUIRING_ORIGIN_VALIDATION.contains(uri)) { request.setHeaderField("referer", "http://localhost"); String sessionId = sc.getSession(true).getId(); String token = CryptoHelper.computeSessionToken(sessionId); request.setParameter(Const.ParamsNames.SESSION_TOKEN, token); } Map<String, List<String>> paramMultiMap = new HashMap<>(); for (int i = 0; i < parameters.length; i = i + 2) { String key = parameters[i]; if (paramMultiMap.get(key) == null) { paramMultiMap.put(key, new ArrayList<String>()); } paramMultiMap.get(key).add(parameters[i + 1]); } paramMultiMap.forEach((key, value) -> { List<String> values = value; request.setParameter(key, values.toArray(new String[values.size()])); }); try { InvocationContext ic = sc.newInvocation(request); return ic.getRequest(); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
private HttpServletRequest createWebRequest(String uri, String... parameters) { WebRequest request = new PostMethodWebRequest("http://localhost" + uri); if (Const.SystemParams.PAGES_REQUIRING_ORIGIN_VALIDATION.contains(uri)) { request.setHeaderField("referer", "http://localhost"); String sessionId = sc.getSession(true).getId(); String token = CryptoHelper.computeSessionToken(sessionId); request.setParameter(Const.ParamsNames.SESSION_TOKEN, token); } Map<String, List<String>> paramMultiMap = new HashMap<>(); for (int i = 0; i < parameters.length; i = i + 2) { String key = parameters[i]; if (paramMultiMap.get(key) == null) { paramMultiMap.put(key, new ArrayList<String>()); } paramMultiMap.get(key).add(parameters[i + 1]); } paramMultiMap.forEach((key, values) -> request.setParameter(key, values.toArray(new String[values.size()]))); try { InvocationContext ic = sc.newInvocation(request); return ic.getRequest(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public int readInteger() { ++ decodedPosition; if (decodedPosition == decoded.length) { byte[] tempEncode = new byte[bitWidth]; encoded.position(encodedPos); if (encodedPos + bitWidth > encoded.limit()) { Arrays.fill(tempEncode, (byte)0); encoded.get(tempEncode, 0, encoded.limit() - encodedPos); packer.unpack8Values(ByteBuffer.wrap(tempEncode), 0, decoded, 0); } else { packer.unpack8Values(encoded, encodedPos, decoded, 0); } encodedPos += bitWidth; decodedPosition = 0; } return decoded[decodedPosition]; }

Target:
public int readInteger() { ++ decodedPosition; if (decodedPosition == decoded.length) { encoded.position(encodedPos); if (encodedPos + bitWidth > encoded.limit()) { byte[] tempEncode = new byte[bitWidth]; encoded.get(tempEncode, 0, encoded.limit() - encodedPos); packer.unpack8Values(ByteBuffer.wrap(tempEncode), 0, decoded, 0); } else { packer.unpack8Values(encoded, encodedPos, decoded, 0); } encodedPos += bitWidth; decodedPosition = 0; } return decoded[decodedPosition]; }
Source:
@Override public boolean exists(Path f) throws IOException { statIncrement(CALL_EXIST); return super.exists(f); }

Target:
public boolean exists(Path f) throws IOException { statIncrement(CALL_EXIST); return super.exists(f); }
Source:
public void shutdown() { for (DBBPool.BBContainer c : m_readBBContainers) { c.discard(); } m_readBBContainers.clear(); }

Target:
public void shutdown() { for (DBBPool.BBContainer c : m_readBBContainers) { c.discard(); } m_readBBContainers.clear(); m_totalAvailable.set(0); }
Source:
private void getUrl(StringBuilder buf) { String f = item.getSearchUrl(); if(f.startsWith("/")) { buf.setLength(0); buf.append(f); } else { if(buf.length()==0 || buf.charAt(buf.length()-1)!='/') buf.append('/'); buf.append(f); } }

Target:
private void getUrl(StringBuilder buf) { if(parent!=null) { parent.getUrl(buf); } String f = item.getSearchUrl(); if(f.startsWith("/")) { buf.setLength(0); buf.append(f); } else { if(buf.length()==0 || buf.charAt(buf.length()-1)!='/') buf.append('/'); buf.append(f); } }
Source:
public static boolean allUnique(List<String> argListNames) { return argListNames.stream().allMatch(new HashSet<>()::add); }

Target:
public static boolean allUnique(List<String> argListNames) { return argListNames.size() == new HashSet<>(argListNames).size(); }
Source:
protected void prepareTestData() { testData = loadDataBundle("/FeedbackRequestAccessLinksResendPageUiTest.json"); String student1GoogleId = TestProperties.TEST_STUDENT1_ACCOUNT; String student1Email = student1GoogleId + "@gmail.com"; testData.accounts.get("alice.tmms").googleId = student1GoogleId; testData.accounts.get("alice.tmms").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS2104").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS1101").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS1101").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS4215").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS4215").email = student1Email; testData.students.get("alice.tmms@SHomeUiT.CS4221").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS4221").email = student1Email; studentEmailAddress = student1Email; removeAndRestoreDataBundle(testData); FeedbackSessionAttributes gracedFeedbackSession = BackDoor.getFeedbackSession("SHomeUiT.CS2104", "Graced Feedback Session"); Calendar fsCalendar = Calendar.getInstance(); fsCalendar.add(Calendar.DATE, -10); gracedFeedbackSession.setStartTime(fsCalendar.getTime().toInstant()); gracedFeedbackSession.setSessionVisibleFromTime(fsCalendar.getTime().toInstant()); fsCalendar.add(Calendar.DATE, +20); gracedFeedbackSession.setEndTime(fsCalendar.getTime().toInstant()); BackDoor.editFeedbackSession(gracedFeedbackSession); }

Target:
protected void prepareTestData() { testData = loadDataBundle("/FeedbackRequestAccessLinksResendPageUiTest.json"); String student1GoogleId = TestProperties.TEST_STUDENT1_ACCOUNT; studentEmailAddress = student1GoogleId + "@gmail.com"; testData.accounts.get("alice.tmms").googleId = student1GoogleId; testData.accounts.get("alice.tmms").email = studentEmailAddress; testData.students.get("alice.tmms@SHomeUiT.CS2104").email = studentEmailAddress; testData.students.get("alice.tmms@SHomeUiT.CS1101").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS1101").email = studentEmailAddress; testData.students.get("alice.tmms@SHomeUiT.CS4215").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS4215").email = studentEmailAddress; testData.students.get("alice.tmms@SHomeUiT.CS4221").googleId = student1GoogleId; testData.students.get("alice.tmms@SHomeUiT.CS4221").email = studentEmailAddress; removeAndRestoreDataBundle(testData); FeedbackSessionAttributes gracedFeedbackSession = BackDoor.getFeedbackSession("SHomeUiT.CS2104", "Graced Feedback Session"); gracedFeedbackSession.setStartTime(Instant.now().minus(Duration.ofDays(10))); gracedFeedbackSession.setSessionVisibleFromTime(Instant.now().minus(Duration.ofDays(10))); gracedFeedbackSession.setEndTime(Instant.now().plus(Duration.ofDays(10))); BackDoor.editFeedbackSession(gracedFeedbackSession); }
Source:
private void copyTitle() { List<BibEntry> selectedBibEntries = stateManager.getSelectedEntries(); List<String> titles = selectedBibEntries.stream() .filter(bibEntry -> bibEntry.getTitle().isPresent()) .map(bibEntry -> bibEntry.getTitle().get()) .collect(Collectors.toList()); if (titles.isEmpty()) { dialogService.notify(Localization.lang("None of the selected entries have titles.")); return; } final String copiedTitles = String.join("\n", titles); clipBoardManager.setContent(copiedTitles); if (titles.size() == selectedBibEntries.size()) { dialogService.notify(Localization.lang("Copied") + " '" + JabRefDialogService.shortenDialogMessage(copiedTitles) + "'."); } else { dialogService.notify(Localization.lang("Warning: %0 out of %1 entries have undefined title.", Integer.toString(selectedBibEntries.size() - titles.size()), Integer.toString(selectedBibEntries.size()))); } }

Target:
private void copyTitle() { List<BibEntry> selectedBibEntries = stateManager.getSelectedEntries(); List<String> titles = selectedBibEntries.stream() .filter(bibEntry -> bibEntry.getTitle().isPresent()) .map(bibEntry -> bibEntry.getTitle().get()) .collect(Collectors.toList()); if (titles.isEmpty()) { dialogService.notify(Localization.lang("None of the selected entries have titles.")); return; } final String copiedTitles = String.join("\n", titles); clipBoardManager.setContent(copiedTitles); if (titles.size() == selectedBibEntries.size()) { dialogService.notify(Localization.lang("Copied '%0' to clipboard.", JabRefDialogService.shortenDialogMessage(copiedTitles))); } else { dialogService.notify(Localization.lang("Warning: %0 out of %1 entries have undefined title.", Integer.toString(selectedBibEntries.size() - titles.size()), Integer.toString(selectedBibEntries.size()))); } }
Source:
public void switch_statement() { Result result = Result.createFor("SwitchStatement"); }

Target:
public void switch_statement() { Result result = Result.createFor("SwitchStatement"); assertThat(result.symbol("a", 16)).isSameAs(result.reference(18, 28)); assertThat(result.symbol("a", 20)).isSameAs(result.reference(21, 24)); }
Source:
public List<SelectItem> getNewspaperBatchesItems() { if (Objects.isNull(newspaperBatchesItems)) { try { newspaperBatchesItems = NewspaperProcessesMigrator.getNewspaperBatches().stream() .map(batchTransfer -> new SelectItem(batchTransfer.getId(), batchTransfer.getTitle())) .collect(Collectors.toList()); } catch (DataException | DAOException | IOException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); return Collections.emptyList(); } } return newspaperBatchesItems; }

Target:
public List<BatchDTO> getNewspaperBatchesItems() { if (Objects.isNull(newspaperBatchesItems)) { try { newspaperBatchesItems = NewspaperProcessesMigrator.getNewspaperBatches(); } catch (DataException | DAOException | IOException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); return Collections.emptyList(); } } return newspaperBatchesItems; }
Source:
public String toString() { return "TableHandle{" + "connectorId=" + connectorId + ", connectorHandle=" + connectorHandle + ", layout=" + layout + '}'; }

Target:
public String toString() { return toStringHelper(this) .add("connectorId", connectorId) .add("connectorHandle", connectorHandle) .add("layout", layout) .toString(); }
Source:
public boolean runWESCommand(String jsonString, File localPrimaryDescriptorFile, File zippedEntry) { try { String tags = "WorkflowExecutionService"; String jsonContent = null; try { jsonContent = new String(java.nio.file.Files.readAllBytes(Paths.get(jsonString)), StandardCharsets.UTF_8); } catch (IOException ioe) { ioe.printStackTrace(); } List<File> workflowAttachment = new ArrayList<>(); addFilesToWorkflowAttachment(workflowAttachment, this.zippedEntry); workflowAttachment.add(localPrimaryDescriptorFile); System.out.println("runWESCommand: json content is: " + jsonContent); System.out.println("runWESCommand: jsonString is: " + jsonString); System.out.println("runWESCommand: workflow absolute path is: " + localPrimaryDescriptorFile.getAbsolutePath()); String workflowURL = localPrimaryDescriptorFile.getName(); System.out.println("runWESCommand: workflow URI is: " + workflowURL); File jsonInputFile = new File(jsonString); workflowAttachment.add(jsonInputFile); for (int i = 0; i < workflowAttachment.size(); i++) { String str = new String(workflowAttachment.get(i).getName()); System.out.println("runWESCommand: workflow attachment " + i + " is: " + str); } RunId response = clientWorkflowExecutionServiceApi.runWorkflow(jsonInputFile, "CWL", "v1.0", tags, "", workflowURL, workflowAttachment); System.out.println("Launched WES run with id: " + response.toString()); } catch (io.swagger.wes.client.ApiException e) { e.printStackTrace(); return false; } return true; }

Target:
public void runWESCommand(String jsonString, File localPrimaryDescriptorFile, File zippedEntry) { String workflowURL = localPrimaryDescriptorFile.getName(); final File tempDir = Files.createTempDir(); List<File> workflowAttachment = new ArrayList<>(); addFilesToWorkflowAttachment(workflowAttachment, this.zippedEntry, tempDir); workflowAttachment.add(localPrimaryDescriptorFile); File jsonInputFile = new File(jsonString); workflowAttachment.add(jsonInputFile); String languageType = this.languageType.toString().toUpperCase(); String workflowTypeVersion = WORKFLOW_TYPE_VERSION; if ("CWL".equals(languageType.toUpperCase())) { workflowTypeVersion = "v" + WORKFLOW_TYPE_VERSION; } try { RunId response = clientWorkflowExecutionServiceApi.runWorkflow(jsonInputFile, languageType, workflowTypeVersion, TAGS, "", workflowURL, workflowAttachment); System.out.println("Launched WES run with id: " + response.toString()); } catch (io.swagger.wes.client.ApiException e) { LOG.error("Error launching WES run", e); } finally { try { FileUtils.deleteDirectory(tempDir); } catch (IOException ioe) { LOG.error("Could not delete temporary directory" + tempDir + " for workflow attachment files", ioe); } } }
Source:
private boolean checkFourLetterWord(final Channel channel, ChannelBuffer message, final int len) throws IOException { if (!FourLetterCommands.isKnown(len)) { return false; } String cmd = FourLetterCommands.getCommandString(len); if (!FourLetterCommands.isEnabled(cmd)) { LOG.debug("Command is not executed because it is not white listed.", cmd); return true; } channel.setInterestOps(0).awaitUninterruptibly(); LOG.info("Processing " + cmd + " command from " + channel.getRemoteAddress()); packetReceived(); final PrintWriter pwriter = new PrintWriter( new BufferedWriter(new SendBufferWriter())); if (len == FourLetterCommands.setTraceMaskCmd) { ByteBuffer mask = ByteBuffer.allocate(8); message.readBytes(mask); mask.flip(); long traceMask = mask.getLong(); ZooTrace.setTextTraceLevel(traceMask); SetTraceMaskCommand setMask = new SetTraceMaskCommand(pwriter, this, traceMask); setMask.start(); return true; } else { CommandExecutor commandExecutor = new CommandExecutor(); return commandExecutor.execute(this, pwriter, len, zkServer,factory); } }

Target:
private boolean checkFourLetterWord(final Channel channel, ChannelBuffer message, final int len) throws IOException { if (!FourLetterCommands.isKnown(len)) { return false; } String cmd = FourLetterCommands.getCommandString(len); channel.setInterestOps(0).awaitUninterruptibly(); packetReceived(); final PrintWriter pwriter = new PrintWriter( new BufferedWriter(new SendBufferWriter())); if (!FourLetterCommands.isEnabled(cmd)) { LOG.debug("Command is not executed because it is not in the whitelist.", cmd); NopCommand nopCmd = new NopCommand(pwriter, this, cmd + " is not executed because it is not in the whitelist."); nopCmd.start(); return true; } LOG.info("Processing " + cmd + " command from " + channel.getRemoteAddress()); if (len == FourLetterCommands.setTraceMaskCmd) { ByteBuffer mask = ByteBuffer.allocate(8); message.readBytes(mask); mask.flip(); long traceMask = mask.getLong(); ZooTrace.setTextTraceLevel(traceMask); SetTraceMaskCommand setMask = new SetTraceMaskCommand(pwriter, this, traceMask); setMask.start(); return true; } else { CommandExecutor commandExecutor = new CommandExecutor(); return commandExecutor.execute(this, pwriter, len, zkServer,factory); } }
Source:
public void checkOpenFileFeatureTest() throws Exception { createProject(PROJECT_NAME); projectExplorer.waitItem(PROJECT_NAME); dashboard.open(); dashboard.selectFactoriesOnDashbord(); dashboardFactories.clickOnAddFactoryBtn(); dashboardFactories.selectWorkspaceForCreation(testWorkspace.getName()); dashboardFactories.setFactoryName(FACTORY_NAME); dashboardFactories.clickOnCreateFactoryBtn(); dashboardFactories.selectAction(OPEN_FILE); dashboardFactories.enterParamValue(OPEN_FILE_URL); dashboardFactories.clickAddOnAddAction(); dashboardFactories.clickOnOpenFactory(); String currentWin = seleniumWebDriver.getWindowHandle(); seleniumWebDriver.switchToNoneCurrentWindow(currentWin); loadingBehaviorPage.waitWhileLoadPageIsClosed(); seleniumWebDriverHelper.switchFromDashboardAndWaitProjectExplorer(); projectExplorer.waitItem(PROJECT_NAME); editor.waitTabIsPresent("web-java-spring", ELEMENT_TIMEOUT_SEC); }

Target:
public void checkOpenFileFeatureTest() throws Exception { createProject(PROJECT_NAME); projectExplorer.waitItem(PROJECT_NAME); dashboard.open(); dashboard.selectFactoriesOnDashbord(); dashboardFactories.clickOnAddFactoryBtn(); dashboardFactories.selectWorkspaceForCreation(testWorkspace.getName()); dashboardFactories.setFactoryName(FACTORY_NAME); dashboardFactories.clickOnCreateFactoryBtn(); dashboardFactories.selectAction(OPEN_FILE); dashboardFactories.enterParamValue(OPEN_FILE_URL); dashboardFactories.clickAddOnAddAction(); dashboardFactories.clickOnOpenFactory(); String currentWin = seleniumWebDriver.getWindowHandle(); seleniumWebDriverHelper.switchToNextWindow(currentWin); loadingBehaviorPage.waitWhileLoadPageIsClosed(); seleniumWebDriverHelper.switchToIdeFrameAndWaitAvailability(); projectExplorer.waitItem(PROJECT_NAME); editor.waitTabIsPresent("web-java-spring", ELEMENT_TIMEOUT_SEC); }