auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Control createDialogArea(Composite parent) { parent.getShell().setText(TITLE); Composite composite = new Composite(parent, SWT.FULL_SELECTION); GridLayout layout = new GridLayout(1, false); composite.setLayout(layout); createViewer(composite); composite.pack(); return composite; }

Target:
protected Control createDialogArea(Composite parent) { getShell().setText(TITLE); Composite composite = (Composite) super.createDialogArea(parent); createViewer(composite); return composite; }
Source:
public void onResume() { super.onResume(); if (controller.needRefreshBookmarkedPictures()) { gridView.setVisibility(GONE); if (gridAdapter != null) { gridAdapter.clear(); ((CategoryImagesCallback) getContext()).viewPagerNotifyDataSetChanged(); } initList(); } }

Target:
public void onResume() { super.onResume(); if (controller.needRefreshBookmarkedPictures()) { gridView.setVisibility(GONE); if (gridAdapter != null) { gridAdapter.clear(); ((BookmarksActivity) getContext()).viewPagerNotifyDataSetChanged(); } initList(); } }
Source:
public List<String> getChildrenIds() { return session.getAllChildrenIds(id); }

Target:
public List<String> getChildrenIds() { return session.getChildrenIds(id); }
Source:
private static Set<String> getRootQualifiers(ResourceTypes resourceTypes) { return resourceTypes.getRoots().stream() .map(ResourceType::getQualifier) .filter(q -> !DEPRECATED_QUALIFIERS.contains(q)) .collect(Collectors.toCollection(TreeSet::new)); }

Target:
private static Set<String> getRootQualifiers(ResourceTypes resourceTypes) { return resourceTypes.getRoots().stream() .map(ResourceType::getQualifier) .collect(Collectors.toCollection(TreeSet::new)); }
Source:
public AutoCloseableLock lock(ByteArrayWrapper key) throws InterruptedException { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } KeyHashIdentifier lockKey = new KeyHashIdentifier(key.toBytes()); Lock lock = new ReentrantLock(); Lock oldLock = weakReferencesTolocks.putIfAbsent(lockKey, lock); if (oldLock != null) { lock = oldLock; lockKey = getReferenceToLockKey(lockKey); } if (!lock.tryLock(timeoutMS, TimeUnit.MILLISECONDS)) { throw new TimeoutException("Couldn't get lock for " + lockKey.toString()); } return new AutoCloseableLock(lockKey, lock); }

Target:
public AutoCloseableLock lock(ByteArrayWrapper key) throws InterruptedException { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } KeyHashIdentifier lockKey = new KeyHashIdentifier(key.toBytes()); KeyHashIdentifier referencedKey = lockKey; Lock lock = new ReentrantLock(); do { Lock oldLock = weakReferencesTolocks.putIfAbsent(lockKey, lock); if (oldLock != null) { lock = oldLock; referencedKey = getReferenceToLockKey(lockKey); } } while (referencedKey == null); if (!lock.tryLock(timeoutMS, TimeUnit.MILLISECONDS)) { throw new TimeoutException("Couldn't get lock for " + lockKey.toString()); } return new AutoCloseableLock(referencedKey, lock); }
Source:
public static void extractTarFile(String tarFileName, String targetFolder) throws Exception { Exception exception = null; byte[] buf = new byte[8192]; TarFile tarFile = null; try { tarFile = new TarFile(tarFileName); Enumeration<TarEntry> enumeration = tarFile.entries(); while (enumeration.hasMoreElements()) { TarEntry entry = enumeration.nextElement(); File file = new File(targetFolder, entry.getName()); if (entry.getFileType() == TarEntry.DIRECTORY) { if (!file.exists()) { file.mkdir(); } } else { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } InputStream zin = tarFile.getInputStream(entry); OutputStream fout = new FileOutputStream(file); File dir = file.getParentFile(); if (dir.isDirectory() && !dir.exists()) { dir.mkdirs(); } try { while (true) { int bytesRead = zin.read(buf); if (bytesRead == -1) { break; } fout.write(buf, 0, bytesRead); } fout.flush(); } catch (Exception e) { exception = e; return; } finally { zin.close(); fout.close(); } } } } catch (Exception e) { exception = e; } finally { try { tarFile.close(); } catch (IOException e) { } if (exception != null) { throw exception; } } }

Target:
public static void extractTarFile(String tarFileName, String targetFolder) throws Exception { Exception exception = null; byte[] buf = new byte[8192]; TarFile tarFile = null; try { tarFile = new TarFile(tarFileName); Enumeration<TarEntry> enumeration = tarFile.entries(); while (enumeration.hasMoreElements()) { TarEntry entry = enumeration.nextElement(); File file = new File(targetFolder, entry.getName()); if (entry.getFileType() == TarEntry.DIRECTORY) { if (!file.exists()) { file.mkdir(); } } else { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } InputStream zin = tarFile.getInputStream(entry); OutputStream fout = new FileOutputStream(file); File dir = file.getParentFile(); if (dir.isDirectory() && !dir.exists()) { dir.mkdirs(); } try { while (true) { int bytesRead = zin.read(buf); if (bytesRead == -1) { break; } fout.write(buf, 0, bytesRead); } fout.flush(); } catch (Exception e) { exception = e; return; } finally { if (zin != null) { try { zin.close(); } catch (Exception e) { } } if (fout != null) { try { fout.close(); } catch (Exception e) { } } } } } } catch (Exception e) { exception = e; } finally { if (tarFile != null) { try { tarFile.close(); } catch (IOException e) { } } if (exception != null) { throw exception; } } }
Source:
public void testGetPartitionSplitsTableNotReadablePartition() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableNotReadable); assertNotNull(tableHandle); ColumnHandle dsColumn = metadata.getColumnHandles(session, tableHandle).get("ds"); assertNotNull(dsColumn); Domain domain = Domain.singleValue(createUnboundedVarcharType(), utf8Slice("2012-12-30")); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of(dsColumn, domain)); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, new Constraint<>(tupleDomain, bindings -> true), Optional.empty()); try { getSplitCount(splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle())); fail("Expected PartitionOfflineException"); } catch (HiveNotReadableException e) { assertEquals(e.getTableName(), tableNotReadable); assertEquals(e.getPartition(), Optional.empty()); } } }

Target:
public void testGetPartitionSplitsTableNotReadablePartition() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableNotReadable); assertNotNull(tableHandle); ColumnHandle dsColumn = metadata.getColumnHandles(session, tableHandle).get("ds"); assertNotNull(dsColumn); Domain domain = Domain.singleValue(createUnboundedVarcharType(), utf8Slice("2012-12-30")); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of(dsColumn, domain)); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, new Constraint<>(tupleDomain, bindings -> true), Optional.empty()); try { getSplitCount(splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING)); fail("Expected HiveNotReadableException"); } catch (HiveNotReadableException e) { assertEquals(e.getMessage(), "Table 'default.presto_test_not_readable' is not readable: reason for not readable"); assertEquals(e.getTableName(), tableNotReadable); assertEquals(e.getPartition(), Optional.empty()); } } }
Source:
public boolean isDiscontinued(Date checkDate) { if (dateStopped != null && autoExpireDate != null && dateStopped.after(autoExpireDate)) { throw new APIException("Order.error.invalidDateStoppedAndAutoExpireDate", (Object[]) null); } if (isVoided()) { return false; } if (checkDate == null) { checkDate = new Date(); } if (dateActivated == null || !isActivated(checkDate) || dateStopped == null) { return false; } return checkDate.after(dateStopped); }

Target:
public boolean isDiscontinued(Date checkDate) { if (dateStopped != null && autoExpireDate != null && dateStopped.after(autoExpireDate)) { throw new APIException("Order.error.invalidDateStoppedAndAutoExpireDate", (Object[]) null); } if (isVoided()) { return false; } if (checkDate == null) { checkDate = new Date(); } if (!isActivated(checkDate) || dateStopped == null) { return false; } return checkDate.after(dateStopped); }
Source:
private void putLightOnOff(String message) { coapClient.setURI( "coap://" + COAP_SERVER_IP_ADDRESS + ":" + COAP_SERVER_PORT + "/InternetOfTiny/actuators/actuator1"); StringBuilder coapLightSwitch = new StringBuilder(); if (message.compareTo("ON") == 0) { coapLightSwitch.append(",1,pp,100,"); } else if (message.compareTo("OFF") == 0) { coapLightSwitch.append(",1,pp,0,"); } CoapResponse clientResponse = coapClient.put(coapLightSwitch.toString(), TEXT_PLAIN); logger.debug(clientResponse.advanced().getSource().toString()); }

Target:
private void putLightOnOff(String message) { coapClient .setURI("coap://" + coapServerIpAddress + ":" + coapServerPort + "/InternetOfTiny/actuators/actuator1"); String coapLightSwitch; if (message.equals("ON")) { coapLightSwitch = new String(",1,pp,100,"); } else if (message.equals("OFF")) { coapLightSwitch = new String(",1,pp,0,"); } else { coapLightSwitch = new String(""); } if (!coapLightSwitch.isEmpty()) { CoapResponse clientResponse = coapClient.put(coapLightSwitch, TEXT_PLAIN); logger.debug(clientResponse.advanced().getSource().toString()); } }
Source:
public static String strictSanitize(String original) { return strictSanitizer.apply(original); }

Target:
public static String strictSanitize(String original) { return STRICT_SANITIZER.sanitize(original); }
Source:
public String get(final String key) { String language = (String) (null != request && null != request.getSession()? request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE):null); if (language == null) { language = String.valueOf(langAPI.getDefaultLanguage().getId()); } return get(key, language); }

Target:
public String get(final String key) { Language foundLanguage = WebAPILocator.getLanguageWebAPI().getLanguage(request); return get(key, String.valueOf(foundLanguage.getId())); }
Source:
private boolean isVmUsingScsiReservation() { List<VmDevice> devices = getDbFacade().getVmDeviceDao().getVmDeviceByVmIdAndType(getVmId(), VmDeviceGeneralType.DISK); for (VmDevice device : devices) { if (device.getIsPlugged() && device.isUsingScsiReservation()) { return true; } } return false; }

Target:
private boolean isVmUsingScsiReservation() { List<VmDevice> devices = getVmDeviceDao().getVmDeviceByVmIdAndType(getVmId(), VmDeviceGeneralType.DISK); for (VmDevice device : devices) { if (device.getIsPlugged() && device.isUsingScsiReservation()) { return true; } } return false; }
Source:
public Boolean run() { if (!isAdministrator()) { return Boolean.FALSE; } long start = System.currentTimeMillis(); WorkManager workManager = Framework.getService(WorkManager.class); AuditLogger auditLogger = Framework.getService(AuditLogger.class); boolean waitForAuditStoredInEs = waitForAudit && Framework.isBooleanPropertyTrue(AUDIT_ELASTICSEARCH_ENABLED); try { if (!workManager.awaitCompletion(timeout, TimeUnit.SECONDS)) { throw new TimeoutException(); } if (waitForAuditStoredInEs && !auditLogger.await(computeRemainingTime(start), TimeUnit.SECONDS)) { throw new TimeoutException(); } esa.prepareWaitForIndexing().get(computeRemainingTime(start), TimeUnit.SECONDS); } catch (TimeoutException | InterruptedException | ExecutionException e) { if (ExceptionUtils.hasInterruptedCause(e)) { Thread.currentThread().interrupt(); } return Boolean.FALSE; } if (refresh) { esa.refreshRepositoryIndex(repo.getRepositoryName()); if (waitForAuditStoredInEs) { esa.getClient().refresh(esa.getIndexNameForType(ElasticSearchConstants.ENTRY_TYPE)); } } return Boolean.TRUE; }

Target:
public Boolean run() { long start = System.currentTimeMillis(); WorkManager workManager = Framework.getService(WorkManager.class); AuditLogger auditLogger = Framework.getService(AuditLogger.class); boolean waitForAuditStoredInEs = waitForAudit && Framework.isBooleanPropertyTrue(AUDIT_ELASTICSEARCH_ENABLED); try { if (!workManager.awaitCompletion(timeout, TimeUnit.SECONDS)) { throw new TimeoutException(); } if (waitForAuditStoredInEs && !auditLogger.await(computeRemainingTime(start), TimeUnit.SECONDS)) { throw new TimeoutException(); } esa.prepareWaitForIndexing().get(computeRemainingTime(start), TimeUnit.SECONDS); } catch (TimeoutException | InterruptedException | ExecutionException e) { if (ExceptionUtils.hasInterruptedCause(e)) { Thread.currentThread().interrupt(); } return Boolean.FALSE; } if (refresh) { esa.refreshRepositoryIndex(repo.getRepositoryName()); if (waitForAuditStoredInEs) { esa.getClient().refresh(esa.getIndexNameForType(ElasticSearchConstants.ENTRY_TYPE)); } } return Boolean.TRUE; }
Source:
static public void println() { synchronized (histories) { if (skipReport()) return; System.out.print("Statistics: "); for (Map.Entry<Tag, History> entry : histories.entrySet()) { Tag tag = entry.getKey(); History history = entry.getValue(); System.out.print(tag + "Cnt " + history.cnt + " "); System.out.print(tag + "Sum " + history.total + " "); System.out.print(tag + "Avg " + (float) history.total / history.cnt + " "); } System.out.println(); } }

Target:
static public void println() { if(!LOG.isDebugEnabled()) return; synchronized (histories) { if (skipReport()) return; StringBuffer tobelogged = new StringBuffer("Statistics: "); for (Map.Entry<Tag, History> entry : histories.entrySet()) { Tag tag = entry.getKey(); History history = entry.getValue(); tobelogged.append(tag + "Cnt " + history.cnt + " "); tobelogged.append(tag + "Sum " + history.total + " "); tobelogged.append(tag + "Avg " + (float) history.total / history.cnt + " "); } LOG.debug(tobelogged); } }
Source:
public void testVcfSorted(final boolean disableSort) { final File liftOutputFile = new File(OUTPUT_DATA_PATH, "lift-delete-me.vcf"); final File rejectOutputFile = new File(OUTPUT_DATA_PATH, "reject-delete-me.vcf"); final File input = new File(TEST_DATA_PATH, "testLiftoverBiallelicIndels.vcf"); liftOutputFile.deleteOnExit(); rejectOutputFile.deleteOnExit(); final String[] args = new String[]{ "INPUT=" + input.getAbsolutePath(), "OUTPUT=" + liftOutputFile.getAbsolutePath(), "REJECT=" + rejectOutputFile.getAbsolutePath(), "CHAIN=" + CHAIN_FILE, "REFERENCE_SEQUENCE=" + REFERENCE_FILE, "CREATE_INDEX=" + (!disableSort), "DISABLE_SORT=" + disableSort }; Assert.assertEquals(runPicardCommandLine(args), 0); try (final VCFFileReader liftReader = new VCFFileReader(liftOutputFile, !disableSort)) { final VCFHeader header = liftReader.getFileHeader(); Assert.assertNotNull(header.getOtherHeaderLine("reference")); try (final CloseableIterator<VariantContext> iter = liftReader.iterator()) { Assert.assertEquals(iter.stream().count(), 5L); } } }

Target:
public void testVcfSorted(final boolean disableSort) { final File liftOutputFile = new File(OUTPUT_DATA_PATH, "lift-delete-me.vcf"); final File rejectOutputFile = new File(OUTPUT_DATA_PATH, "reject-delete-me.vcf"); final File input = new File(TEST_DATA_PATH, "testLiftoverBiallelicIndels.vcf"); liftOutputFile.deleteOnExit(); rejectOutputFile.deleteOnExit(); final String[] args = new String[]{ "INPUT=" + input.getAbsolutePath(), "OUTPUT=" + liftOutputFile.getAbsolutePath(), "REJECT=" + rejectOutputFile.getAbsolutePath(), "CHAIN=" + CHAIN_FILE, "REFERENCE_SEQUENCE=" + REFERENCE_FILE, "CREATE_INDEX=" + (!disableSort), "DISABLE_SORT=" + disableSort }; Assert.assertEquals(runPicardCommandLine(args), 0); try (final VCFFileReader inputReader = new VCFFileReader(input, false)) { final VCFHeader header = inputReader.getFileHeader(); Assert.assertNull(header.getOtherHeaderLine("reference")); } try (final VCFFileReader liftReader = new VCFFileReader(liftOutputFile, !disableSort)) { final VCFHeader header = liftReader.getFileHeader(); Assert.assertNotNull(header.getOtherHeaderLine("reference")); try (final CloseableIterator<VariantContext> iter = liftReader.iterator()) { Assert.assertEquals(iter.stream().count(), 5L); } } }
Source:
public IFileInfo getFileInfo(IFileStore store) { ICVSRemoteFolder folder=null; String resourceName = null; CVSURI cvsUri = CVSURI.fromUri(store.toURI()); folder = cvsUri.getParentFolder(); resourceName = cvsUri.getLastSegment(); if (folder.getName().equals(ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME)) { FileInfo info = new FileInfo(); info.setExists(true); info.setName(resourceName); info.setDirectory(true); return info; } try { RemoteFolderTree remoteFolder = (RemoteFolderTree) remoteFolders.get(folder.getName()); if (remoteFolder == null){ String repoPath = folder.getRepositoryRelativePath(); IPath repoPath2 = new Path(repoPath); repoPath2 = repoPath2.removeFirstSegments(1); remoteFolder = (RemoteFolderTree) remoteFolders.get(repoPath2.toString()); } if (remoteFolder == null) remoteFolder = remoteTree; ICVSRemoteResource[] children =remoteFolder.getChildren(); ICVSResource resource = null; for (ICVSRemoteResource c : children) { ICVSResource child = c; if (child.getName().equals(resourceName)) { resource = child; break; } } return getFileInfo(resource, new NullProgressMonitor()); } catch (CoreException e) { CVSProviderPlugin.log(e); return null; } }

Target:
public IFileInfo getFileInfo(IFileStore store) { ICVSRemoteFolder folder=null; String resourceName = null; CVSURI cvsUri = CVSURI.fromUri(store.toURI()); folder = cvsUri.getParentFolder(); resourceName = cvsUri.getLastSegment(); if (folder.getName().equals(ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME)) { FileInfo info = new FileInfo(); info.setExists(true); info.setName(resourceName); info.setDirectory(true); return info; } try { RemoteFolderTree remoteFolder = (RemoteFolderTree) remoteFolders.get(folder.getName()); if (remoteFolder == null){ String repoPath = folder.getRepositoryRelativePath(); IPath repoPath2 = new Path(repoPath); repoPath2 = repoPath2.removeFirstSegments(1); remoteFolder = (RemoteFolderTree) remoteFolders.get(repoPath2.toString()); } if (remoteFolder == null) remoteFolder = remoteTree; ICVSRemoteResource[] children =remoteFolder.getChildren(); ICVSResource resource = null; for (ICVSRemoteResource child : children) { if (child.getName().equals(resourceName)) { resource = child; break; } } return getFileInfo(resource, new NullProgressMonitor()); } catch (CoreException e) { CVSProviderPlugin.log(e); return null; } }
Source:
public Message sign$getLine(int index) throws IndexOutOfBoundsException { if(index > signText.length) throw new IndexOutOfBoundsException(); return SpongeMessage.of(signText[index]); }

Target:
public Message sign$getLine(int index) throws IndexOutOfBoundsException { checkElementIndex(index, signText.length); return SpongeMessage.of(signText[index]); }
Source:
public static void inspectGcsFile() throws InterruptedException, ExecutionException, IOException { String projectId = "your-project-id"; String gcsUri = "gs://" + "your-bucket-name" + "/path/to/your/test.txt"; String pubSubTopicId = "your-pubsub-topic-id"; String pubSubSubscriptionId = "your-pubsub-subscription-id"; inspectGcsFile(projectId, gcsUri, pubSubTopicId, pubSubSubscriptionId); }

Target:
public static void inspectGcsFile() throws InterruptedException, ExecutionException, IOException { String projectId = "your-project-id"; String gcsUri = "gs://" + "your-bucket-name" + "/path/to/your/file.txt"; String pubSubTopicId = "your-pubsub-topic-id"; String pubSubSubscriptionId = "your-pubsub-subscription-id"; inspectGcsFile(projectId, gcsUri, pubSubTopicId, pubSubSubscriptionId); }
Source:
public static <R extends Product> QuantityTrade.Builder<R> builder(Security<R> security) { return QuantityTrade.<R>builder().securityLink(SecurityLink.resolved(security)); }

Target:
public static <R extends Product> QuantityTrade.Builder<R> builder(Security<R> security) { return QuantityTrade.builder(SecurityLink.resolved(security)); }
Source:
public void deleteScope(ScopeEvent event) { Scope scope = new Scope(); scope.setName(event.getName()); scope.setTimeStamp(event.getTimeStamp()); SubscriptionDataStore store = SubscriptionDataHolder.getInstance() .getTenantSubscriptionStore(event.getTenantDomain()); if (store == null) { if (log.isDebugEnabled()) { log.debug("Ignoring the Event due to tenant " + event.getTenantDomain() + " not loaded"); } return; } store.deleteScope(scope); }

Target:
public void deleteScope(ScopeEvent event) { Scope scope = new Scope(); scope.setName(event.getName()); scope.setTimeStamp(event.getTimeStamp()); SubscriptionDataStore store = SubscriptionDataHolder.getInstance() .getTenantSubscriptionStore(event.getTenantDomain()); if (store == null) { if (log.isDebugEnabled()) { log.debug("Ignoring the event as the tenant " + event.getTenantDomain() + " is not loaded"); } return; } store.deleteScope(scope); }
Source:
public boolean shouldRun() { final boolean shouldRun = pendingPartitions != null && pendingPartitions.size() > 0; return shouldRun; }

Target:
public boolean shouldRun() { final boolean shouldRun = pendingPartitions.size() > 0; return shouldRun; }
Source:
public void levelLost() { stop(); addToLog("[GAME}\t[LOST]\tYou just lost the game, kind of."); loadCurrentLevel(); }

Target:
public void levelLost() { stop(); gameOver(); addToLog("[GAME]\t[LOST]\tYou just lost the game, kind of."); }
Source:
public void updateAsync(T value, Executor executor) { if (!running) throw new IllegalLifecycleStateException(); lastValue = Objects.requireNonNull(value); try { executor.execute(() -> checkConditions(value)); } catch (Throwable t) { for (Data data : futures.values()) { data.cancelFuture.cancel(false); data.completeExceptionally(t); } } }

Target:
public void updateAsync(T value, Executor executor) { if (!running) throw new IllegalLifecycleStateException(); lastValue = Objects.requireNonNull(value); try { executor.execute(() -> checkConditions(value)); } catch (Throwable t) { List<CompletableFuture<?>> completed; synchronized (futures) { completed = new ArrayList<>(futures.size()); for (Data data : futures.values()) { data.cancelFuture.cancel(false); completed.add(data); } } for (CompletableFuture<?> future : completed) { future.completeExceptionally(t); } } }
Source:
public void start() throws Exception { if (!clusteringService.isOpen()) { throw new IllegalStateException("The clustering service has not been started"); } localJournal.start(); long lastChangeSetTime = -1; Records allLocalRecords = localJournal.allRecords(true); if (allLocalRecords.size() > 0) { lastChangeSetTime = allLocalRecords.iterator().next().getChangeTimeMillisUTC(); } clusteringService.addConsumer(this); if (clusteringService.multipleMembersInCluster()) { deltaReconciliationCompleted.set(false); this.expectedNumberOfDeltaResponses.compareAndSet(0, clusteringService.membersInCluster() - 1); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending delta request from journal {0} as part of cluster {1}", journalId(), clusterName()); } clusteringService.sendMessage(DeltaMessage.request(journalId(), lastChangeSetTime)); waitForReconciliationToComplete(); } else { this.deltaReconciliationCompleted.set(true); } }

Target:
public void start() throws Exception { if (!clusteringService.isOpen()) { throw new IllegalStateException("The clustering service has not been started"); } localJournal.start(); clusteringService.addConsumer(this); if (clusteringService.multipleMembersInCluster()) { int numberOfExpectedResponses = clusteringService.membersInCluster() - 1; reconciliationLatch = new CountDownLatch(numberOfExpectedResponses); this.expectedNumberOfDeltaResponses.compareAndSet(0, numberOfExpectedResponses); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending delta request from journal {0} as part of cluster {1}", journalId(), clusterName()); } JournalRecord lastRecord = lastRecord(); DateTime lastChangeSetTimeMillis = lastRecord != null ? new DateTime(lastRecord.getChangeTimeMillis()) : null; clusteringService.sendMessage(DeltaMessage.request(journalId(), lastChangeSetTimeMillis)); waitForReconciliationToComplete(); } else { this.reconciliationLatch = new CountDownLatch(0); } }
Source:
public <T extends Entity> T createEntityProxy(EntitySpec<T> spec, T entity) { MutableSet.Builder<Class<?>> builder = MutableSet.<Class<?>>builder() .add(EntityProxy.class, Entity.class, EntityLocal.class, EntityInternal.class); if (spec.getType().isInterface()) { builder.add(spec.getType()); } else { log.warn("EntitySpec declared in terms of concrete type "+spec.getType()+"; should be supplied in terms of interface"); } builder.addAll(spec.getAdditionalInterfaces()); Set<Class<?>> interfaces = builder.build(); AggregateClassLoader aggregateClassLoader = AggregateClassLoader.newInstanceWithNoLoaders(); aggregateClassLoader.addFirst(entity.getClass().getClassLoader()); for(Class<?> iface : interfaces) { aggregateClassLoader.addLast(iface.getClassLoader()); } return (T) java.lang.reflect.Proxy.newProxyInstance( aggregateClassLoader, interfaces.toArray(new Class[interfaces.size()]), new EntityProxyImpl(entity)); }

Target:
public <T extends Entity> T createEntityProxy(EntitySpec<T> spec, T entity) { MutableSet.Builder<Class<?>> builder = MutableSet.<Class<?>>builder() .add(EntityProxy.class, Entity.class, EntityLocal.class, EntityInternal.class); if (spec.getType().isInterface()) { builder.add(spec.getType()); } else { log.warn("EntitySpec declared in terms of concrete type "+spec.getType()+"; should be supplied in terms of interface"); } builder.addAll(spec.getAdditionalInterfaces()); Set<Class<?>> interfaces = builder.build(); Collection<ClassLoader> loaders = Sets.newLinkedHashSet(); addClassLoaders(entity.getClass(), loaders); for(Class<?> iface : interfaces) { loaders.add(iface.getClassLoader()); } AggregateClassLoader aggregateClassLoader = AggregateClassLoader.newInstanceWithNoLoaders(); for (ClassLoader cl : loaders) { aggregateClassLoader.addLast(cl); } return (T) java.lang.reflect.Proxy.newProxyInstance( aggregateClassLoader, interfaces.toArray(new Class[interfaces.size()]), new EntityProxyImpl(entity)); }
Source:
protected void runNow(String ruleUID, boolean considerConditions){ RuntimeRule rule = getRuntimeRule(ruleUID); if (rule == null) { logger.warn("Fail to execute rule '{}': {}", ruleUID, "Invalid Rule UID."); return; } synchronized (this) { final RuleStatus ruleStatus = getRuleStatus(ruleUID); if (ruleStatus != RuleStatus.IDLE) { logger.error("Failed to execute rule ‘{}' with status '{}'", ruleUID, ruleStatus.name()); return; } setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.RUNNING),true); } try { clearContext(rule); if (considerConditions) { if (calculateConditions(rule)) { executeActions(rule, false); } } else { executeActions(rule, false); } logger.debug("The rule '{}' is executed.", ruleUID); } catch (Throwable t) { logger.error("Fail to execute rule '{}': {}", new Object[] { ruleUID, t.getMessage() }, t); } synchronized (this) { if (getRuleStatus(ruleUID) == RuleStatus.RUNNING) { setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.IDLE),true); } } }

Target:
protected void runNow(String ruleUID, boolean considerConditions) { RuntimeRule rule = getRuntimeRule(ruleUID); if (rule == null) { logger.warn("Failed to execute rule '{}': Invalid Rule UID", ruleUID); return; } synchronized (this) { final RuleStatus ruleStatus = getRuleStatus(ruleUID); if (ruleStatus != RuleStatus.IDLE) { logger.error("Failed to execute rule ‘{}' with status '{}'", ruleUID, ruleStatus.name()); return; } setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.RUNNING), true); } try { clearContext(rule); if (considerConditions) { if (calculateConditions(rule)) { executeActions(rule, false); } } else { executeActions(rule, false); } logger.debug("The rule '{}' is executed.", ruleUID); } catch (Throwable t) { logger.error("Fail to execute rule '{}': {}", new Object[] { ruleUID, t.getMessage() }, t); } synchronized (this) { if (getRuleStatus(ruleUID) == RuleStatus.RUNNING) { setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.IDLE), true); } } }
Source:
private void processSignal(Signal signal) { logger.debug("Processing signal: {}", signal); switch (signal.getType()) { case START: start(signal.getTarget(), signal.getPayload()); break; case RETRANSMIT: process(signal).accept(signal); break; case UPDATE_SUBSCRIPTION: case UPDATE_TOPIC: process(signal).accept(signal); break; case RESTART: case KILL_RESTART: kill(process(signal)); taskQueue.offer(Signal.of(Signal.SignalType.START, signal.getTarget())); break; case STOP: process(signal).accept(signal); taskQueue.offer(Signal.of(Signal.SignalType.CLEANUP, signal.getTarget())); break; case CLEANUP: cleanup(process(signal)); break; default: break; } }

Target:
private void processSignal(Signal signal) { try { logger.debug("Processing signal: {}", signal); metrics.counter("supervisor.signal." + signal.getType().name()).inc(); switch (signal.getType()) { case START: start(signal.getTarget(), signal.getPayload()); break; case RETRANSMIT: process(signal).accept(signal); break; case UPDATE_SUBSCRIPTION: case UPDATE_TOPIC: process(signal).accept(signal); break; case RESTART: case KILL_RESTART: Consumer consumer = process(signal).getConsumer(); kill(process(signal)); taskQueue.offer(Signal.of(Signal.SignalType.START, signal.getTarget(), consumer)); break; case STOP: process(signal).accept(signal); taskQueue.offer(Signal.of(Signal.SignalType.CLEANUP, signal.getTarget())); break; case CLEANUP: cleanup(process(signal)); break; default: break; } } catch (Exception exception) { logger.error("Supervisor failed to process signal {}", signal, exception); } }
Source:
public void validateFindingNotificationId() { String notificationURI = "<LINK_0>"; String expectedNotifcationId = "gWu2zdPNXG6oQHp0VDaEmNn77NGJ5aQ9rww"; String actualNotificationId = concurEventNotificationServiceImpl.findNotificationId(notificationURI); assertEquals("Expeted NotificationId and ActualNotificationId should be the same", expectedNotifcationId, actualNotificationId); }

Target:
public void validateFindingNotificationId() { String notificationURI = "<LINK_0>"; String expectedNotifcationId = "gWu2zdPNXG6oQHp0VDaEmNn77NGJ5aQ9rww"; String actualNotificationId = concurEventNotificationServiceImpl.findNotificationId(notificationURI); assertEquals("Expected NotificationId and ActualNotificationId should be the same", expectedNotifcationId, actualNotificationId); }
Source:
public void validateEmail(final String token, final AsyncCallback<VoidResult> callback) { try { final ValidToken t = authConfig.getEmailRegistrationToken().checkToken(token, null); if (t == null || t.getData() == null || "".equals(t.getData())) { callback.onFailure(new IllegalStateException("Invalid token")); return; } final String newEmail = new String(Base64.decode(t.getData()), "UTF-8"); accountManager.link(user.get().getAccountId(), AuthRequest .forEmail(newEmail)); callback.onSuccess(VoidResult.INSTANCE); } catch (XsrfException e) { callback.onFailure(e); } catch (UnsupportedEncodingException e) { callback.onFailure(e); } catch (AccountException e) { callback.onFailure(e); } }

Target:
public void validateEmail(final String token, final AsyncCallback<VoidResult> callback) { try { final ValidToken t = authConfig.getEmailRegistrationToken().checkToken(token, null); if (t == null || t.getData() == null || "".equals(t.getData())) { callback.onFailure(new IllegalStateException("Invalid token")); return; } final String newEmail = new String(Base64.decode(t.getData()), "UTF-8"); if (!newEmail.contains("@")) { callback.onFailure(new IllegalStateException("Invalid token")); return; } accountManager.link(user.get().getAccountId(), AuthRequest .forEmail(newEmail)); callback.onSuccess(VoidResult.INSTANCE); } catch (XsrfException e) { callback.onFailure(e); } catch (UnsupportedEncodingException e) { callback.onFailure(e); } catch (AccountException e) { callback.onFailure(e); } }
Source:
private static void checkPrint( @NotNull ProblemsHolder holder, @NotNull GoCallExpr callExpr, @NotNull GoFunctionOrMethodDeclaration declaration) { List<GoExpression> arguments = callExpr.getArgumentList().getExpressionList(); if (arguments.isEmpty()) return; GoExpression firstArg = arguments.get(0); if (GoTypeUtil.isString(firstArg.getGoType(null))) { String firstArgText = GoPlaceholderChecker.resolve(firstArg); if (firstArgText != null) { if (GoPlaceholderChecker.hasPlaceholder(firstArgText)) { String message = "Possible formatting directive in <code>#ref</code>"; holder.registerProblem(firstArg, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } } } String declarationName = declaration.getName(); boolean isLn = declarationName != null && declarationName.endsWith("ln"); for (GoExpression argument : arguments) { GoType goType = argument.getGoType(null); if (isLn && GoTypeUtil.isString(goType)) { String argText = GoPlaceholderChecker.resolve(argument); if (argText != null && argText.endsWith("\\n")) { String message = "Function already ends with new line"; holder.registerProblem(argument, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } else if (GoTypeUtil.isFunction(goType)) { String message = "Argument <code>#ref</code> is not a function call"; if (argument instanceof GoCallExpr) { message = "Final return type of <code>#ref</code> is a function not a function call"; } holder.registerProblem(argument, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } }

Target:
private static void checkPrint(@NotNull ProblemsHolder holder, @NotNull GoCallExpr callExpr, @NotNull GoFunctionOrMethodDeclaration declaration) { List<GoExpression> arguments = callExpr.getArgumentList().getExpressionList(); if (arguments.isEmpty()) return; GoExpression firstArg = arguments.get(0); if (GoTypeUtil.isString(firstArg.getGoType(null))) { String firstArgText = resolve(firstArg); if (firstArgText != null) { if (GoPlaceholderChecker.hasPlaceholder(firstArgText)) { String message = "Possible formatting directive in <code>#ref</code> #loc"; holder.registerProblem(firstArg, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } } } String declarationName = declaration.getName(); boolean isLn = declarationName != null && declarationName.endsWith("ln"); for (GoExpression argument : arguments) { GoType goType = argument.getGoType(null); if (isLn && GoTypeUtil.isString(goType)) { String argText = resolve(argument); if (argText != null && argText.endsWith("\\n")) { String message = "Function already ends with new line #loc"; TextRange range = TextRange.create(argText.length() - 1, argText.length() + 1); holder.registerProblem(argument, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, range); } } else if (GoTypeUtil.isFunction(goType)) { String message = "Argument <code>#ref</code> is not a function call #loc"; if (argument instanceof GoCallExpr) { message = "Final return type of <code>#ref</code> is a function not a function call #loc"; } holder.registerProblem(argument, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } }
Source:
public String getImage(ImageName name) { return u("images/%s/get", name.getNameWithoutTag()) .build(); }

Target:
public String getImage(ImageName name) { return u("images/%s/get", name.getFullName()) .build(); }
Source:
public void updateWith(Speaker speaker) { final URI speakerPic = speaker.getPic(); if (speakerPic != null) { imageLoader.load(speakerPic.toString(), avatar); } else { avatar.setImageResource(R.drawable.ic_nav_schedule); } name.setText(speaker.getName()); jobTitle.setText(speaker.getCompany()); }

Target:
public void updateWith(Speaker speaker) { setSpeakerPicture(speaker.getPic()); name.setText(speaker.getName()); jobTitle.setText(speaker.getCompany()); }
Source:
public void setVisible (boolean visible) { checkWidget(); Canvas canvas = getParent(); canvas.setBlink(true); canvas.drawFlag = visible; getDisplay().resetCaretTiming(); if (visible == isVisible) return; isVisible = visible; if (!isFocusCaret ()) return; if (isVisible) { showCaret (); } else { hideCaret (); } }

Target:
public void setVisible (boolean visible) { checkWidget(); Canvas canvas = getParent(); canvas.blink = true; canvas.drawFlag = visible; getDisplay().resetCaretTiming(); if (visible == isVisible) return; isVisible = visible; if (!isFocusCaret ()) return; if (isVisible) { showCaret (); } else { hideCaret (); } }
Source:
public TerminalPopupMenu(TerminalList terminals) { super(); RStudioGinjector.INSTANCE.injectMembers(this); terminals_ = terminals; }

Target:
public TerminalPopupMenu(TerminalList terminals) { RStudioGinjector.INSTANCE.injectMembers(this); terminals_ = terminals; }
Source:
public void reload(final Injector injector) { _periodicMetrics.recordCounter("cached_job_reload", 1); final Optional<Job<T>> loaded = _ref.get(injector); if (!loaded.isPresent()) { throw new NoSuchElementException(_ref.toString()); } _cached = loaded.get(); _lastRun = _ref.getRepository(injector).getLastRun(_ref.getJobId(), _ref.getOrganization()); }

Target:
public void reload(final Injector injector) throws NoSuchJobException { final Optional<Job<T>> loaded = _ref.get(injector); if (!loaded.isPresent()) { _periodicMetrics.recordCounter("cached_job_reload_success", 0); throw new NoSuchJobException(_ref.toString()); } _periodicMetrics.recordCounter("cached_job_reload_success", 1); _cached = loaded.get(); _lastRun = _ref.getRepository(injector).getLastRun(_ref.getJobId(), _ref.getOrganization()); }
Source:
protected void dispose() { ReentrantReadWriteLock.WriteLock lock = this.lock.writeLock(); lock.lock(); try { referenceCount--; if (referenceCount <= 0) { LifecycleUtil.dispose(wrapped); wrapped = null; } } finally { lock.unlock(); } }

Target:
private void dispose() { ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); writeLock.lock(); try { referenceCount--; if (referenceCount <= 0) { LifecycleUtil.dispose(wrapped); wrapped = null; } } finally { writeLock.unlock(); } }
Source:
public void removeProcessedGroupingRequests() { Iterator<Entry<String, GroupingRequest>> itr = groupingRequests.entrySet().iterator(); while (itr.hasNext()) { Entry<String, GroupingRequest> request = itr.next(); if (request.getValue().isProcessed()) { LOG.debug("Removing Grouping request for :" + request.getKey()); itr.remove(); } } }

Target:
public void removeProcessedGroupingRequests() { Iterator<Entry<String, GroupingRequest>> itr = groupingRequests.entrySet().iterator(); while (itr.hasNext()) { Entry<String, GroupingRequest> entry = itr.next(); if (entry.getValue().isProcessed()) { LOG.debug("Removing Grouping request for : {}", entry.getKey()); itr.remove(); } } }
Source:
public <C extends Credential> C getCredential(Class<C> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { if (BearerTokenCredential.class.equals(credentialType)) { try { HttpRequest request = HttpClient.builder().sslContext(resolveSSLContext()).build() .post(tokenEndpointUri.toURL()) .param("grant_type", grantType); clientAuthenticator.accept(request); if (scopes != null) { request.param("scope", scopes); } return request.execute((inputStream, throwable) -> { if (throwable != null) { throw log.httpClientUnexpectedResponseFromServer(throwable); } JsonObject jsonObject = Json.createReader(inputStream).readObject(); String accessToken = jsonObject.getString("access_token"); return (C) new BearerTokenCredential(accessToken); }); } catch (Exception cause) { throw log.mechCallbackHandlerFailedForUnknownReason("OAuth2 Credentials Grant Type", cause); } } return null; }

Target:
public <C extends Credential> C getCredential(Class<C> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { if (credentialType.isAssignableFrom(credentialType)) { try { HttpURLConnection connection = null; try { connection = openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); HashMap<String, String> parameters = new HashMap<>(); parameters.put("grant_type", grantType); consumer.accept(parameters); if (scopes != null) { parameters.put("scope", scopes); } byte[] paramBytes = buildParameters(parameters); try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(paramBytes); } try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) { JsonObject jsonObject = Json.createReader(inputStream).readObject(); String accessToken = jsonObject.getString("access_token"); return credentialType.cast(new BearerTokenCredential(accessToken)); } } catch (IOException ioe) { InputStream errorStream = null; if (connection != null && connection.getErrorStream() != null) { errorStream = connection.getErrorStream(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) { StringBuffer response = reader.lines().reduce(new StringBuffer(), StringBuffer::append, (buffer1, buffer2) -> buffer1); log.errorf(ioe, "Unexpected response from server [%s]. Response: [%s]", tokenEndpointUri, response); } catch (IOException ignore) { } } throw log.mechUnableToHandleResponseFromServer("OAuth2CredentialSource", ioe); } } catch (Exception cause) { throw log.mechCallbackHandlerFailedForUnknownReason("OAuth2CredentialSource", cause); } } return null; }
Source:
public synchronized KafkaPositionTracker build() { if (_built) { throw new IllegalStateException("Builder already used"); } _built = true; return new KafkaPositionTracker(_datastreamTaskPrefix, _datastreamTaskName, _connectorTaskStartTime, _enableBrokerOffsetFetcher, _isConnectorTaskAlive, _consumerSupplier); }

Target:
public KafkaPositionTracker build() { return new KafkaPositionTracker(_datastreamTaskPrefix, _datastreamTaskName, _connectorTaskStartTime, _enableBrokerOffsetFetcher, _isConnectorTaskAlive, _consumerSupplier); }
Source:
public void setDefinedSize_rangeEndEqualsAssumedSize_flushRequested() { fakeClientCommunication(); StateNode stateNode = Mockito.spy(element.getNode()); DataCommunicator<Item> dataCommunicator = new DataCommunicator<>( dataGenerator, arrayUpdater, data -> {}, stateNode); dataCommunicator.setPageSize(pageSize); dataCommunicator.setDataProvider(createDataProvider(), null); fakeClientCommunication(); dataCommunicator.setRequestedRange(0, 100); fakeClientCommunication(); Mockito.reset(stateNode); dataCommunicator.setDefinedSize(false); Mockito.verify(stateNode).runWhenAttached(Mockito.anyObject()); }

Target:
public void setDefinedSize_rangeEndEqualsAssumedSize_flushRequested() { fakeClientCommunication(); StateNode stateNode = Mockito.spy(element.getNode()); DataCommunicator<Item> dataCommunicator = new DataCommunicator<>( dataGenerator, arrayUpdater, data -> {}, stateNode); dataCommunicator.setPageSize(pageSize); dataCommunicator.setDataProvider(createDataProvider(), null); fakeClientCommunication(); dataCommunicator.setRequestedRange(0, 100); fakeClientCommunication(); Mockito.reset(stateNode); dataCommunicator.setDefinedSize(false); fakeClientCommunication(); Mockito.verify(stateNode).runWhenAttached(Mockito.anyObject()); Assert.assertEquals(300, dataCommunicator.getItemCount()); }
Source:
private void parseSegmentNodeChildren(Segment segment) throws XMLStreamException, TypeImportException { processChildren(LibraryElementTags.SEGMENT_ELEMENT, name -> { if (name.equals(LibraryElementTags.ATTRIBUTE_ELEMENT)) { if (isColorAttributeNode()) { parseColor(segment); } else { parseGenericAttributeNode(segment); } proceedToEndElementNamed(LibraryElementTags.ATTRIBUTE_ELEMENT); return true; } return false; }); }

Target:
private void parseSegmentNodeChildren(Segment segment) throws XMLStreamException, TypeImportException { processChildren(LibraryElementTags.SEGMENT_ELEMENT, name -> { if (LibraryElementTags.ATTRIBUTE_ELEMENT.equals(name)) { if (isColorAttributeNode()) { parseColor(segment); } else { parseGenericAttributeNode(segment); } proceedToEndElementNamed(LibraryElementTags.ATTRIBUTE_ELEMENT); return true; } return false; }); }
Source:
public void saveInEnvironment(String value, String envVar) throws Exception { if (value == null) { throw new Exception("Element to be saved: " + value + " is null"); } else { ThreadProperty.set(envVar, value); } }

Target:
public void saveInEnvironment(String value, String envVar) throws Exception { if (envVar.isEmpty()) { throw new Exception("Environment variable must be specified!"); } else { ThreadProperty.set(envVar, value); } }
Source:
public void test_setForegroundLorg_eclipse_swt_graphics_Color() { Color color = new Color(control.getDisplay(), 255, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); control.setForeground(null); assertFalse(control.getForeground().equals(color)); if (SwtTestUtil.isGTK3()) { color = new Color (control.getDisplay(), 255, 0, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); } if ("gtk".equals(SWT.getPlatform ())) { Color bg = new Color(control.getDisplay(), 0, 255, 0); control.setForeground(color); control.setBackground(bg); assertEquals("Setting a background disrupted the foreground color for " + control, color, control.getForeground()); assertEquals("Setting a background onto a widget with a foreground failed for " + control, bg, control.getBackground()); } color.dispose(); }

Target:
public void test_setForegroundLorg_eclipse_swt_graphics_Color() { Color color = new Color(control.getDisplay(), 255, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); control.setForeground(null); assertFalse(control.getForeground().equals(color)); if ("gtk".equals(SWT.getPlatform ())) { Color bg = new Color(control.getDisplay(), 0, 255, 0); control.setForeground(color); control.setBackground(bg); assertEquals("Setting a background disrupted the foreground color for " + control, color, control.getForeground()); assertEquals("Setting a background onto a widget with a foreground failed for " + control, bg, control.getBackground()); } color.dispose(); }
Source:
private String getContentType() { switch (gcsTargetConfig.dataFormat.getLabel()) { case "JSON": return "text/json"; case "CSV": return "text/csv"; } return null; }

Target:
private String getContentType() { switch (gcsTargetConfig.dataFormat) { case JSON: return "text/json"; default: break; } return null; }
Source:
public Session<String> getSession() { try { Session<String> session = mock(Session.class); willReturn(new String[] { "/foo/foo", "/foo/bar" }).given(session).list("/foo"); ByteArrayInputStream foo = new ByteArrayInputStream("foo\nbar".getBytes()); ByteArrayInputStream bar = new ByteArrayInputStream("baz\nqux".getBytes()); willReturn(foo).given(session).readRaw("/foo/foo"); willReturn(bar).given(session).readRaw("/foo/bar"); willReturn(new String[] { "/bar/foo", "/bar/bar" }).given(session).list("/bar"); ByteArrayInputStream foo2 = new ByteArrayInputStream("foo\r\nbar".getBytes()); ByteArrayInputStream bar2 = new ByteArrayInputStream("baz\r\nqux".getBytes()); willReturn(foo2).given(session).readRaw("/bar/foo"); willReturn(bar2).given(session).readRaw("/bar/bar"); given(session.finalizeRaw()).willReturn(true); return session; } catch (Exception e) { fail("failed to mock session"); } return null; }

Target:
public Session<String> getSession() { try { Session<String> session = mock(Session.class); willReturn(new String[] { "/foo/foo", "/foo/bar" }).given(session).list("/foo"); ByteArrayInputStream foo = new ByteArrayInputStream("foo\nbar".getBytes()); ByteArrayInputStream bar = new ByteArrayInputStream("baz\nqux".getBytes()); willReturn(foo).given(session).readRaw("/foo/foo"); willReturn(bar).given(session).readRaw("/foo/bar"); willReturn(new String[] { "/bar/foo", "/bar/bar" }).given(session).list("/bar"); ByteArrayInputStream foo2 = new ByteArrayInputStream("foo\r\nbar".getBytes()); ByteArrayInputStream bar2 = new ByteArrayInputStream("baz\r\nqux".getBytes()); willReturn(foo2).given(session).readRaw("/bar/foo"); willReturn(bar2).given(session).readRaw("/bar/bar"); given(session.finalizeRaw()).willReturn(true); return session; } catch (Exception e) { throw new RuntimeException("failed to mock session", e); } }