auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void setOnViewChanged() { getGeneratedClass()._implements(OnViewChangedListener.class); onViewChanged = getGeneratedClass().method(PUBLIC, getCodeModel().VOID, "onViewChanged"); onViewChanged.annotate(Override.class); onViewChangedBody = onViewChanged.body(); onViewChangedBodyBeforeFindViews = onViewChangedBody.blockSimple(); onViewChangedBodyFindViews = onViewChangedBody.blockSimple(); onViewChangedHasViewsParam = onViewChanged.param(HasViews.class, "hasViews"); AbstractJClass notifierClass = getJClass(OnViewChangedNotifier.class); getInitBody().staticInvoke(notifierClass, "registerOnViewChangedListener").arg(_this()); }

Target:
protected void setOnViewChanged() { getGeneratedClass()._implements(OnViewChangedListener.class); onViewChanged = getGeneratedClass().method(PUBLIC, getCodeModel().VOID, "onViewChanged"); onViewChanged.annotate(Override.class); onViewChangedBody = onViewChanged.body(); onViewChangedBodyBeforeInjectionBlock = onViewChangedBody.blockVirtual(); onViewChangedBodyInjectionBlock = onViewChangedBody.blockVirtual(); onViewChangedBodyAfterInjectionBlock = onViewChangedBody.blockVirtual(); onViewChangedHasViewsParam = onViewChanged.param(HasViews.class, "hasViews"); AbstractJClass notifierClass = getJClass(OnViewChangedNotifier.class); getInitBodyInjectionBlock().staticInvoke(notifierClass, "registerOnViewChangedListener").arg(_this()); }
Source:
public Boolean thereIsAProjectInTheWorkbench() { final Collection<OrganizationalUnit> organizationalUnits = getOrganizationalUnits(); for ( OrganizationalUnit organizationalUnit : organizationalUnits ) { final Collection<Repository> repositories = organizationalUnit.getRepositories(); for ( Repository repository : repositories ) { final Collection<String> branches = repository.getBranches(); for ( String branch : branches ) { final Set<Project> projects = kieProjectService.getProjects( repository, branch ); if ( projects != null && !projects.isEmpty() ) { return true; } } } } return false; }

Target:
public Boolean thereIsAProjectInTheWorkbench() { return getOrganizationalUnits().stream() .flatMap( organizationalUnit -> organizationalUnit.getRepositories().stream() .filter( repository -> authorizationManager.authorize( repository, sessionInfo.getIdentity() ) ) ) .flatMap( repository -> repository.getBranches().stream() .map( branch -> kieProjectService.getProjects( repository, branch ) ) ) .anyMatch( projects -> projects != null && !projects.isEmpty() ); }
Source:
public void testAdd() { MockEnabledModelResolver resolver = new MockEnabledModelResolver(); ModelResolverDescriptor oldValue = manager.add(resolver, resolver.getClass().getName(), "", ""); assertSame(manager.getAllResolver().iterator().next().getModelResolver(), resolver); assertEquals(oldValue, null); }

Target:
public void testAdd() { MockEnabledModelResolver resolver = new MockEnabledModelResolver(); ModelResolverDescriptor oldValue = manager.add(resolver, resolver.getClass().getName(), "", ""); assertSame(manager.getAllResolver().iterator().next().getModelResolver(), resolver); assertNull(oldValue); }
Source:
public void dealWithLicenseAction(ResourceRequest request, ResourceResponse response, String action) throws IOException, PortletException { if (PortalConstants.LICENSE_SEARCH.equals(action)) { final String searchText = request.getParameter(PortalConstants.WHAT); try { LicenseService.Iface client = thriftClients.makeLicenseClient(); List<License> licenses = client.getLicenseSummary(); if (!isNullOrEmpty(searchText)) { licenses = FluentIterable.from(licenses).filter(new Predicate<License>() { @Override public boolean apply(License input) { String fullname = input.getFullname(); String shortname = input.getShortname(); return !isNullOrEmpty(fullname) && ((StringUtils.containsIgnoreCase(searchText, fullname) || StringUtils.containsIgnoreCase(searchText, shortname))); } }).toList(); } request.setAttribute(PortalConstants.LICENSE_LIST, licenses); include("/html/utils/ajax/licenseListAjax.jsp", request, response, PortletRequest.RESOURCE_PHASE); } catch (TException e) { log.error("Error getting licenses", e); } } }

Target:
public void dealWithLicenseAction(ResourceRequest request, ResourceResponse response, String action) throws IOException, PortletException { if (PortalConstants.LICENSE_SEARCH.equals(action)) { final String searchText = request.getParameter(PortalConstants.WHAT); try { LicenseService.Iface client = thriftClients.makeLicenseClient(); List<License> licenses = client.getLicenseSummary(); licenses = FluentIterable.from(licenses).filter(new Predicate<License>() { @Override public boolean apply(License input) { String fullname = input.getFullname(); String shortname = input.getShortname(); return (StringUtils.containsIgnoreCase(fullname, searchText) || StringUtils.containsIgnoreCase(shortname, searchText)); } }).toList(); request.setAttribute(PortalConstants.LICENSE_LIST, licenses); include("/html/utils/ajax/licenseListAjax.jsp", request, response, PortletRequest.RESOURCE_PHASE); } catch (TException e) { log.error("Error getting licenses", e); } } }
Source:
private JsonToRowDataConverter createMapConverter( String typeSummary, LogicalType keyType, LogicalType valueType) { if (!LogicalTypeChecks.hasFamily(keyType, LogicalTypeFamily.CHARACTER_STRING)) { throw new UnsupportedOperationException( "JSON format doesn't support non-string as key type of map. " + "The map type is: " + typeSummary); } final JsonToRowDataConverter keyConverter = createConverter(keyType); final JsonToRowDataConverter valueConverter = createConverter(valueType); return jsonNode -> { Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields(); Map<Object, Object> result = new HashMap<>(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); Object key = keyConverter.convert(TextNode.valueOf(entry.getKey())); Object value = valueConverter.convert(entry.getValue()); result.put(key, value); } return new GenericMapData(result); }; }

Target:
private JsonToRowDataConverter createMapConverter( String typeSummary, LogicalType keyType, LogicalType valueType) { if (!LogicalTypeChecks.hasFamily(keyType, LogicalTypeFamily.CHARACTER_STRING)) { throw new UnsupportedOperationException( "JSON format doesn't support non-string as key type of map. " + "The type is: " + typeSummary); } final JsonToRowDataConverter keyConverter = createConverter(keyType); final JsonToRowDataConverter valueConverter = createConverter(valueType); return jsonNode -> { Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields(); Map<Object, Object> result = new HashMap<>(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); Object key = keyConverter.convert(TextNode.valueOf(entry.getKey())); Object value = valueConverter.convert(entry.getValue()); result.put(key, value); } return new GenericMapData(result); }; }
Source:
private void resetWallet() { final WalletLock walletLock = WalletLock.getInstance(); if (WalletLock.getInstance().isWalletLocked(wallet)) { UnlockWalletDialogFragment.show(getSupportFragmentManager(), new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!walletLock.isWalletLocked(wallet)) { resetWallet(); } } }); return; } log.info("Clearing all app data and exiting."); try { Runtime.getRuntime().exec("pm clear "+ getApplicationContext().getPackageName()); } catch (IOException e) { e.printStackTrace(); } }

Target:
private void resetWallet() { final WalletLock walletLock = WalletLock.getInstance(); if (WalletLock.getInstance().isWalletLocked(wallet)) { UnlockWalletDialogFragment.show(getSupportFragmentManager(), new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!walletLock.isWalletLocked(wallet)) { resetWallet(); } } }); return; } try { getWalletApplication().eraseAndCreateNewWallet(); } catch (Exception e) { e.printStackTrace(); } }
Source:
public void put(Map<String, LookupExtractorFactory> lookups) { synchronized (lock) { assertStarted(); for (ImmutableMap.Entry<String, LookupExtractorFactory> entry : lookups.entrySet()) { final String lookupName = entry.getKey(); final LookupExtractorFactory lookupExtractorFactory = entry.getValue(); if (!lookupExtractorFactory.start()) { throw new ISE("start method returned false for lookup [%s]", lookupName); } if (null != lookupMap.putIfAbsent(lookupName, lookupExtractorFactory)) { LOGGER.warn("lookup with name [%s] is not add since it already exist", lookupName); } } } }

Target:
public void put(Map<String, LookupExtractorFactory> lookups) { Map<String, LookupExtractorFactory> faildExtractorFactoryMap = new HashMap<>(); synchronized (lock) { assertStarted(); for (Map.Entry<String, LookupExtractorFactory> entry : lookups.entrySet()) { final String lookupName = entry.getKey(); final LookupExtractorFactory lookupExtractorFactory = entry.getValue(); if (lookupMap.containsKey(lookupName)) { LOGGER.warn("lookup [%s] is not add, another lookup with the same name already exist", lookupName); continue; } if (!lookupExtractorFactory.start()) { faildExtractorFactoryMap.put(lookupName, lookupExtractorFactory); continue; } lookupMap.put(lookupName, lookupExtractorFactory); } if (!faildExtractorFactoryMap.isEmpty()) { throw new ISE( "was not able to start the following lookup(s) [%s]", faildExtractorFactoryMap.keySet().toString() ); } } }
Source:
public int hashCode() { int ppHashCode = 0; Collection<ProductData> providedProducts = this.getProvidedProducts(); if (providedProducts != null) { for (ProductData pProduct : providedProducts) { ppHashCode = 31 * ppHashCode + (pProduct != null ? pProduct.hashCode() : 0); } } HashCodeBuilder builder = new HashCodeBuilder(37, 7) .append(super.hashCode()) .append(this.uuid) .append(this.id) .append(this.name) .append(this.multiplier) .append(this.href) .append(this.attributes) .append(this.content) .append(this.dependentProductIds) .append(this.branding) .append(this.locked) .append(ppHashCode); return builder.toHashCode(); }

Target:
public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(37, 7) .append(super.hashCode()) .append(this.uuid) .append(this.id) .append(this.name) .append(this.multiplier) .append(this.href) .append(this.attributes) .append(this.content) .append(this.dependentProductIds) .append(this.branding) .append(this.locked) .append(this.providedProducts); return builder.toHashCode(); }
Source:
public void trace(final String msg, final Throwable t) { throw new UnsupportedOperationException(); }

Target:
public void trace(final String msg, final Throwable t) { log("TRACE", msg, t); }
Source:
public void onLongPress(int x, int y, final PageTitle title, final HistoryEntry entry) { anchorView = new View(fragment.getActivity()); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(1, 1); params.leftMargin = x; params.topMargin = y; anchorView.setLayoutParams(params); containerView.addView(anchorView); PopupMenu popupMenu = new PopupMenu(activity, anchorView); popupMenu.inflate(R.menu.menu_page_long_press); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.menu_open_link: activity.displayNewPage(title, entry); return true; case R.id.menu_open_in_new_tab: fragment.openInNewTab(title, entry); return true; default: break; } return false; } }); popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { if (anchorView != null) { containerView.removeView(anchorView); anchorView = null; } } }); popupMenu.show(); final int vibrateMillis = 50; vibrator.vibrate(vibrateMillis); }

Target:
public void onLongPress(int x, int y, final PageTitle title, final HistoryEntry entry) { anchorView = new View(fragment.getActivity()); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(1, 1); params.leftMargin = x; params.topMargin = y; anchorView.setLayoutParams(params); containerView.addView(anchorView); PopupMenu popupMenu = new PopupMenu(activity, anchorView); popupMenu.inflate(R.menu.menu_page_long_press); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.menu_open_link: activity.displayNewPage(title, entry); return true; case R.id.menu_open_in_new_tab: fragment.openInNewTab(title, entry); return true; default: break; } return false; } }); popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { if (anchorView != null) { containerView.removeView(anchorView); anchorView = null; } } }); popupMenu.show(); }
Source:
public static InstallState getInstallState() { if (!Boolean.getBoolean("jenkins.install.runSetupWizard")) { if (Functions.getIsUnitTest()) { return InstallState.TEST; } if (Boolean.getBoolean("hudson.Main.development")) { return InstallState.DEVELOPMENT; } } VersionNumber lastRunVersion = new VersionNumber(getLastExecVersion()); if (lastRunVersion.compareTo(NEW_INSTALL_VERSION) == 0) { if (!Jenkins.getInstance().getItemMap().isEmpty() || Jenkins.getInstance().getSecurityRealm() != SecurityRealm.NO_AUTHENTICATION) { return InstallState.UPGRADE; } return InstallState.NEW; } VersionNumber currentRunVersion = new VersionNumber(getCurrentExecVersion()); if (lastRunVersion.isOlderThan(currentRunVersion)) { return InstallState.UPGRADE; } else if (lastRunVersion.isNewerThan(currentRunVersion)) { return InstallState.DOWNGRADE; } else { return InstallState.RESTART; } }

Target:
public static InstallState getInstallState() { String stateOverride = System.getenv("jenkins.install.state"); if (stateOverride != null) { try { return InstallState.valueOf(stateOverride.toUpperCase()); } catch (RuntimeException e) { throw new IllegalStateException("Unknown install state override specified on the commandline: '" + stateOverride + "'."); } } if (!Boolean.getBoolean("jenkins.install.runSetupWizard")) { if (Functions.getIsUnitTest()) { return InstallState.TEST; } if (Boolean.getBoolean("hudson.Main.development")) { return InstallState.DEVELOPMENT; } } VersionNumber lastRunVersion = new VersionNumber(getLastExecVersion()); if (lastRunVersion.compareTo(NEW_INSTALL_VERSION) == 0) { Jenkins j = Jenkins.getInstance(); if (!j.getItemMap().isEmpty() || !mayBeJenkins2SecurityDefaults(j)) { return InstallState.UPGRADE; } return InstallState.NEW; } VersionNumber currentRunVersion = new VersionNumber(getCurrentExecVersion()); if (lastRunVersion.isOlderThan(currentRunVersion)) { return InstallState.UPGRADE; } else if (lastRunVersion.isNewerThan(currentRunVersion)) { return InstallState.DOWNGRADE; } else { return InstallState.RESTART; } }
Source:
private void deleteSelfFromEntries(User user) { user.getEntries().stream() .filter(e -> e.getUsers().size() == 1 && !e.getIsPublished()) .forEach(entry -> { EntryDAO entryDAO; if (entry instanceof Workflow) { entryDAO = workflowDAO; } else if (entry instanceof Tool) { entryDAO = toolDAO; } else { throw new CustomWebApplicationException( MessageFormat.format("Unexpected entry type {0}", entry.getClass().toString()), HttpStatus.SC_INTERNAL_SERVER_ERROR); } List<Event> eventsByEntryIDs = eventDAO.findEventsByEntryId(entry.getId()); eventsByEntryIDs.forEach(eventDAO::delete); entryDAO.delete(entry); }); }

Target:
private void deleteSelfFromEntries(User user) { user.getEntries().stream() .filter(e -> e.getUsers().size() == 1 && !e.getIsPublished()) .forEach(entry -> { EntryDAO entryDAO; if (entry instanceof Workflow) { entryDAO = workflowDAO; } else if (entry instanceof Tool) { entryDAO = toolDAO; } else { throw new CustomWebApplicationException( MessageFormat.format("Unexpected entry type {0}", entry.getClass().toString()), HttpStatus.SC_INTERNAL_SERVER_ERROR); } eventDAO.deleteEventByEntryID(entry.getId()); entryDAO.delete(entry); }); }
Source:
private boolean decodeScenarioParameters(Cardio2eScenarioTransaction receivedCardio2eTransaction, List<String> digestedTransaction) { boolean decodeComplete = false; switch (receivedCardio2eTransaction.getTransactionType()){ case ACK: if (digestedTransaction.size() == 3) { try { receivedCardio2eTransaction.setObjectNumber (Short.parseShort(digestedTransaction.get(2))); decodeComplete = true; } catch (IllegalArgumentException e1) { e1.printStackTrace(); } } break; case NACK: decodeComplete = decodeNACK(receivedCardio2eTransaction, digestedTransaction); break; case SET: if (digestedTransaction.size() == 3) { try { receivedCardio2eTransaction.setObjectNumber (Short.parseShort(digestedTransaction.get(2))); decodeComplete = true; } catch (IllegalArgumentException e1) { e1.printStackTrace(); } } if (digestedTransaction.size() == 4) { try { if (digestedTransaction.get(3).length() <= Cardio2eTransaction.CARDIO2E_MAX_SECURITY_CODE_LENGTH) { receivedCardio2eTransaction.setObjectNumber (Short.parseShort(digestedTransaction.get(2))); receivedCardio2eTransaction.setSecurityCode(digestedTransaction.get(3)); decodeComplete = true; } } catch (IllegalArgumentException e1) { e1.printStackTrace(); } } break; } return decodeComplete; }

Target:
private boolean decodeScenarioParameters( Cardio2eScenarioTransaction receivedCardio2eTransaction, List<String> digestedTransaction) { boolean decodeComplete = false; switch (receivedCardio2eTransaction.getTransactionType()) { case ACK: if (digestedTransaction.size() == 3) { try { receivedCardio2eTransaction.setObjectNumber(Short .parseShort(digestedTransaction.get(2))); decodeComplete = true; } catch (IllegalArgumentException ex) { logger.warn( "Illegal argument in decoding SCENARIO transaction: '{}'", ex.toString()); } } break; case NACK: decodeComplete = decodeNACK(receivedCardio2eTransaction, digestedTransaction); break; case SET: if (digestedTransaction.size() == 3) { try { receivedCardio2eTransaction.setObjectNumber(Short .parseShort(digestedTransaction.get(2))); decodeComplete = true; } catch (IllegalArgumentException ex) { logger.warn( "Illegal argument in decoding SCENARIO transaction: '{}'", ex.toString()); } } if (digestedTransaction.size() == 4) { try { if (digestedTransaction.get(3).length() <= Cardio2eTransaction.CARDIO2E_MAX_SECURITY_CODE_LENGTH) { receivedCardio2eTransaction.setObjectNumber(Short .parseShort(digestedTransaction.get(2))); receivedCardio2eTransaction .setSecurityCode(digestedTransaction.get(3)); decodeComplete = true; } } catch (IllegalArgumentException ex) { logger.warn( "Illegal argument in decoding SCENARIO transaction: '{}'", ex.toString()); } } break; } return decodeComplete; }
Source:
private void initialize(final Bundle savedInstanceState) { loadSettingsFromXml(); if (!shouldShowDualPane) { setupNavigationDrawer(); setupActionBar(); setupActionBarToggle(); } setupActivityFromState(savedInstanceState); }

Target:
private void initialize(final Bundle savedInstanceState) { shouldShowDualPane = getResources().getBoolean(R.bool.main_is_dualpane); if (!shouldShowDualPane) { navigationDrawer = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); setupActionBar(); setupActionBarToggle(); } setupActivityFromState(savedInstanceState); }
Source:
public <T> void addParameter(VdcParameter param, T value) { paramsMap.<T>put(param, value); }

Target:
public <T> VdcQueryParametersBase addParameter(VdcParameter param, T value) { paramsMap.<T>put(param, value); return this; }
Source:
boolean removeUserBan(final int moderatorId, final String banId) { final String unbanName = bannedUserDao.lookupUsernameByBanId(banId).orElse(null); if (bannedUserDao.removeBan(banId) != 1) { return false; } if (unbanName == null) { throw new AssertionError( "Consistency error, unbanned " + banId + ", but " + "there was no matching name for that ban."); } moderatorAuditHistoryDao.addAuditRecord( ModeratorAuditHistoryDao.AuditArgs.builder() .actionName(ModeratorAuditHistoryDao.AuditAction.REMOVE_USER_BAN) .actionTarget(unbanName) .moderatorUserId(moderatorId) .build()); return true; }

Target:
boolean removeUserBan(final int moderatorId, final String banId) { final String unbanName = bannedUserDao.lookupUsernameByBanId(banId).orElse(null); if (bannedUserDao.removeBan(banId) != 1) { return false; } if (unbanName == null) { throw new IllegalStateException( "Consistency error, unbanned " + banId + ", but " + "there was no matching name for that ban."); } moderatorAuditHistoryDao.addAuditRecord( ModeratorAuditHistoryDao.AuditArgs.builder() .actionName(ModeratorAuditHistoryDao.AuditAction.REMOVE_USER_BAN) .actionTarget(unbanName) .moderatorUserId(moderatorId) .build()); return true; }
Source:
public void whenConsumerIsBlocked429() throws Exception { final FloodService.Flooder flooder = new FloodService.Flooder(eventType.getName(), FloodService.Type.CONSUMER_ET); NakadiControllerAT.blockFlooder(flooder); TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "") .start(); Thread.sleep(2000); Assert.assertEquals(MoreStatus.TOO_MANY_REQUESTS.getStatusCode(), client.getResponseCode()); Assert.assertEquals("300", client.getHeaderValue("Retry-After")); NakadiControllerAT.unblockFlooder(flooder); client = TestStreamingClient .create(URL, subscription.getId(), "") .start(); Thread.sleep(2000); Assert.assertEquals(HttpStatus.SC_OK, client.getResponseCode()); }

Target:
public void whenConsumerIsBlocked429() throws Exception { final FloodService.Flooder flooder = new FloodService.Flooder(eventType.getName(), FloodService.Type.CONSUMER_ET); SettingsControllerAT.blockFlooder(flooder); final TestStreamingClient client1 = TestStreamingClient .create(URL, subscription.getId(), "") .start(); waitFor(() -> { Assert.assertEquals(MoreStatus.TOO_MANY_REQUESTS.getStatusCode(), client1.getResponseCode()); Assert.assertEquals("300", client1.getHeaderValue("Retry-After")); }); SettingsControllerAT.unblockFlooder(flooder); final TestStreamingClient client2 = TestStreamingClient .create(URL, subscription.getId(), "") .start(); waitFor(() -> Assert.assertEquals(HttpStatus.SC_OK, client2.getResponseCode())); }
Source:
public void setupTestCluster() throws Exception { assertTrue(baseDir.mkdirs() || baseDir.isDirectory()); File testDir = new File(baseDir, testName.getMethodName()); FileUtils.deleteQuietly(testDir); assertTrue(testDir.mkdir()); zooKeeper = new TestingServer(); MiniAccumuloConfig config = new MiniAccumuloConfig(testDir, "superSecret"); config.setExistingZooKeepers(zooKeeper.getConnectString()); accumulo = new MiniAccumuloCluster(config); }

Target:
public void setupTestCluster() throws Exception { assertTrue(BASE_DIR.mkdirs() || BASE_DIR.isDirectory()); File testDir = new File(BASE_DIR, testName.getMethodName()); FileUtils.deleteQuietly(testDir); assertTrue(testDir.mkdir()); zooKeeper = new TestingServer(); MiniAccumuloConfig config = new MiniAccumuloConfig(testDir, SECRET); config.getImpl().setExistingZooKeepers(zooKeeper.getConnectString()); accumulo = new MiniAccumuloCluster(config); accumulo.start(); }
Source:
protected ActionContext createActionContext(DocumentModel doc) { ActionContext actionContext = new ELActionContext(); actionContext.setCurrentDocument(doc); actionContext.setDocumentManager(doc.getCoreSession()); if (doc.getCoreSession() != null) { actionContext.setCurrentPrincipal(doc.getCoreSession().getPrincipal()); } return actionContext; }

Target:
protected ActionContext createActionContext(DocumentModel doc) { ActionContext actionContext = new ELActionContext(); actionContext.setCurrentDocument(doc); CoreSession coreSession = doc.getCoreSession(); actionContext.setDocumentManager(coreSession); if (coreSession != null) { actionContext.setCurrentPrincipal(coreSession.getPrincipal()); } return actionContext; }
Source:
private void selectTrackableSort() { final Builder alert = new AlertDialog.Builder(this); alert.setTitle(res.getString(R.string.log_tb_sortby)); final String[] tbSortLabels = { res.getString(R.string.trackable_code), res.getString(R.string.trackable_name) }; final List<Comparator<TrackableLog>> comparators = new ArrayList<>(); comparators.add(new Comparator<TrackableLog>() { @Override public int compare(final TrackableLog lhs, final TrackableLog rhs) { return TextUtils.COLLATOR.compare(lhs.name, rhs.name); } }); comparators.add(new Comparator<TrackableLog>() { @Override public int compare(final TrackableLog lhs, final TrackableLog rhs) { return TextUtils.COLLATOR.compare(lhs.trackCode, rhs.trackCode); } }); alert.setSingleChoiceItems(tbSortLabels, trackableSortPositionSelected , new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int position) { trackableSort = comparators.get(position); trackableSortPositionSelected = position; updateTrackablesList(); dialog.dismiss(); } }); alert.create().show(); }

Target:
private void selectTrackableSort() { final Builder alert = new AlertDialog.Builder(this); alert.setTitle(res.getString(R.string.log_tb_sortby)); final String[] tbSortLabels = new String[TrackableComparator.values().length]; for (final TrackableComparator tc: TrackableComparator.values()) { tbSortLabels[tc.getPosition()] = res.getString(tc.getLabel()); } alert.setSingleChoiceItems(tbSortLabels, Settings.getTrackableInventorySortMethod() , new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int position) { Settings.setTrackableInventorySortMethod(position); updateTrackablesList(); dialog.dismiss(); } }); alert.create().show(); }
Source:
public int hashCode() { return Objects.hash(position, sequence); }

Target:
public int hashCode() { int result = Objects.hash(position); result = 31 * result + Arrays.hashCode(sequence); return result; }
Source:
private void orderContainedClasses(JupiterEngineDescriptor jupiterEngineDescriptor, ClassOrderer classOrderer) { Set<? extends TestDescriptor> children = jupiterEngineDescriptor.getChildren(); List<TestDescriptor> nonClassTestDescriptors = children.stream() .filter(testDescriptor -> !(testDescriptor instanceof ClassBasedTestDescriptor)) .collect(Collectors.toList()); List<DefaultClassDescriptor> classDescriptors = children.stream() .filter(ClassBasedTestDescriptor.class::isInstance) .map(ClassBasedTestDescriptor.class::cast) .map(DefaultClassDescriptor::new) .collect(toCollection(ArrayList::new)); Set<DefaultClassDescriptor> originalClassDescriptors = new LinkedHashSet<>(classDescriptors); classOrderer.orderClasses(new DefaultClassOrdererContext(classDescriptors, this.configuration)); int difference = classDescriptors.size() - originalClassDescriptors.size(); if (difference > 0) { logger.warn(() -> String.format("ClassOrderer [%s] added %s ClassDescriptor(s) which will be ignored.", classOrderer.getClass().getName(), difference)); } else if (difference < 0) { logger.warn(() -> String.format( "ClassOrderer [%s] removed %s ClassDescriptor(s) which will be retained with arbitrary ordering.", classOrderer.getClass().getName(), -difference)); } Set<TestDescriptor> sortedClassTestDescriptors = classDescriptors.stream() .filter(originalClassDescriptors::contains) .map(DefaultClassDescriptor::getTestDescriptor) .collect(toCollection(LinkedHashSet::new)); Stream.concat(sortedClassTestDescriptors.stream(), nonClassTestDescriptors.stream()) .forEach(jupiterEngineDescriptor::removeChild); Stream.concat(sortedClassTestDescriptors.stream(), nonClassTestDescriptors.stream()) .forEach(jupiterEngineDescriptor::addChild); }

Target:
private void orderContainedClasses(JupiterEngineDescriptor jupiterEngineDescriptor, ClassOrderer classOrderer) { orderChildrenTestDescriptors(jupiterEngineDescriptor, ClassBasedTestDescriptor.class, DefaultClassDescriptor::new, descriptorWrappers -> classOrderer.orderClasses( new DefaultClassOrdererContext(descriptorWrappers, this.configuration)), difference -> String.format("ClassOrderer [%s] added %s ClassDescriptor(s) which will be ignored.", classOrderer.getClass().getName(), difference), difference -> String.format( "ClassOrderer [%s] removed %s ClassDescriptor(s) which will be retained with arbitrary ordering.", classOrderer.getClass().getName(), -difference)); }
Source:
public void doExecute() throws MojoExecutionException { getLog().debug("Verifying packaged files ..."); try { if (!skipValidation) { getProjectVerifier().verify(); } else { getLog().debug("skipping verify validation for Mule application"); } } catch (ValidationException e) { throw new MojoExecutionException("Verify exception", e); } }

Target:
public void doExecute() throws MojoExecutionException { getLog().debug("Verifying packaged files..."); try { if (!skipValidation) { getProjectVerifier().verify(); } else { getLog().debug("Skipping verify validation for Mule application"); } } catch (ValidationException e) { throw new MojoExecutionException("Verify exception", e); } }
Source:
public void registerClasses( Kryo kryo ) { FeatureSerializer simpleSerializer = new FeatureSerializer(); PersistableSerializer persistSerializer = new PersistableSerializer(); kryo.register( SimpleFeature.class, simpleSerializer, 1200); kryo.register( SimpleFeatureImpl.class, simpleSerializer, 1201); kryo.register( AvroSimpleFeature.class, simpleSerializer, 1202); kryo.register( Persistable.class, persistSerializer); kryo.register( TieredSFCIndexStrategy.class, persistSerializer); kryo.register( SingleTierSubStrategy.class, persistSerializer); kryo.register( HilbertSFC.class, persistSerializer); }

Target:
public void registerClasses( Kryo kryo ) { FeatureSerializer simpleSerializer = new FeatureSerializer(); PersistableSerializer persistSerializer = new PersistableSerializer(); PersistableFactory.getInstance().getClassIdMapping().entrySet().forEach(e -> kryo.register(e.getKey(), persistSerializer, e.getValue())); kryo.register( SimpleFeatureImpl.class, simpleSerializer); }
Source:
private void flatMap(IndexedRecord input, ProcessContext context) throws IOException { python.set("inputJSON", new PyString(input.toString())); python.exec("input = json.loads(inputJSON)"); python.exec("outputList = []"); python.exec(properties.pythonCode.getValue()); python.exec("outputJSON = [ json.dumps(outputElement) for outputElement in outputList ]"); PyObject outputList = python.get("outputJSON"); if (outputList instanceof PyList) { PyList list = (PyList) outputList; for (Object output : list) { JsonSchemaInferrer jsonSchemaInferrer = new JsonSchemaInferrer(new ObjectMapper()); Schema jsonSchema = jsonSchemaInferrer.inferSchema(output.toString()); JsonGenericRecordConverter jsonGenericRecordConverter = new JsonGenericRecordConverter(jsonSchema); GenericRecord outputRecord = jsonGenericRecordConverter.convertToAvro(output.toString()); context.output(outputRecord); } } }

Target:
private void flatMap(IndexedRecord input, ProcessContext context) throws IOException { python.set("inputJSON", new PyString(input.toString())); python.exec("input = json.loads(inputJSON)"); python.exec("outputList = []"); python.exec(properties.pythonCode.getValue()); python.exec("outputJSON = [ json.dumps(outputElement) for outputElement in outputList ]"); PyObject outputList = python.get("outputJSON"); if (outputList instanceof PyList) { PyList list = (PyList) outputList; for (Object output : list) { if (jsonGenericRecordConverter == null) { JsonSchemaInferrer jsonSchemaInferrer = new JsonSchemaInferrer(new ObjectMapper()); Schema jsonSchema = jsonSchemaInferrer.inferSchema(output.toString()); jsonGenericRecordConverter = new JsonGenericRecordConverter(jsonSchema); } GenericRecord outputRecord = jsonGenericRecordConverter.convertToAvro(output.toString()); context.output(outputRecord); } } }
Source:
public final void error() { for (InputAnchor in : getInputs()) { if (!in.isConnected()) { argumentSpace.getChildren().get(getArgumentIndex(in)) .getStyleClass().add("error"); } else if (in.isConnected()) { argumentSpace.getChildren().get(getArgumentIndex(in)) .getStyleClass().remove("error"); } } this.getStyleClass().add("error"); }

Target:
public final void error() { for (InputAnchor in : getInputs()) { ObservableList<Node> children = argumentSpace.getChildren(); Node arg = children.get(getArgumentIndex(in)); if (!in.isConnected()) { arg.getStyleClass().add("error"); } else if (in.isConnected()) { arg.getStyleClass().remove("error"); } } this.getStyleClass().add("error"); }
Source:
public static void appLaunched(Context mContext, String packageName) { SharedPreferences prefs = mContext.getSharedPreferences("app_rater", 0); if (prefs.getBoolean("don't_show_again", false)) { return; } SharedPreferences.Editor editor = prefs.edit(); long launchCount = prefs.getLong("launch_count", 0) + 1; editor.putLong("launch_count", launchCount); Long dateFirstLaunch = prefs.getLong("date_first_launch", 0); if (dateFirstLaunch == 0) { dateFirstLaunch = System.currentTimeMillis(); editor.putLong("date_first_launch", dateFirstLaunch); } Long dateNeutralClick = prefs.getLong("date_neutral", 0); if (launchCount >= LAUNCHES_UNTIL_PROMPT) { if (System.currentTimeMillis() >= Math.max(dateFirstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000), dateNeutralClick + (DAYS_UNTIL_NEUTRAL_CLICK * 24 * 60 * 60 * 1000))) { showRateDialog(mContext, packageName, false); } } editor.apply(); }

Target:
public static void appLaunched(Context mContext, String packageName) { SharedPreferences prefs = mContext.getSharedPreferences(APP_RATER_PREF_TITLE, 0); if (prefs.getBoolean(APP_RATER_PREF_DONT_SHOW, false)) { return; } SharedPreferences.Editor editor = prefs.edit(); long launchCount = prefs.getLong(APP_RATER_PREF_LAUNCH_COUNT, 0) + 1; editor.putLong(APP_RATER_PREF_LAUNCH_COUNT, launchCount); Long dateFirstLaunch = prefs.getLong(APP_RATER_PREF_DATE_FIRST_LAUNCH, 0); if (dateFirstLaunch == 0) { dateFirstLaunch = System.currentTimeMillis(); editor.putLong(APP_RATER_PREF_DATE_FIRST_LAUNCH, dateFirstLaunch); } Long dateNeutralClick = prefs.getLong(APP_RATER_PREF_DATE_NEUTRAL, 0); if (launchCount >= LAUNCHES_UNTIL_PROMPT) { if (System.currentTimeMillis() >= Math.max(dateFirstLaunch + daysToMilliseconds(DAYS_UNTIL_PROMPT), dateNeutralClick + daysToMilliseconds(DAYS_UNTIL_NEUTRAL_CLICK))) { showRateDialog(mContext, packageName, false); } } editor.apply(); }
Source:
public WebappDaoFactoryConfig() { preferredLocales = Arrays.asList(Locale.getDefault()); preferredLanguages = Arrays.asList("en-US", "en", "EN"); defaultNamespace = "<LINK_0>"; nonUserNamespaces = new HashSet<String>(); nonUserNamespaces.add(VitroVocabulary.vitroURI); }

Target:
public WebappDaoFactoryConfig() { preferredLanguages = Arrays.asList("en-US", "en", "EN"); preferredLocales = LanguageFilteringUtils.languagesToLocales(preferredLanguages); defaultNamespace = "<LINK_0>"; nonUserNamespaces = new HashSet<String>(); nonUserNamespaces.add(VitroVocabulary.vitroURI); }
Source:
public Object instantiate(Target<?> target, Parameters parameters) { try { if(isSupportedCollection(target)) { return multiInstantiator.instantiate(target, parameters); } Parameter parameter = parameters.namedAfter(target); return converterForTarget(target).convert(parameter.getValue(), target.getClassType()); } catch (ConversionException ex) { logger.warn("Could not convert target", ex); errors.add(ex.getValidationMessage().withCategory(target.getName())); } catch (IllegalStateException e) { logger.warn("An error occured while getting validation message", e); return setPropertiesAfterConversions(target, parameters); } return null; }

Target:
public Object instantiate(Target<?> target, Parameters parameters) { try { if(isSupportedCollection(target)) { return multiInstantiator.instantiate(target, parameters); } Parameter parameter = parameters.namedAfter(target); return converterForTarget(target).convert(parameter.getValue(), target.getClassType()); } catch (ConversionException ex) { logger.debug("Could not convert target", ex); errors.add(ex.getValidationMessage().withCategory(target.getName())); } catch (IllegalStateException e) { logger.debug("An error occured while getting validation message", e); return setPropertiesAfterConversions(target, parameters); } return null; }
Source:
protected Command getCommand() { Request request = getSourceRequest(); if (request instanceof MoveArrowRequest) { ICommand moveArrowCommand = new AbstractTransactionalCommand(editingDomain, "Move arrow", null) { @Override protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { Connector connector = (Connector) durationLinkEditPart.getNotationView(); IntValueStyle deltaStyle = (IntValueStyle) connector.getNamedStyle(NotationPackage.eINSTANCE.getIntValueStyle(), "delta"); if (deltaStyle == null) { deltaStyle = (IntValueStyle) connector.createStyle(NotationPackage.eINSTANCE.getIntValueStyle()); deltaStyle.setName("delta"); } Point moveDelta = ((MoveArrowRequest) request).getMoveDelta(); Orientation arrowOrientation = ((MoveArrowRequest) request).getArrowOrientation(); if (arrowOrientation == Orientation.VERTICAL) { deltaStyle.setIntValue(deltaStyle.getIntValue() + moveDelta.x); } else { deltaStyle.setIntValue(deltaStyle.getIntValue() + moveDelta.y); } return CommandResult.newOKCommandResult(); } }; return new ICommandProxy(moveArrowCommand); } return super.getCommand(); }

Target:
protected Command getCommand() { Request request = getSourceRequest(); if (request instanceof MoveArrowRequest) { ICommand moveArrowCommand = new AbstractTransactionalCommand(editingDomain, "Move arrow", null) { @Override protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { Connector connector = (Connector) durationLinkEditPart.getNotationView(); @SuppressWarnings("unchecked") Optional<IntValueStyle> deltaOptional = connector.getStyles().stream().filter(IntValueStyle.class::isInstance).filter(style -> "delta".equals(((IntValueStyle) style).getName())).findFirst(); IntValueStyle deltaStyle = deltaOptional.orElseGet(() -> { IntValueStyle style = (IntValueStyle) connector.createStyle(NotationPackage.eINSTANCE.getIntValueStyle()); style.setName("delta"); return style; }); Point moveDelta = ((MoveArrowRequest) request).getMoveDelta(); Orientation arrowOrientation = ((MoveArrowRequest) request).getArrowOrientation(); if (arrowOrientation == Orientation.VERTICAL) { deltaStyle.setIntValue(deltaStyle.getIntValue() + moveDelta.x); } else { deltaStyle.setIntValue(deltaStyle.getIntValue() + moveDelta.y); } return CommandResult.newOKCommandResult(); } }; return new ICommandProxy(moveArrowCommand); } return super.getCommand(); }
Source:
public FongoDB(Fongo fongo, String name) { super(fongo.getMongoClient(), name); this.fongo = fongo; }

Target:
public FongoDB(Fongo fongo, String name) { super(fongo.getMongo(), name); this.fongo = fongo; }
Source:
public static boolean isChimeric(final SAMRecord r1, final SAMRecord r2, final int maxInsertSize, final Set<PairOrientation> expectedOrientations) { return (Math.abs(r1.getInferredInsertSize()) > maxInsertSize || !r1.getReferenceIndex().equals(r2.getReferenceIndex()) || expectedOrientations.contains(SamPairUtil.getPairOrientation(r1)) || r1.getAttribute("SA") != null || r2.getAttribute("SA") != null); }

Target:
public static boolean isChimeric(final SAMRecord r1, final SAMRecord r2, final int maxInsertSize, final Set<PairOrientation> expectedOrientations) { return !(r1.getReadUnmappedFlag() || r2.getMateUnmappedFlag()) && (Math.abs(r1.getInferredInsertSize()) > maxInsertSize || !r1.getReferenceIndex().equals(r2.getReferenceIndex()) || expectedOrientations.contains(SamPairUtil.getPairOrientation(r1)) || r1.getAttribute("SA") != null || r2.getAttribute("SA") != null); }
Source:
public void updateApplicationKeyTypeMetaData(int applicationId, String keyType, String keyManagerName, OAuthApplicationInfo updatedAppInfo) throws APIManagementException { if (applicationId != -1 && updatedAppInfo != null) { String addApplicationKeyMapping = SQLConstants.UPDATE_APPLICATION_KEY_TYPE_MAPPINGS_METADATA_SQL; try (Connection connection = APIMgtDBUtil.getConnection()) { connection.setAutoCommit(false); try { try (PreparedStatement ps = connection.prepareStatement(addApplicationKeyMapping)) { String content = new Gson().toJson(updatedAppInfo); ps.setBinaryStream(1, new ByteArrayInputStream(content.getBytes())); ps.setInt(2, applicationId); ps.setString(3, keyType); ps.setString(4, keyManagerName); ps.executeUpdate(); } connection.commit(); } catch (SQLException e) { connection.rollback(); } } catch (SQLException e) { handleException("Error updating the Application Metadata of the AM_APPLICATION_KEY_MAPPING table " + "where " + "APPLICATION_ID = " + applicationId + " and KEY_TYPE = " + keyType, e); } } }

Target:
public void updateApplicationKeyTypeMetaData(int applicationId, String keyType, String keyManagerName, OAuthApplicationInfo updatedAppInfo) throws APIManagementException { if (applicationId > 0 && updatedAppInfo != null) { String addApplicationKeyMapping = SQLConstants.UPDATE_APPLICATION_KEY_TYPE_MAPPINGS_METADATA_SQL; try (Connection connection = APIMgtDBUtil.getConnection()) { connection.setAutoCommit(false); try { try (PreparedStatement ps = connection.prepareStatement(addApplicationKeyMapping)) { String content = new Gson().toJson(updatedAppInfo); ps.setBinaryStream(1, new ByteArrayInputStream(content.getBytes())); ps.setInt(2, applicationId); ps.setString(3, keyType); ps.setString(4, keyManagerName); ps.executeUpdate(); } connection.commit(); } catch (SQLException e) { connection.rollback(); } } catch (SQLException e) { handleException("Error updating the Application Metadata of the AM_APPLICATION_KEY_MAPPING table " + "where " + "APPLICATION_ID = " + applicationId + " and KEY_TYPE = " + keyType, e); } } }
Source:
public IOService next() { return INSTANCE.IOIteratorNext(this); }

Target:
public IORegistryEntry next() { return INSTANCE.IOIteratorNext(this); }
Source:
public RestartRequirement onApply(UserPrefs prefs) { RestartRequirement restartRequirement = super.onApply(prefs); prefs_.lineEndingConversion().setGlobalValue(lineEndings_.getValue()); prefs_.ansiConsoleMode().setGlobalValue(consoleColorMode_.getValue()); prefs_.defaultEncoding().setGlobalValue(encodingValue_); prefs_.codeCompletion().setGlobalValue(showCompletions_.getValue()); prefs_.codeCompletionOther().setGlobalValue(showCompletionsOther_.getValue()); String editorMode = editorMode_.getValue(); prefs_.editorKeybindings().setGlobalValue(editorMode); boolean isVim = editorMode == UserPrefs.EDITOR_KEYBINDINGS_VIM; boolean isEmacs = editorMode == UserPrefs.EDITOR_KEYBINDINGS_EMACS; boolean isSublime = editorMode == UserPrefs.EDITOR_KEYBINDINGS_SUBLIME; if (isVim) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_VIM); else if (isEmacs) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_EMACS); else if (isSublime) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_SUBLIME); else ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_DEFAULT); prefs_.foldStyle().setGlobalValue(foldMode_.getValue()); prefs_.surroundSelection().setGlobalValue(delimiterSurroundWidget_.getValue()); prefs_.executionBehavior().setGlobalValue(executionBehavior_.getValue()); prefs_.autoSaveOnIdle().setGlobalValue(autoSaveOnIdle_.getValue()); prefs_.autoSaveIdleMs().setGlobalValue(Integer.parseInt(autoSaveIdleMs_.getValue())); return restartRequirement; }

Target:
public RestartRequirement onApply(UserPrefs prefs) { RestartRequirement restartRequirement = super.onApply(prefs); prefs_.lineEndingConversion().setGlobalValue(lineEndings_.getValue()); prefs_.ansiConsoleMode().setGlobalValue(consoleColorMode_.getValue()); prefs_.defaultEncoding().setGlobalValue(encodingValue_); prefs_.codeCompletion().setGlobalValue(showCompletions_.getValue()); prefs_.codeCompletionOther().setGlobalValue(showCompletionsOther_.getValue()); String editorMode = editorMode_.getValue(); prefs_.editorKeybindings().setGlobalValue(editorMode); boolean isVim = editorMode == UserPrefs.EDITOR_KEYBINDINGS_VIM; boolean isEmacs = editorMode == UserPrefs.EDITOR_KEYBINDINGS_EMACS; boolean isSublime = editorMode == UserPrefs.EDITOR_KEYBINDINGS_SUBLIME; if (isVim) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_VIM); else if (isEmacs) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_EMACS); else if (isSublime) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_SUBLIME); else ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_DEFAULT); prefs_.foldStyle().setGlobalValue(foldMode_.getValue()); prefs_.surroundSelection().setGlobalValue(delimiterSurroundWidget_.getValue()); prefs_.executionBehavior().setGlobalValue(executionBehavior_.getValue()); prefs_.autoSaveOnIdle().setGlobalValue(autoSaveOnIdle_.getValue()); prefs_.autoSaveIdleMs().setGlobalValue(StringUtil.parseInt(autoSaveIdleMs_.getValue(), 1000)); return restartRequirement; }
Source:
private AsyncCleanerService(Elide elide, Integer maxRunTimeSeconds, Integer queryCleanupDays, Integer cancelDelaySeconds, AsyncQueryDAO asyncQueryDao) { int queryRunTimeThresholdMinutes = Math.round((maxRunTimeSeconds * 2) / 60); ScheduledExecutorService cleaner = Executors.newSingleThreadScheduledExecutor(); AsyncQueryCleanerThread cleanUpTask = new AsyncQueryCleanerThread(queryRunTimeThresholdMinutes, elide, queryCleanupDays, asyncQueryDao); Random random = new Random(); int initialDelayMinutes = random.ints(0, maxInitialDelayMinutes).limit(1).findFirst().getAsInt(); log.debug("Initial Delay for cleaner service is {}", initialDelayMinutes); cleaner.scheduleWithFixedDelay(cleanUpTask, 0, Math.max(defaultCleanupDelayMinutes, queryRunTimeThresholdMinutes), TimeUnit.MINUTES); ScheduledExecutorService cancellation = Executors.newSingleThreadScheduledExecutor(); AsyncQueryCancelThread cancelTask = new AsyncQueryCancelThread(maxRunTimeSeconds, elide, asyncQueryDao); cancellation.scheduleWithFixedDelay(cancelTask, 0, cancelDelaySeconds, TimeUnit.SECONDS); }

Target:
private AsyncCleanerService(Elide elide, Integer maxRunTimeSeconds, Integer queryCleanupDays, Integer cancelDelaySeconds, AsyncQueryDAO asyncQueryDao) { int queryRunTimeThresholdMinutes = Math.round((maxRunTimeSeconds * 2) / 60); ScheduledExecutorService cleaner = Executors.newSingleThreadScheduledExecutor(); AsyncQueryCleanerThread cleanUpTask = new AsyncQueryCleanerThread(queryRunTimeThresholdMinutes, elide, queryCleanupDays, asyncQueryDao, new DateUtil()); Random random = new Random(); int initialDelayMinutes = random.ints(0, maxInitialDelayMinutes).limit(1).findFirst().getAsInt(); log.debug("Initial Delay for cleaner service is {}", initialDelayMinutes); cleaner.scheduleWithFixedDelay(cleanUpTask, initialDelayMinutes, Math.max(defaultCleanupDelayMinutes, queryRunTimeThresholdMinutes), TimeUnit.MINUTES); ScheduledExecutorService cancellation = Executors.newSingleThreadScheduledExecutor(); AsyncQueryCancelThread cancelTask = new AsyncQueryCancelThread(maxRunTimeSeconds, elide, asyncQueryDao); cancellation.scheduleWithFixedDelay(cancelTask, 0, cancelDelaySeconds, TimeUnit.SECONDS); }
Source:
private void testParameter(List<String> args) { if (containsHelpRequest(args) || args.isEmpty()) { testParameterHelp(); } else if (!args.isEmpty()) { String entry = reqVal(args, "--entry"); String version = reqVal(args, "--version"); String descriptorType = null; final List<String> adds = optVals(args, "--add"); final List<String> removes = optVals(args, "--remove"); if (getEntryType().toLowerCase().equals("tool")) { descriptorType = reqVal(args, "--descriptor-type"); descriptorType = descriptorType.toLowerCase(); if (!descriptorType.equals(CWL_STRING) && !descriptorType.equals(WDL_STRING)) { errorMessage("Only \'CWL\' and \'WDL\' are valid descriptor types", CLIENT_ERROR); } } handleTestParameter(entry, version, adds, removes, descriptorType); } }

Target:
private void testParameter(List<String> args) { if (containsHelpRequest(args) || args.isEmpty()) { testParameterHelp(); } else if (!args.isEmpty()) { String entry = reqVal(args, "--entry"); String version = reqVal(args, "--version"); String descriptorType = null; final List<String> adds = optVals(args, "--add"); final List<String> removes = optVals(args, "--remove"); if (getEntryType().toLowerCase().equals("tool")) { descriptorType = reqVal(args, "--descriptor-type"); descriptorType = descriptorType.toLowerCase(); boolean validType = false; for (Type type : Type.values()) { if (type.toString().equals(descriptorType) && !descriptorType.equals("none")) { validType = true; break; } } if (!validType) { errorMessage("Only \'CWL\' and \'WDL\' are valid descriptor types", CLIENT_ERROR); } } handleTestParameter(entry, version, adds, removes, descriptorType); } }