auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
LegacyPolicy getLegacyPolicyFromServicePolicy(ServicePolicy servicePolicy) { List<GeoCircleFence> geoFences = null; if (servicePolicy.getLocations() != null) { if (!servicePolicy.getLocations().isEmpty()) { geoFences = new ArrayList<>(); for (ServicePolicy.Location location : servicePolicy.getLocations()) { geoFences.add(getGeoCircleFenceFromLocation(location)); } } } Integer requiredFactors = servicePolicy.getRequiredFactors(); int amount = (requiredFactors != null) ? requiredFactors : 0; Boolean inherence = servicePolicy.isInherenceFactorRequired(); Boolean knownledge = servicePolicy.isKnowledgeFactorRequired(); Boolean possession = servicePolicy.isPossessionFactorRequired(); boolean denyRootedJailbroken = (servicePolicy.isJailBreakProtectionEnabled() != null) ? servicePolicy.isJailBreakProtectionEnabled() : false; List<LegacyPolicy.TimeFence> timeFences = new ArrayList<>(); for (ServicePolicy.TimeFence servicePolicyTimefence : servicePolicy.getTimeFences()) { List<LegacyPolicy.Day> days = new ArrayList<>(); for (ServicePolicy.Day day : servicePolicyTimefence.getDays()) { days.add(LegacyPolicy.Day.fromString(day.toString())); } timeFences.add(new LegacyPolicy.TimeFence( servicePolicyTimefence.getName(), days, servicePolicyTimefence.getStartHour(), servicePolicyTimefence.getStartMinute(), servicePolicyTimefence.getEndHour(), servicePolicyTimefence.getEndMinute(), servicePolicyTimefence.getTimeZone()) ); } return new LegacyPolicy(amount, inherence, knownledge, possession, denyRootedJailbroken, geoFences, timeFences); }

Target:
LegacyPolicy getLegacyPolicyFromServicePolicy(ServicePolicy servicePolicy) { List<GeoCircleFence> geoFences = null; if (servicePolicy.getLocations() != null) { if (!servicePolicy.getLocations().isEmpty()) { geoFences = new ArrayList<>(); for (ServicePolicy.Location location : servicePolicy.getLocations()) { geoFences.add(getGeoCircleFenceFromLocation(location)); } } } Integer requiredFactors = servicePolicy.getRequiredFactors(); int amount = (requiredFactors != null) ? requiredFactors : 0; Boolean inherence = servicePolicy.isInherenceFactorRequired(); Boolean knowledge = servicePolicy.isKnowledgeFactorRequired(); Boolean possession = servicePolicy.isPossessionFactorRequired(); boolean denyRootedJailbroken = (servicePolicy.isJailBreakProtectionEnabled() != null) ? servicePolicy.isJailBreakProtectionEnabled() : false; List<LegacyPolicy.TimeFence> timeFences = new ArrayList<>(); for (ServicePolicy.TimeFence servicePolicyTimefence : servicePolicy.getTimeFences()) { List<LegacyPolicy.Day> days = new ArrayList<>(); for (ServicePolicy.Day day : servicePolicyTimefence.getDays()) { days.add(LegacyPolicy.Day.fromString(day.toString())); } timeFences.add(new LegacyPolicy.TimeFence( servicePolicyTimefence.getName(), days, servicePolicyTimefence.getStartHour(), servicePolicyTimefence.getStartMinute(), servicePolicyTimefence.getEndHour(), servicePolicyTimefence.getEndMinute(), servicePolicyTimefence.getTimeZone()) ); } return new LegacyPolicy(amount, inherence, knowledge, possession, denyRootedJailbroken, geoFences, timeFences); }
Source:
EurekaInterestClientImpl(final SourcedEurekaRegistry<InstanceInfo> registry, ChannelFactory<InterestChannel> channelFactory, int retryWaitMillis) { this.registry = registry; this.interestTracker = new InterestTracker(); this.isShutdown = new AtomicBoolean(false); RetryableConnectionFactory<InterestChannel> retryableConnectionFactory = new RetryableConnectionFactory<>(channelFactory); Observable<Interest<InstanceInfo>> opStream = interestTracker.interestChangeStream(); Func2<InterestChannel, Interest<InstanceInfo>, Observable<Void>> executeOnChannel = new Func2<InterestChannel, Interest<InstanceInfo>, Observable<Void>>() { @Override public Observable<Void> call(InterestChannel interestChannel, Interest<InstanceInfo> interest) { return interestChannel.change(interest); } }; this.retryableConnection = retryableConnectionFactory.singleOpConnection(opStream, executeOnChannel); retryableConnection.getChannelObservable() .flatMap(new Func1<InterestChannel, Observable<Long>>() { @Override public Observable<Long> call(InterestChannel interestChannel) { if (interestChannel instanceof Sourced) { Source toRetain = ((Sourced) interestChannel).getSource(); return registry.evictAllExcept(Source.matcherFor(toRetain)); } return Observable.empty(); } }) .subscribe(new Subscriber<Long>() { @Override public void onCompleted() { logger.info("Completed one round of eviction due to a new interestChannel creation"); } @Override public void onError(Throwable e) { logger.warn("OnError in one round of eviction due to a new interestChannel creation"); } @Override public void onNext(Long aLong) { logger.info("Evicted instances in one round of eviction due to a new interestChannel creation", aLong); } }); retryableConnection.getRetryableLifecycle() .retryWhen(new RetryStrategyFunc(retryWaitMillis)) .subscribe(new Subscriber<Void>() { @Override public void onCompleted() { logger.info("channel onCompleted"); } @Override public void onError(Throwable e) { logger.error("Lifecycle closed with an error"); } @Override public void onNext(Void aVoid) { } }); }

Target:
EurekaInterestClientImpl(final SourcedEurekaRegistry<InstanceInfo> registry, ChannelFactory<InterestChannel> channelFactory, int retryWaitMillis) { super(registry, retryWaitMillis); this.interestTracker = new InterestTracker(); RetryableConnectionFactory<InterestChannel> retryableConnectionFactory = new RetryableConnectionFactory<>(channelFactory); Observable<Interest<InstanceInfo>> opStream = interestTracker.interestChangeStream(); Func2<InterestChannel, Interest<InstanceInfo>, Observable<Void>> executeOnChannel = new Func2<InterestChannel, Interest<InstanceInfo>, Observable<Void>>() { @Override public Observable<Void> call(InterestChannel interestChannel, Interest<InstanceInfo> interest) { return interestChannel.change(interest); } }; this.retryableConnection = retryableConnectionFactory.singleOpConnection(opStream, executeOnChannel); registryEvictionSubscribe(retryableConnection); lifecycleSubscribe(retryableConnection); }
Source:
public GameBuilder defaultValues() { game.setFeaturedMod(KnownFeaturedMod.DEFAULT.getTechnicalName()); game.setFeaturedModVersions(FXCollections.emptyObservableMap()); game.setVictoryCondition(VictoryCondition.DEMORALIZATION); game.setHost("Host"); game.setMapFolderName("mapName"); game.setNumPlayers(1); game.setNumPlayers(2); game.setSimMods(FXCollections.emptyObservableMap()); game.setStatus(GameStatus.OPEN); game.setTitle("Title"); game.setTeams(FXCollections.emptyObservableMap()); game.setId(1); game.setMaxRating(800); game.setMaxRating(1300); game.setStartTime(Instant.now()); game.setGameType(GameType.CUSTOM); return this; }

Target:
public GameBuilder defaultValues() { game.setFeaturedMod(KnownFeaturedMod.DEFAULT.getTechnicalName()); game.setFeaturedModVersions(FXCollections.emptyObservableMap()); game.setVictoryCondition(VictoryCondition.DEMORALIZATION); game.setHost("Host"); game.setMapFolderName("mapName"); game.setNumPlayers(1); game.setNumPlayers(2); game.setSimMods(FXCollections.emptyObservableMap()); game.setStatus(GameStatus.OPEN); game.setTitle("Title"); game.setTeams(FXCollections.emptyObservableMap()); game.setId(1); game.setMinRating(800); game.setMaxRating(1300); game.setStartTime(Instant.now()); game.setGameType(GameType.CUSTOM); return this; }
Source:
public ATCommandResponse sendATCommand(ATCommand command) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isConnected()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); ATCommandResponse response = null; switch (getOperatingMode()) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(); case API: case API_ESCAPE: XBeeAPIPacket packet = new ATCommandPacket(getNextFrameID(), command.getCommand(), command.getParameter()); try { ATCommandResponsePacket answerPacket = (ATCommandResponsePacket)sendXBeePacket(packet); response = new ATCommandResponse(command, answerPacket.getCommandData(), answerPacket.getStatus()); } catch (InvalidOperatingModeException e) { } catch (ClassCastException e1) { System.err.println("Received an invalid packet type after sending an AT Command packet."); e1.printStackTrace(); } } return response; }

Target:
public ATCommandResponse sendATCommand(ATCommand command) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (!connectionInterface.isOpen()) throw new NullPointerException("AT command cannot be null."); ATCommandResponse response = null; switch (getOperatingMode()) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(); case API: case API_ESCAPE: XBeeAPIPacket packet = new ATCommandPacket(getNextFrameID(), command.getCommand(), command.getParameter()); try { ATCommandResponsePacket answerPacket = (ATCommandResponsePacket)sendXBeePacket(packet); response = new ATCommandResponse(command, answerPacket.getCommandData(), answerPacket.getStatus()); } catch (InvalidOperatingModeException e) { } catch (ClassCastException e1) { System.err.println("Received an invalid packet type after sending an AT Command packet."); e1.printStackTrace(); } } return response; }
Source:
private double correctedCentralWavelength() { if (_mode instanceof Imaging) { _Filter = Filter.fromFile(getPrefix(), params.filter().get().name(), getDirectory() + "/"); return (int) _Filter.getEffectiveWavelength(); } else if (!isXDispUsed()) { return params.centralWavelength().toNanometers(); } else { return XDISP_CENTRAL_WAVELENGTH; } }

Target:
private double correctedCentralWavelength() { if (_mode instanceof Imaging) { _Filter = Filter.fromFile(getPrefix(), getFilter().name(), getDirectory() + "/"); return _Filter.getEffectiveWavelength(); } else if (!isXDispUsed()) { return params.centralWavelength().toNanometers(); } else { return XDISP_CENTRAL_WAVELENGTH; } }
Source:
public void setupCache() throws Exception { globalConfig = new GlobalConfigurationBuilder(); globalConfig.globalJmxStatistics().disable(); globalConfig.globalJmxStatistics().mBeanServerLookup(null); GlobalAuthorizationConfigurationBuilder globalRoles = globalConfig.security().authorization() .principalRoleMapper(getPrincipalRoleMapper()); cacheConfig = new ConfigurationBuilder(); cacheConfig.transaction().lockingMode(LockingMode.PESSIMISTIC); cacheConfig.invocationBatching().enable(); cacheConfig.jmxStatistics().disable(); AuthorizationConfigurationBuilder authConfig = cacheConfig.security().authorization().enable(); Map<String, AuthorizationPermission[]> rolePermissionMap = getRolePermissionMap(); for (Entry<String, AuthorizationPermission[]> role : rolePermissionMap.entrySet()) { authConfig = authConfig.role(role.getKey()); GlobalRoleConfigurationBuilder roleBuilder = globalRoles.role(role.getKey()); for (AuthorizationPermission permission : role.getValue()) { roleBuilder = roleBuilder.permission(permission); } } Subject admin = getAdminSubject(); Subject.doAs(admin, new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { manager = new DefaultCacheManager(globalConfig.build()); manager.defineConfiguration(CACHE_NAME, cacheConfig.build()); secureCache = manager.getCache(CACHE_NAME); secureCache.put("predefined key", "predefined value"); return null; } }); }

Target:
public void setupCache() throws Exception { globalConfig = new GlobalConfigurationBuilder(); globalConfig.globalJmxStatistics().disable(); globalConfig.globalJmxStatistics().mBeanServerLookup(null); GlobalAuthorizationConfigurationBuilder globalRoles = globalConfig.security().authorization() .principalRoleMapper(getPrincipalRoleMapper()); cacheConfig = new ConfigurationBuilder(); cacheConfig.transaction().lockingMode(LockingMode.PESSIMISTIC); cacheConfig.invocationBatching().enable(); cacheConfig.jmxStatistics().disable(); AuthorizationConfigurationBuilder authConfig = cacheConfig.security().authorization().enable(); Map<String, AuthorizationPermission[]> rolePermissionMap = getRolePermissionMap(); for (Entry<String, AuthorizationPermission[]> role : rolePermissionMap.entrySet()) { authConfig = authConfig.role(role.getKey()); GlobalRoleConfigurationBuilder roleBuilder = globalRoles.role(role.getKey()); for (AuthorizationPermission permission : role.getValue()) { roleBuilder = roleBuilder.permission(permission); } } Subject admin = getAdminSubject(); Subject.doAs(admin, new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { manager = new DefaultCacheManager(globalConfig.build()); manager.defineConfiguration(CACHE_NAME, cacheConfig.build()); secureCache = manager.getCache(CACHE_NAME); secureCache.put(TEST_ENTRY_KEY, TEST_ENTRY_VALUE); return null; } }); }
Source:
public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof NegativeNodeLocationFilter)) return false; return (this.toString().equals(obj.toString())); }

Target:
public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof NegativeLocationFilter)) return false; return (this.toString().equals(obj.toString())); }
Source:
public GroupDetail renameGroup(final AccountGroup.Id groupId, final String newName) throws OrmException, NameAlreadyUsedException, NoSuchGroupException, InvalidNameException { final GroupControl ctl = groupControlFactory.validateFor(groupId); final AccountGroup group = db.accountGroups().get(groupId); if (group == null || !ctl.isOwner()) { throw new NoSuchGroupException(groupId); } if (newName.isEmpty()) { throw new InvalidNameException(); } final AccountGroup.NameKey old = group.getNameKey(); final AccountGroup.NameKey key = new AccountGroup.NameKey(newName); try { final AccountGroupName id = new AccountGroupName(key, groupId); db.accountGroupNames().insert(Collections.singleton(id)); } catch (OrmDuplicateKeyException dupeErr) { AccountGroupName other = db.accountGroupNames().get(key); if (other != null && other.getId().equals(groupId)) { return groupDetailFactory.create(groupId).call(); } throw new NameAlreadyUsedException(); } group.setNameKey(key); db.accountGroups().update(Collections.singleton(group)); AccountGroupName priorName = db.accountGroupNames().get(old); if (priorName != null) { db.accountGroupNames().delete(Collections.singleton(priorName)); } groupCache.evict(group); groupCache.evictAfterRename(old, key); renameGroupOpFactory.create( currentUser.newCommitterIdent(new Date(), TimeZone.getDefault()), group.getGroupUUID(), old.get(), newName).start(0, TimeUnit.MILLISECONDS); return groupDetailFactory.create(groupId).call(); }

Target:
public GroupDetail renameGroup(final AccountGroup.Id groupId, final String newName) throws OrmException, NameAlreadyUsedException, NoSuchGroupException, InvalidNameException { final GroupControl ctl = groupControlFactory.validateFor(groupId); final AccountGroup group = db.accountGroups().get(groupId); if (group == null || !ctl.isOwner()) { throw new NoSuchGroupException(groupId); } if (newName.trim().isEmpty()) { throw new InvalidNameException(); } final AccountGroup.NameKey old = group.getNameKey(); final AccountGroup.NameKey key = new AccountGroup.NameKey(newName); try { final AccountGroupName id = new AccountGroupName(key, groupId); db.accountGroupNames().insert(Collections.singleton(id)); } catch (OrmDuplicateKeyException dupeErr) { AccountGroupName other = db.accountGroupNames().get(key); if (other != null && other.getId().equals(groupId)) { return groupDetailFactory.create(groupId).call(); } throw new NameAlreadyUsedException(); } group.setNameKey(key); db.accountGroups().update(Collections.singleton(group)); AccountGroupName priorName = db.accountGroupNames().get(old); if (priorName != null) { db.accountGroupNames().delete(Collections.singleton(priorName)); } groupCache.evict(group); groupCache.evictAfterRename(old, key); renameGroupOpFactory.create( currentUser.newCommitterIdent(new Date(), TimeZone.getDefault()), group.getGroupUUID(), old.get(), newName).start(0, TimeUnit.MILLISECONDS); return groupDetailFactory.create(groupId).call(); }
Source:
private void initNuageVspVpcOffering() { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { if (_vpcOffDao.findByUniqueName(nuageVPCOfferingName) == null) { s_logger.debug("Creating default Nuage VPC offering " + nuageVPCOfferingName); Map<Network.Service, Set<Network.Provider>> svcProviderMap = new HashMap<Network.Service, Set<Network.Provider>>(); Set<Network.Provider> nuageProviders = new HashSet<Network.Provider>(); nuageProviders.add(Network.Provider.NuageVsp); svcProviderMap.put(Network.Service.Connectivity, nuageProviders); svcProviderMap.put(Network.Service.Dhcp, nuageProviders); svcProviderMap.put(Network.Service.StaticNat, nuageProviders); svcProviderMap.put(Network.Service.SourceNat, nuageProviders); svcProviderMap.put(Network.Service.NetworkACL, nuageProviders); Set<Network.Provider> userDataProviders = new HashSet<Network.Provider>(); userDataProviders.add(Network.Provider.VPCVirtualRouter); svcProviderMap.put(Network.Service.UserData, userDataProviders); createVpcOffering(nuageVPCOfferingName, nuageVPCOfferingDisplayText, svcProviderMap, true, VpcOffering.State.Enabled, null); } } }); }

Target:
private void initNuageVspVpcOffering() { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { if (_vpcOffDao.findByUniqueName(nuageVPCOfferingName) == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Creating default Nuage VPC offering " + nuageVPCOfferingName); } Map<Network.Service, Set<Network.Provider>> svcProviderMap = Maps.newHashMap(NUAGE_VSP_VPC_SERVICE_MAP); Set<Network.Provider> userDataProviders = Collections.singleton(Network.Provider.VPCVirtualRouter); svcProviderMap.put(Network.Service.UserData, userDataProviders); createVpcOffering(nuageVPCOfferingName, nuageVPCOfferingDisplayText, svcProviderMap, true, VpcOffering.State.Enabled, null); } } }); }
Source:
private void createIssues(InputFile file, SensorContext context, String repo) { RuleKey ruleKey = RuleKey.of(repo, RULE_KEY); for (int line = 1; line <= file.lines(); line++) { TextRange text = file.selectLine(line); if (text.end().lineOffset() > 0) { NewIssue newIssue = context.newIssue(); newIssue .forRule(ruleKey) .at(newIssue.newLocation() .on(file) .at(text) .message("This bug issue is generated on each line")) .save(); } } }

Target:
private static void createIssues(InputFile file, SensorContext context, String repo) { RuleKey ruleKey = RuleKey.of(repo, RULE_KEY); for (int line = 1; line <= file.lines(); line++) { TextRange text = file.selectLine(line); if (text.end().lineOffset() == 0) { continue; } NewIssue newIssue = context.newIssue(); newIssue .forRule(ruleKey) .at(newIssue.newLocation() .on(file) .at(text) .message("This bug issue is generated on each line")) .save(); } }
Source:
public URI getPageUri(final UriComponentsBuilder uriBuilder) { return uriBuilder .queryParam("offset", offset) .queryParam("limit", limit) .build().toUri(); }

Target:
public URI getPageUri(final UriComponentsBuilder uriBuilder) { return notNull(uriBuilder, "uriBuilder") .queryParam("offset", offset) .queryParam("limit", limit) .build().toUri(); }
Source:
protected IPAssignment allocateIp(IpAddress ipAddress, Network network) { Instance instance = getInstanceForPrimaryIp(ipAddress); IPAssignment ip = null; String requestedIp = null; if (instance != null) { String allocatedIpAddress = DataAccessor .fieldString(instance, InstanceConstants.FIELD_ALLOCATED_IP_ADDRESS); if (allocatedIpAddress != null) { ip = new IPAssignment(allocatedIpAddress, null); } requestedIp = DataAccessor.fieldString(instance, InstanceConstants.FIELD_REQUESTED_IP_ADDRESS); } if (ip == null) { ip = networkService.assignIpAddress(network, ipAddress, Arrays.asList(StringUtils.stripAll(StringUtils.split(requestedIp, ",")))); if (ip == null) { objectProcessManager.scheduleStandardProcess(StandardProcess.DEACTIVATE, ipAddress, null); throw new ResourceExhaustionException("IP allocation error", "Failed to allocate IP from subnet", ipAddress); } } return ip; }

Target:
protected IPAssignment allocateIp(IpAddress ipAddress, Network network) { Instance instance = getInstanceForPrimaryIp(ipAddress); IPAssignment ip = null; String requestedIp = null; if (instance != null) { String allocatedIpAddress = DataAccessor .fieldString(instance, InstanceConstants.FIELD_ALLOCATED_IP_ADDRESS); if (allocatedIpAddress != null) { ip = new IPAssignment(allocatedIpAddress, null); } requestedIp = DataAccessor.fieldString(instance, InstanceConstants.FIELD_REQUESTED_IP_ADDRESS); } if (ip == null) { List<String> list = new ArrayList<>(); if (!StringUtils.isEmpty(requestedIp)) { list = Arrays.asList(StringUtils.stripAll(StringUtils.split(requestedIp, ","))); } ip = networkService.assignIpAddress(network, ipAddress, list); if (ip == null) { objectProcessManager.scheduleStandardProcess(StandardProcess.DEACTIVATE, ipAddress, null); throw new ResourceExhaustionException("IP allocation error", "Failed to allocate IP from subnet", ipAddress); } } return ip; }
Source:
private BBox createBbox() { if (!containsParameter(BBOX)) { return null; } String bboxValue = getAsString(BBOX); BBox bbox; if (bboxValue.matches("^(\\d*\\.?\\d*\\,){3}(\\d*\\.?\\d*)$")) { bbox = new BBox(bboxValue); } else { bbox = parseJson(bboxValue, BBox.class); } bbox.setLl(convertToCrs84(bbox.getLl())); bbox.setUr(convertToCrs84(bbox.getUr())); return bbox; }

Target:
private BBox createBbox() { if (!containsParameter(BBOX)) { return null; } String bboxValue = getAsString(BBOX); BBox bbox; if (bboxValue.matches("^(\\d*\\.?\\d*\\,){3}(\\d*\\.?\\d*)$")) { String[] coordArray = bboxValue.split("\\,"); GeojsonPoint ll = GeojsonPoint.createWithCoordinates(new Double[] {Double.valueOf(coordArray[0]), Double.valueOf(coordArray[1])}); GeojsonPoint ur = GeojsonPoint.createWithCoordinates(new Double[] {Double.valueOf(coordArray[2]), Double.valueOf(coordArray[3])}); bbox = new BBox(ll, ur); } else { bbox = parseJson(bboxValue, BBox.class); } bbox.setLl(convertToCrs84(bbox.getLl())); bbox.setUr(convertToCrs84(bbox.getUr())); return bbox; }
Source:
protected boolean isHotPlugSupported() { if (FeatureSupported.hotPlug(getVds().getVdsGroupCompatibilityVersion())) { return true; } addCanDoActionMessage(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); return false; }

Target:
protected boolean isHotPlugSupported() { if (FeatureSupported.hotPlug(getVds().getVdsGroupCompatibilityVersion())) { return true; } return failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); }
Source:
private Mutation getMutation(Cell cell, TimestampRangeDelete delete, long rangeTombstoneCassandraTimestamp, ToLongFunction<TimestampRangeDelete> exclusiveTimestampExtractor) { if (delete.deleteSentinels()) { return Mutations.rangeTombstoneIncludingSentinelForColumn( cell.getColumnName(), exclusiveTimestampExtractor.applyAsLong(delete), rangeTombstoneCassandraTimestamp); } return Mutations.rangeTombstoneForColumn( cell.getColumnName(), exclusiveTimestampExtractor.applyAsLong(delete), rangeTombstoneCassandraTimestamp); }

Target:
private Mutation getMutation(Cell cell, TimestampRangeDelete delete, long rangeTombstoneCassandraTimestamp, ToLongFunction<TimestampRangeDelete> exclusiveTimestampExtractor) { return Mutations.fromTimestampRangeDelete( cell.getColumnName(), delete, rangeTombstoneCassandraTimestamp, exclusiveTimestampExtractor); }
Source:
public Transaction beginTransaction(MuleContext muleContext) throws TransactionException { Transaction transaction = new ExtensionTransaction(muleContext); transaction.begin(); return transaction; }

Target:
public Transaction beginTransaction(MuleContext muleContext) throws TransactionException { try { return this.beginTransaction(muleContext.getConfiguration().getId(), ((MuleContextWithRegistry) muleContext).getRegistry() .lookupObject(NotificationDispatcher.class), muleContext.getTransactionFactoryManager(), muleContext.getTransactionManager(), 10000); } catch (RegistrationException e) { throw new TransactionException(cannotStartTransaction("Extension"), e); } }
Source:
public Mono<Response<Key>> getKeyWithResponse(KeyProperties keyProperties) { Objects.requireNonNull(keyProperties, "The Key Base parameter cannot be null."); return withContext(context -> getKeyWithResponse(keyProperties.getName(), keyProperties.getVersion() == null ? "" : keyProperties.getVersion(), context)); }

Target:
public Mono<Response<Key>> getKeyWithResponse(KeyProperties keyProperties) { Objects.requireNonNull(keyProperties, "The Key Properties parameter cannot be null."); return withContext(context -> getKeyWithResponse(keyProperties.getName(), keyProperties.getVersion() == null ? "" : keyProperties.getVersion(), context)); }
Source:
private void handleOnSubmit() { Catalog catalog = getCatalog(); WorkspaceInfo workspace = (WorkspaceInfo) model.getObject(); NamespaceInfo namespace = catalog.getFactory().createNamespace(); namespace.setPrefix(workspace.getName()); namespace.setURI(nsUriTextField.getDefaultModelObjectAsString()); namespace.setIsolated(workspace.isIsolated()); if (!validateAndReport(() -> catalog.validate(workspace, true)) || !validateAndReport(() -> catalog.validate(namespace, true))) { return; } try { catalog.add(workspace); catalog.add(namespace); } catch (Exception exception) { LOGGER.log(Level.INFO, "Error storing workspace related objects.", exception); cleanAndReport(exception); } if (infoPanel.defaultWs) { catalog.setDefaultWorkspace(workspace); } try { if (accessdataPanel != null) accessdataPanel.save(); } catch (IOException e) { LOGGER.log( Level.INFO, "Error saving access rules associated to workspace " + workspace.getName(), e); error(e.getMessage() == null ? e.toString() : e.getMessage()); } doReturn(WorkspacePage.class); }

Target:
private void handleOnSubmit() { Catalog catalog = getCatalog(); WorkspaceInfo workspace = (WorkspaceInfo) model.getObject(); NamespaceInfo namespace = catalog.getFactory().createNamespace(); namespace.setPrefix(workspace.getName()); namespace.setURI(nsUriTextField.getDefaultModelObjectAsString()); namespace.setIsolated(workspace.isIsolated()); if (!validateAndReport(() -> catalog.validate(workspace, true)) || !validateAndReport(() -> catalog.validate(namespace, true))) { return; } try { catalog.add(workspace); catalog.add(namespace); } catch (Exception exception) { LOGGER.log(Level.INFO, "Error storing workspace related objects.", exception); cleanAndReport(exception); } if (infoPanel.defaultWs) { catalog.setDefaultWorkspace(workspace); } try { if (accessdataPanel != null) accessdataPanel.save(); doReturn(WorkspacePage.class); } catch (IOException e) { LOGGER.log( Level.INFO, "Error saving access rules associated to workspace " + workspace.getName(), e); error(e.getMessage() == null ? e.toString() : e.getMessage()); } }
Source:
public ChatComponent setItalic(boolean italic) { $lock.writeLock().lock(); if (this.italic == null) this.italic = new AtomicBoolean(italic); else this.italic.set(italic); $lock.writeLock().unlock(); return this; }

Target:
public ChatComponent setItalic(boolean italic) { if (this.italic == null) this.italic = new AtomicBoolean(italic); else this.italic.set(italic); return this; }
Source:
public boolean configure( StaplerRequest req, JSONObject formData) throws FormException { this.stashRootUrl = null; this.ignoreUnverifiedSsl = false; this.includeBuildNumberInKey = false; this.credentialsId = null; this.projectKey = null; this.prependParentProjectKey = false; this.disableInprogressNotification = false; this.considerUnstableAsSuccess = false; req.bindJSON(this, formData); save(); return true; }

Target:
public boolean configure( StaplerRequest req, JSONObject formData) throws FormException { this.considerUnstableAsSuccess = false; this.credentialsId = null; this.disableInprogressNotification = false; this.ignoreUnverifiedSsl = false; this.includeBuildNumberInKey = false; this.prependParentProjectKey = false; this.projectKey = null; this.stashRootUrl = null; req.bindJSON(this, formData); save(); return true; }
Source:
private String initialConnectionName() throws CoreException { String name = DEFAULT_CONNECTION_NAME; int count = 1; while (getSelectedConnectionType().getConnection(name) != null) { name = DEFAULT_CONNECTION_NAME + " " + count++; } return name; }

Target:
private String initialConnectionName() { String name = DEFAULT_CONNECTION_NAME; int count = 1; while (getSelectedConnectionType().getConnection(name) != null) { name = DEFAULT_CONNECTION_NAME + " " + count++; } return name; }
Source:
public static boolean isEmpty(Object[] array) { return array == null ? true : array.length == 0; }

Target:
public static boolean isEmpty(Object[] array) { return array == null || array.length == 0; }
Source:
protected void initActionContext(ActionContext actionContext) { actionContext.setParameters(HttpParameters.create(request.getParameterMap()).build()); initSession(actionContext); ActionContext.bound(actionContext); }

Target:
protected void initActionContext(ActionContext actionContext) { actionContext.setParameters(HttpParameters.create(request.getParameterMap()).build()); initSession(actionContext); ActionContext.bind(actionContext); }
Source:
public void userCannotSignUpWithExistingUsernameDesktopSzl() { RegisterPage form = performSignUpExpectingFailureOnDesktopAs(createUserWithExistingUsername()); assertEquals(form.getError(), "Nazwa użytkownika jest już wykorzystywana"); }

Target:
public void userCannotSignUpWithExistingUsernameDesktopSzl() { RegisterPage form = performSignUpExpectingFailureOnDesktopAs(createUserWithExistingUsername()); assertEquals(form.getError(), USERNAME_TAKEN_MSG_SZL); }
Source:
public void testConvertToExtended() throws Exception { Method method = Code93Writer.class.getDeclaredMethod("convertToExtended", String.class); method.setAccessible(true); String src = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%"; String dst = (String) method.invoke(null, src); assertEquals(src, dst); }

Target:
public void testConvertToExtended() throws Exception { String src = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%"; String dst = Code93Writer.convertToExtended(src); assertEquals(src, dst); }
Source:
public static DomainTrust[] getDomainTrusts(String serverName) { IntByReference domainCount = new IntByReference(); PointerByReference domainsPointerRef = new PointerByReference(); int rc = Netapi32.INSTANCE.DsEnumerateDomainTrusts(serverName, DsGetDC.DS_DOMAIN_VALID_FLAGS, domainsPointerRef, domainCount); if(W32Errors.NO_ERROR != rc) { throw new Win32Exception(rc); } try { PDS_DOMAIN_TRUSTS domains = new PDS_DOMAIN_TRUSTS(domainsPointerRef.getValue()); int domainCountValue = domainCount.getValue(); ArrayList<DomainTrust> trusts = new ArrayList<DomainTrust>(domainCountValue); for(DS_DOMAIN_TRUSTS trust : domains.getTrusts(domainCountValue)) { DomainTrust t = new DomainTrust(); if (trust.DnsDomainName != null) { t.DnsDomainName = trust.DnsDomainName.toString(); } if (trust.NetbiosDomainName != null) { t.NetbiosDomainName = trust.NetbiosDomainName.toString(); } t.DomainSid = trust.DomainSid; if (trust.DomainSid != null) { t.DomainSidString = Advapi32Util.convertSidToStringSid(trust.DomainSid); } t.DomainGuid = trust.DomainGuid; if (trust.DomainGuid != null) { t.DomainGuidString = Ole32Util.getStringFromGUID(trust.DomainGuid); } t.flags = trust.Flags; trusts.add(t); } return trusts.toArray(new DomainTrust[0]); } finally { rc = Netapi32.INSTANCE.NetApiBufferFree(domainsPointerRef.getValue()); if(W32Errors.NO_ERROR != rc) { throw new Win32Exception(rc); } } }

Target:
public static DomainTrust[] getDomainTrusts(String serverName) { IntByReference domainCount = new IntByReference(); PointerByReference domainsPointerRef = new PointerByReference(); int rc = Netapi32.INSTANCE.DsEnumerateDomainTrusts(serverName, DsGetDC.DS_DOMAIN_VALID_FLAGS, domainsPointerRef, domainCount); if(W32Errors.NO_ERROR != rc) { throw new Win32Exception(rc); } try { DS_DOMAIN_TRUSTS domains = new DS_DOMAIN_TRUSTS(domainsPointerRef.getValue()); int domainCountValue = domainCount.getValue(); ArrayList<DomainTrust> trusts = new ArrayList<DomainTrust>(domainCountValue); for(DS_DOMAIN_TRUSTS trust : (DS_DOMAIN_TRUSTS[]) domains.toArray(new DS_DOMAIN_TRUSTS[domainCountValue])) { DomainTrust t = new DomainTrust(); if (trust.DnsDomainName != null) { t.DnsDomainName = trust.DnsDomainName.toString(); } if (trust.NetbiosDomainName != null) { t.NetbiosDomainName = trust.NetbiosDomainName.toString(); } t.DomainSid = trust.DomainSid; if (trust.DomainSid != null) { t.DomainSidString = Advapi32Util.convertSidToStringSid(trust.DomainSid); } t.DomainGuid = trust.DomainGuid; if (trust.DomainGuid != null) { t.DomainGuidString = Ole32Util.getStringFromGUID(trust.DomainGuid); } t.flags = trust.Flags; trusts.add(t); } return trusts.toArray(new DomainTrust[0]); } finally { rc = Netapi32.INSTANCE.NetApiBufferFree(domainsPointerRef.getValue()); if(W32Errors.NO_ERROR != rc) { throw new Win32Exception(rc); } } }
Source:
public void saveRelationship(TaskExecution taskExecution, JobExecution jobExecution) { jdbcTemplate.update(getQuery(INSERT_STATEMENT), taskExecution.getExecutionId(), jobExecution.getId()); }

Target:
public void saveRelationship(TaskExecution taskExecution, JobExecution jobExecution) { Assert.notNull(taskExecution, "A taskExecution is required"); Assert.notNull(jobExecution, "A jobExecution is required"); jdbcTemplate.update(getQuery(INSERT_STATEMENT), taskExecution.getExecutionId(), jobExecution.getId()); }
Source:
private void setUpRegions() { server1.invoke(() -> { Cache cache = ClusterStartupRule.getCache(); assertThat(cache).isNotNull(); RegionFactory<String, String> dataRegionFactory = cache.createRegionFactory(RegionShortcut.PARTITION); Region<String, String> region = dataRegionFactory.create(REGION_ONE_NAME); for (int i = 0; i < 10; i++) { region.put("key" + (i + 200), "value" + (i + 200)); } region = dataRegionFactory.create(REGION_TWO_NAME); for (int i = 0; i < 100; i++) { region.put("key" + (i + 200), "value" + (i + 200)); } }); server2.invoke(() -> { Cache cache = ClusterStartupRule.getCache(); assertThat(cache).isNotNull(); RegionFactory<String, String> dataRegionFactory = cache.createRegionFactory(RegionShortcut.PARTITION); Region<String, String> region = dataRegionFactory.create(REGION_ONE_NAME); for (int i = 0; i < 100; i++) { region.put("key" + (i + 400), "value" + (i + 400)); } region = dataRegionFactory.create(REGION_THREE_NAME); for (int i = 0; i < 10; i++) { region.put("key" + (i + 200), "value" + (i + 200)); } }); }

Target:
private void setUpRegions() { server1.invoke(() -> { Cache cache = ClusterStartupRule.getCache(); assertThat(cache).isNotNull(); RegionFactory<String, String> dataRegionFactory = cache.createRegionFactory(RegionShortcut.PARTITION); Region<String, String> region1 = dataRegionFactory.create(REGION_ONE_NAME); Region<String, String> region2 = dataRegionFactory.create(REGION_TWO_NAME); for (int i = 0; i < ENTRIES_PER_REGION; i++) { region1.put("key" + i, "Value" + i); region2.put("key" + i, "Value" + i); } }); server2.invoke(() -> { Cache cache = ClusterStartupRule.getCache(); assertThat(cache).isNotNull(); RegionFactory<String, String> dataRegionFactory = cache.createRegionFactory(RegionShortcut.PARTITION); dataRegionFactory.create(REGION_ONE_NAME); Region<String, String> region3 = dataRegionFactory.create(REGION_THREE_NAME); for (int i = 0; i < ENTRIES_PER_REGION; i++) { region3.put("key" + i, "Value" + i); } }); }
Source:
public void testVariantIds() { Set<String> emptySet = new HashSet<>(); checkIds(factory, "1\t1000\trs123\tC\tT\t.\t.\t.", emptySet); checkIds(factory, "1\t1000\trs123;rs456\tC\tT\t.\t.\t.", emptySet); checkIds(factory, "1\t1000\t.\tC\tT\t.\t.\t.", emptySet); VariantVcfFactory accessionedVariantFactory = instantiateAbstractVcfFactory(); accessionedVariantFactory.setIncludeIds(true); checkIds(accessionedVariantFactory, "1\t1000\trs123\tC\tT\t.\t.\t.", Collections.singleton("rs123")); checkIds(accessionedVariantFactory, "1\t1000\trs123;.\tC\tT\t.\t.\t.", Collections.singleton("rs123")); checkIds(accessionedVariantFactory, "1\t1000\trs123;rs456\tC\tT\t.\t.\t.", Stream.of("rs123", "rs456").collect(Collectors.toSet())); }

Target:
public void testVariantIds() { Set<String> emptySet = Collections.emptySet(); checkIds(factory, "1\t1000\trs123\tC\tT\t.\t.\t.", emptySet); checkIds(factory, "1\t1000\trs123;rs456\tC\tT\t.\t.\t.", emptySet); checkIds(factory, "1\t1000\t.\tC\tT\t.\t.\t.", emptySet); VariantVcfFactory accessionedVariantFactory = instantiateAbstractVcfFactory(); accessionedVariantFactory.setIncludeIds(true); checkIds(accessionedVariantFactory, "1\t1000\trs123\tC\tT\t.\t.\t.", Collections.singleton("rs123")); checkIds(factory, "1\t1000\t.\tC\tT\t.\t.\t.", emptySet); checkIds(accessionedVariantFactory, "1\t1000\trs123;.\tC\tT\t.\t.\t.", Collections.singleton("rs123")); checkIds(accessionedVariantFactory, "1\t1000\trs123;rs456\tC\tT\t.\t.\t.", Stream.of("rs123", "rs456").collect(Collectors.toSet())); checkIds(accessionedVariantFactory, "1\t1000\trs123,rs456\tC\tT\t.\t.\t.", Collections.singleton("rs123,rs456")); }
Source:
public DockerImageName apply(DockerImageName original) { final String configuredPrefix = configuration.getEnvVarOrProperty(PREFIX_PROPERTY_KEY, ""); if (!!configuredPrefix.isEmpty()) { log.debug("No prefix is configured"); return original; } boolean isAHubImage = original.getRegistry().isEmpty() || original.getRegistry().equals("docker.io") || original.getRegistry().equals("registry.hub.docker.com"); if (!isAHubImage) { log.debug("Image is not a Docker Hub image - not applying registry/repository change", original); return original; } log.debug( "Applying changes to image name {}: applying prefix '{}'", original, configuredPrefix ); DockerImageName prefixAsImage = DockerImageName.parse(configuredPrefix); return original .withRegistry(prefixAsImage.getRegistry()) .withRepository(prefixAsImage.getRepository() + original.getRepository()); }

Target:
public DockerImageName apply(DockerImageName original) { final String configuredPrefix = configuration.getEnvVarOrProperty(PREFIX_PROPERTY_KEY, ""); if (configuredPrefix.isEmpty()) { log.debug("No prefix is configured"); return original; } boolean isAHubImage = original.getRegistry().isEmpty(); if (!isAHubImage) { log.debug("Image is not a Docker Hub image - not applying registry/repository change", original); return original; } log.debug( "Applying changes to image name {}: applying prefix '{}'", original, configuredPrefix ); DockerImageName prefixAsImage = DockerImageName.parse(configuredPrefix); return original .withRegistry(prefixAsImage.getRegistry()) .withRepository(prefixAsImage.getRepository() + original.getRepository()); }
Source:
public static Collection<String> replaceWith(String propertyName, List<?> items, String separator, int maxNumberOfPrintedItems) { Validate.isTrue(maxNumberOfPrintedItems >= 0); int size = Math.min(maxNumberOfPrintedItems, items.size()); List<String> printedItems = new ArrayList<String>(size); for (int i = 0; i < size; i++) { printedItems.add(String.format("\t%s", String.valueOf(items.get(i)))); } if (items.size() > maxNumberOfPrintedItems) { printedItems.add("\t..."); } ArrayList<String> replacements = new ArrayList<String>(); replacements.add(MessageFormat.format("${0} {1}", propertyName, StringUtils.join(printedItems, separator))); replacements.add(MessageFormat.format("${0}_COUNTER {1}", propertyName, items.size())); return replacements; }

Target:
public static Collection<String> replaceWith(String propertyName, List<?> items, String separator, int maxNumberOfPrintedItems) { Validate.isTrue(maxNumberOfPrintedItems >= 1); Validate.isTrue(StringUtils.isNotEmpty(separator)); int size = Math.min(maxNumberOfPrintedItems, items.size()); List<String> printedItems = new ArrayList<String>(size); for (int i = 0; i < size; i++) { printedItems.add(String.format("\t%s", String.valueOf(items.get(i)))); } if (items.size() > maxNumberOfPrintedItems) { printedItems.add("\t..."); } ArrayList<String> replacements = new ArrayList<String>(); replacements.add(MessageFormat.format("${0} {1}", propertyName, StringUtils.join(printedItems, separator))); replacements.add(MessageFormat.format("${0}_COUNTER {1}", propertyName, items.size())); return replacements; }
Source:
public ResponseEntity deleteDictionary(@PathVariable("tenant") final String tenant, @PathVariable("name") final String name) { final TenantContext context = _contextFactory.getContext(tenant); final Dictionary dictionary = getReferenceDataCatalog(tenant).getDictionary(name); if (dictionary instanceof TextFileDictionary) { try { Files.delete(getResourceFile(context, name).toPath()); } catch (final IOException e) { logger.warn("Synonym catalog file could not be deleted.", e); } } _referenceDataDao.removeDictionary(context, name); return ResponseEntity.noContent().build(); }

Target:
public ResponseEntity<Void> deleteDictionary(@PathVariable("tenant") final String tenant, @PathVariable("name") final String name) { final TenantContext context = _contextFactory.getContext(tenant); final Dictionary dictionary = getReferenceDataCatalog(tenant).getDictionary(name); if (dictionary instanceof TextFileDictionary) { try { Files.delete(getResourceFile(context, name).toPath()); } catch (final IOException e) { logger.warn("Synonym catalog file could not be deleted.", e); } } _referenceDataDao.removeDictionary(context, name); return ResponseEntity.noContent().build(); }
Source:
public RangerCloudIdentitySyncStatus setAzureCloudIdentityMapping(String envCrn, Map<String, String> azureUserMapping) { Optional<SdxCluster> sdxCluster = getSdxCluster(envCrn); if (sdxCluster.isEmpty()) { return newSyncStatus(RangerCloudIdentitySyncState.NOT_APPLICABLE, "No datalakes associated with the environment."); } if (!isDatalakeRunning(sdxCluster.get())) { return newSyncStatus(RangerCloudIdentitySyncState.NOT_APPLICABLE, "Datalake is not running for the environment."); } return setAzureCloudIdentityMapping(envCrn, sdxCluster.get(), azureUserMapping); }

Target:
public RangerCloudIdentitySyncStatus setAzureCloudIdentityMapping(String envCrn, Map<String, String> azureUserMapping) { Optional<SdxCluster> sdxCluster = getSdxCluster(envCrn); return checkIfUnapplicable(sdxCluster).orElseGet(() -> setAzureCloudIdentityMapping(envCrn, sdxCluster.get(), azureUserMapping)); }
Source:
public ToolInstallation installVersion(String version) { autoInstall.check(); sleep(1000); control("properties/hudson-tools-InstallSourceProperty/installers/id").select(version); return this; }

Target:
public ToolInstallation installVersion(String version) { autoInstall.check(); control("properties/hudson-tools-InstallSourceProperty/installers/id").select(version); return this; }
Source:
private FileObject addFileToWork(WorkObject work, Resource childResc) throws DepositException { PID childPid = PIDs.get(childResc.getURI()); String stagingPath = getPropertyValue(childResc, CdrDeposit.stagingLocation); if (stagingPath == null) { throw new DepositException("No staging location provided for child (" + childResc.getURI() + ") of Work object (" + work.getPid().getQualifiedId() + ")"); } String mimetype = getPropertyValue(childResc, CdrDeposit.mimetype); String sha1 = getPropertyValue(childResc, CdrDeposit.sha1sum); String label = getPropertyValue(childResc, CdrDeposit.label); File file = null; try { URI stagingUri = new URI(stagingPath); file = new File(stagingUri); } catch (URISyntaxException e) { failJob(e, "Unable to staging URI: {0}", stagingPath); } String filename = label != null? label : file.getName(); try (InputStream fileStream = new FileInputStream(file)) { FileObject fileObj = work.addDataFile(childPid, fileStream, filename, mimetype, sha1); metricsClient.incrDepositFileThroughput(getDepositUUID(), file.length()); log.info("Ingested file in for deposit {}", new Object[] {filename, childPid, getDepositPID()}); return fileObj; } catch (FileNotFoundException e) { throw new DepositException("Data file missing for child (" + childPid.getQualifiedId() + ") of work (" + work.getPid().getQualifiedId() + "): " + stagingPath, e); } catch (IOException e) { throw new DepositException("Unable to close inputstream for binary " + childPid.getQualifiedId(), e); } }

Target:
private FileObject addFileToWork(WorkObject work, Resource childResc) throws DepositException { PID childPid = PIDs.get(childResc.getURI()); String stagingPath = getPropertyValue(childResc, CdrDeposit.stagingLocation); if (stagingPath == null) { throw new DepositException("No staging location provided for child (" + childResc.getURI() + ") of Work object (" + work.getPid().getQualifiedId() + ")"); } String mimetype = getPropertyValue(childResc, CdrDeposit.mimetype); String sha1 = getPropertyValue(childResc, CdrDeposit.sha1sum); String label = getPropertyValue(childResc, CdrDeposit.label); File file = null; try { URI stagingUri = new URI(stagingPath); file = new File(stagingUri); } catch (URISyntaxException e) { failJob(e, "Unable to resolve staging URI: {0}", stagingPath); } String filename = label != null? label : file.getName(); try (InputStream fileStream = new FileInputStream(file)) { FileObject fileObj = work.addDataFile(childPid, fileStream, filename, mimetype, sha1); metricsClient.incrDepositFileThroughput(getDepositUUID(), file.length()); log.info("Ingested file in for deposit {}", new Object[] {filename, childPid, getDepositPID()}); return fileObj; } catch (FileNotFoundException e) { throw new DepositException("Data file missing for child (" + childPid.getQualifiedId() + ") of work (" + work.getPid().getQualifiedId() + "): " + stagingPath, e); } catch (IOException e) { throw new DepositException("Unable to close inputstream for binary " + childPid.getQualifiedId(), e); } }
Source:
public Optional<ResourceGroupId> match(SelectionContext context) { if (userRegex.isPresent() && !userRegex.get().matcher(context.getUser()).matches()) { return Optional.empty(); } if (sourceRegex.isPresent()) { String source = context.getSource().orElse(""); if (!sourceRegex.get().matcher(source).matches()) { return Optional.empty(); } } if (!clientTags.isEmpty()) { if (!context.getTags().containsAll(clientTags)) { return Optional.empty(); } } if (queryType.isPresent()) { String contextQueryType = context.getQueryType().orElse(""); if (!queryType.get().equalsIgnoreCase(contextQueryType)) { return Optional.empty(); } } return Optional.of(group.expandTemplate(context)); }

Target:
public Optional<ResourceGroupId> match(SelectionContext context) { if (userRegex.isPresent() && !userRegex.get().matcher(context.getUser()).matches()) { return Optional.empty(); } if (sourceRegex.isPresent()) { String source = context.getSource().orElse(""); if (!sourceRegex.get().matcher(source).matches()) { return Optional.empty(); } } if (!clientTags.isEmpty() && !context.getTags().containsAll(clientTags)) { return Optional.empty(); } if (queryType.isPresent()) { String contextQueryType = context.getQueryType().orElse(""); if (!queryType.get().equalsIgnoreCase(contextQueryType)) { return Optional.empty(); } } return Optional.of(group.expandTemplate(context)); }
Source:
public void retrieveSubjectToken_noRole_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); IOException response = new IOException(); transportFactory.transport.addResponseErrorSequence(response); transportFactory.transport.addResponseSequence(true, false); final AwsCredentials awsCredential = (AwsCredentials) AwsCredentials.newBuilder(AWS_CREDENTIAL) .setHttpTransportFactory(transportFactory) .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); IOException e = assertThrows( IOException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { awsCredential.retrieveSubjectToken(); } }); assertThat(e.getMessage()).isEqualTo("Failed to retrieve AWS IAM role."); }

Target:
public void retrieveSubjectToken_noRole_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); IOException response = new IOException(); transportFactory.transport.addResponseErrorSequence(response); transportFactory.transport.addResponseSequence(true, false); final AwsCredentials awsCredential = (AwsCredentials) AwsCredentials.newBuilder(AWS_CREDENTIAL) .setHttpTransportFactory(transportFactory) .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); IOException e = assertThrows( IOException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { awsCredential.retrieveSubjectToken(); } }); assertEquals("Failed to retrieve AWS IAM role.", e.getMessage()); }