auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void ExecuteVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getInterfaceTranslation()).toString()); this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); if (StringHelper.isNullOrEmpty(getParameters().getInterface().getMacAddress())) { String mac = null; RefObject<String> tempRefObject = new RefObject<String>(mac); MacPoolManager.getInstance().allocateNewMac(tempRefObject); mac = tempRefObject.argvalue; getParameters().getInterface().setMacAddress(mac); } getParameters().getInterface().setSpeed( VmInterfaceType.forValue( getParameters().getInterface().getType()).getSpeed()); getParameters().getInterface().setId(Guid.NewGuid()); getParameters().getInterface().setVmId(getParameters().getVmId()); DbFacade dbFacade = DbFacade.getInstance(); dbFacade .getVmNetworkInterfaceDAO() .save(getParameters().getInterface()); dbFacade .getVmNetworkStatisticsDAO() .save(getParameters().getInterface().getStatistics()); VmDevice vmDevice = VmDeviceUtils.addManagedDevice(new VmDeviceId(getParameters().getInterface().getId(), getParameters().getVmId()), VmDeviceType.INTERFACE, VmDeviceType.BRIDGE, "", true, false); boolean succeded = true; VmDynamic vmDynamic = DbFacade.getInstance().getVmDynamicDAO().get(getParameters().getVmId()); if (vmDynamic.getstatus() == VMStatus.Up) { succeded = hotPlugNic(vmDevice, vmDynamic); if (!succeded) { getReturnValue().getExecuteFailedMessages().add("Failed hot-plugging nic to VM"); } } setSucceeded(succeded); }

Target:
protected void ExecuteVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getInterfaceTranslation()).toString()); this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); if (StringHelper.isNullOrEmpty(getParameters().getInterface().getMacAddress())) { String mac = null; RefObject<String> tempRefObject = new RefObject<String>(mac); MacPoolManager.getInstance().allocateNewMac(tempRefObject); mac = tempRefObject.argvalue; getParameters().getInterface().setMacAddress(mac); } getParameters().getInterface().setSpeed( VmInterfaceType.forValue( getParameters().getInterface().getType()).getSpeed()); getParameters().getInterface().setId(Guid.NewGuid()); getParameters().getInterface().setVmId(getParameters().getVmId()); DbFacade dbFacade = DbFacade.getInstance(); dbFacade .getVmNetworkInterfaceDAO() .save(getParameters().getInterface()); dbFacade .getVmNetworkStatisticsDAO() .save(getParameters().getInterface().getStatistics()); VmDevice vmDevice = VmDeviceUtils.addManagedDevice(new VmDeviceId(getParameters().getInterface().getId(), getParameters().getVmId()), VmDeviceType.INTERFACE, VmDeviceType.BRIDGE, "", true, false); boolean succeded = true; VmDynamic vmDynamic = getVm().getDynamicData(); if (vmDynamic.getstatus() == VMStatus.Up) { succeded = hotPlugNic(vmDevice, vmDynamic); if (!succeded) { getReturnValue().getExecuteFailedMessages().add("Failed hot-plugging nic to VM"); } } setSucceeded(succeded); }
Source:
public static void setDefaultRetention_test() throws Exception { String methodName = "setDefaultRetention(SetDefaultRetentionArgs args)"; if (!mintEnv) { System.out.println("Test: " + methodName); } long startTime = System.currentTimeMillis(); String bucketName = getRandomName(); try { client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).objectLock(true).build()); try { ObjectLockConfiguration config = new ObjectLockConfiguration(RetentionMode.COMPLIANCE, new RetentionDurationDays(10)); client.setDefaultRetention( SetDefaultRetentionArgs.builder().bucket(bucketName).config(config).build()); } finally { client.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build()); } mintSuccessLog(methodName, null, startTime); } catch (Exception e) { handleException(methodName, null, startTime, e); } }

Target:
public static void setDefaultRetention_test() throws Exception { String methodName = "setDefaultRetention(SetDefaultRetentionArgs args)"; if (!mintEnv) { System.out.println("Test: " + methodName); } long startTime = System.currentTimeMillis(); String bucketName = getRandomName(); String mintArgs = "config={COMPLIANCE, 10 days}"; try { client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).objectLock(true).build()); try { ObjectLockConfiguration config = new ObjectLockConfiguration(RetentionMode.COMPLIANCE, new RetentionDurationDays(10)); client.setDefaultRetention( SetDefaultRetentionArgs.builder().bucket(bucketName).config(config).build()); } finally { client.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build()); } mintSuccessLog(methodName, mintArgs, startTime); } catch (Exception e) { handleException(methodName, mintArgs, startTime, e); } }
Source:
public InputSource resolveEntity(String publicId, String systemId) { InputSource source = null; log.debug("Trying to resolve XML entity with public ID and system ID [{}]", publicId, systemId); if (VERSION_5_XSD.equalsIgnoreCase(systemId)) { throw new MappingException("Found v5 XSD: '" + VERSION_5_XSD + "'. Expected v6 XSD: '" + VERSION_6_XSD + "'"); } try { source = resolveFromClassPath(publicId, systemId); } catch (IOException ex1) { log.error("Could not resolve bean-mapping XML Schema [" + systemId + "]: not found in classpath", ex1); try { source = resolveFromURL(systemId); } catch (IOException ex2) { log.error("Could not resolve bean-mapping XML Schema [" + systemId + "]", ex2); } } return source; }

Target:
public InputSource resolveEntity(String publicId, String systemId) { InputSource source = null; log.debug("Trying to resolve XML entity with public ID and system ID [{}]", publicId, systemId); if (VERSION_5_XSD.equalsIgnoreCase(systemId)) { throw new MappingException("Dozer >= v6.0.0 uses a new XSD location. Your current config needs to be upgraded. " + "Found v5 XSD: '" + VERSION_5_XSD + "'. Expected v6 XSD: '" + VERSION_6_XSD + "'. Please see migration guide @ <LINK_0>"); } try { source = resolveFromClassPath(publicId, systemId); } catch (IOException ex1) { log.error("Could not resolve bean-mapping XML Schema [" + systemId + "]: not found in classpath", ex1); try { source = resolveFromURL(systemId); } catch (IOException ex2) { log.error("Could not resolve bean-mapping XML Schema [" + systemId + "]", ex2); } } return source; }
Source:
public void testRunAfterDataInsertedLiveReport() throws Exception { insertData(); final KafkaIndexTask task = createTask( null, new KafkaIndexTaskIOConfig( 0, "sequence0", new SeekableStreamStartSequenceNumbers<>(topic, ImmutableMap.of(0, 2L), ImmutableSet.of()), new SeekableStreamEndSequenceNumbers<>(topic, ImmutableMap.of(0, 13L)), kafkaServer.consumerProperties(), KafkaSupervisorIOConfig.DEFAULT_POLL_TIMEOUT_MILLIS, true, null, null ) ); final ListenableFuture<TaskStatus> future = runTask(task); SeekableStreamIndexTaskRunner runner = task.getRunner(); while (true) { runner.pause(); if (runner.getRowIngestionMeters().getProcessed() >= 4) { break; } runner.resume(); } Assert.assertEquals(TaskState.SUCCESS, future.get().getStatusCode()); Assert.assertEquals(4, task.getRunner().getRowIngestionMeters().getProcessed()); Assert.assertEquals(3, task.getRunner().getRowIngestionMeters().getUnparseable()); Assert.assertEquals(1, task.getRunner().getRowIngestionMeters().getThrownAway()); }

Target:
public void testRunAfterDataInsertedLiveReport() throws Exception { insertData(); final KafkaIndexTask task = createTask( null, new KafkaIndexTaskIOConfig( 0, "sequence0", new SeekableStreamStartSequenceNumbers<>(topic, ImmutableMap.of(0, 2L), ImmutableSet.of()), new SeekableStreamEndSequenceNumbers<>(topic, ImmutableMap.of(0, 12L)), kafkaServer.consumerProperties(), KafkaSupervisorIOConfig.DEFAULT_POLL_TIMEOUT_MILLIS, true, null, null ) ); final ListenableFuture<TaskStatus> future = runTask(task); SeekableStreamIndexTaskRunner runner = task.getRunner(); while (true) { Thread.sleep(1000); if (runner.getStatus() == Status.PUBLISHING) { break; } } Map rowStats = runner.doGetRowStats(); Map totals = (Map) rowStats.get("totals"); RowIngestionMetersTotals buildSegments = (RowIngestionMetersTotals) totals.get("buildSegments"); Map movingAverages = (Map) rowStats.get("movingAverages"); Map buildSegments2 = (Map) movingAverages.get("buildSegments"); HashMap avg_1min = (HashMap) buildSegments2.get("1m"); HashMap avg_5min = (HashMap) buildSegments2.get("5m"); HashMap avg_15min = (HashMap) buildSegments2.get("15m"); runner.resume(); Assert.assertEquals(buildSegments.getProcessed(), task.getRunner().getRowIngestionMeters().getProcessed()); Assert.assertEquals(buildSegments.getUnparseable(), task.getRunner().getRowIngestionMeters().getUnparseable()); Assert.assertEquals(buildSegments.getThrownAway(), task.getRunner().getRowIngestionMeters().getThrownAway()); Assert.assertEquals(avg_1min.get("processed"), 0.0); Assert.assertEquals(avg_5min.get("processed"), 0.0); Assert.assertEquals(avg_15min.get("processed"), 0.0); Assert.assertEquals(TaskState.SUCCESS, future.get().getStatusCode()); }
Source:
public Set<Class> springClasses() { return SetX.of(ElasticacheConfig.class); }

Target:
public Set<Class> springClasses() { return SetX.of(ElasticacheConfig.class, DistributedCacheFactory.class); }
Source:
public void testVerified() { IGerritHudsonTriggerConfig config = Setup.createConfig(); ParameterExpander instance = new ParameterExpander(config); Integer result = instance.getMinimumVerifiedValue(parameter.memoryImprint, true); if (parameter.expectedVerified == null) { assertEquals(null, result); } else { assertEquals(Integer.valueOf(parameter.expectedVerified), result); } }

Target:
public void testVerified() { IGerritHudsonTriggerConfig config = Setup.createConfig(); ParameterExpander instance = new ParameterExpander(config); Integer result = instance.getMinimumVerifiedValue(parameter.memoryImprint, true); if (parameter.expectedVerified == null) { assertNull(result); } else { assertEquals(Integer.valueOf(parameter.expectedVerified), result); } }
Source:
public void setObjectName(ObjectName objectName) { this.objectName = objectName; }

Target:
void setObjectName(ObjectName objectName) { this.objectName = objectName; }
Source:
public Object wrap(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class.cast(point.getSignature()).getMethod(); final UnitedThrow annot = method.getAnnotation(UnitedThrow.class); final Class<? extends Throwable> clz = clazz(method, annot); try { return point.proceed(); } catch (Throwable ex) { Throwable throwable = ex; if (!clz.isAssignableFrom(ex.getClass())) { try { throwable = clz.getConstructor(Throwable.class) .newInstance(ex); } catch (NoSuchMethodException methodex) { throwable = clz.newInstance(); } } throw throwable; } }

Target:
public Object wrap(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class.cast(point.getSignature()).getMethod(); final UnitedThrow annot = method.getAnnotation(UnitedThrow.class); final Class<? extends Throwable> clz = clazz(method, annot); try { return point.proceed(); } catch (Throwable ex) { Throwable throwable = ex; if (!clz.isAssignableFrom(ex.getClass())) { if (exists(clz)) { throwable = clz.getConstructor(Throwable.class) .newInstance(ex); } else { throwable = clz.newInstance(); } } throw throwable; } }
Source:
public void annotationShouldWorkWithRange() { TestData data = null; for(int x=0; x < 10; x++) { data = new EnhancedRandomBuilder().build().nextObject(TestData.class); then(data.getPrice()).isBetween(200, 500); } }

Target:
public void annotationShouldWorkWithRange() { TestData data = null; for(int x=0; x < 10; x++) { data = EnhancedRandom.random(TestData.class); then(data.getPrice()).isBetween(200, 500); } }
Source:
private void updateScreenSaverStatus(boolean screenSaverActive) { if (screenSaverActive) { updateProperty("Screensaver.State", OnOffType.ON); } else { updateProperty("Screensaver.State", OnOffType.OFF); } }

Target:
private void updateScreenSaverStatus(boolean screenSaverActive) { if (screenSaverActive) { updateProperty(SCREENSAVER_STATE, OnOffType.ON); } else { updateProperty(SCREENSAVER_STATE, OnOffType.OFF); } }
Source:
protected void handleFeature(EObject owner, EStructuralFeature unkownFeature, Object valueOfUnknownFeature) { super.handleFeature(owner, unkownFeature, valueOfUnknownFeature); if (DVIEW_OWNED_REPRESENTATIONS_UNKNOWN_FEATURE.equals(unkownFeature.getName())) { if (valueOfUnknownFeature instanceof DRepresentation && owner instanceof DView) { DRepresentation representation = (DRepresentation) valueOfUnknownFeature; owner.eResource().getContents().add(representation); String representationName = representationToNameMap.get(representation); DRepresentationDescriptor newDescriptor = DRepresentationDescriptorInternalHelper.createDescriptor(representation, representationName); ((DView) owner).getOwnedRepresentationDescriptors().add(newDescriptor); if (representationName == null) { representation2RepresentationDescriptorMap.put(representation, newDescriptor); } } } else if (owner instanceof DRepresentation && FEATURE_NAME_LABEL.equals(unkownFeature.getName())) { DRepresentationDescriptor dRepresentationDescriptor = representation2RepresentationDescriptorMap.get(owner); if (dRepresentationDescriptor != null) { dRepresentationDescriptor.setName((String) valueOfUnknownFeature); } } }

Target:
protected void handleFeature(EObject owner, EStructuralFeature unkownFeature, Object valueOfUnknownFeature) { if (DVIEW_OWNED_REPRESENTATIONS_UNKNOWN_FEATURE.equals(unkownFeature.getName())) { if (valueOfUnknownFeature instanceof DRepresentation && owner instanceof DView) { DRepresentation representation = (DRepresentation) valueOfUnknownFeature; owner.eResource().getContents().add(representation); String representationName = representationToNameMap.get(representation); DRepresentationDescriptor newDescriptor = DRepresentationDescriptorInternalHelper.createDescriptor(representation, representationName); ((DView) owner).getOwnedRepresentationDescriptors().add(newDescriptor); if (representationName == null) { representation2RepresentationDescriptorMap.put(representation, newDescriptor); } } } else if (owner instanceof DRepresentation && FEATURE_NAME_LABEL.equals(unkownFeature.getName())) { DRepresentationDescriptor dRepresentationDescriptor = representation2RepresentationDescriptorMap.get(owner); if (dRepresentationDescriptor != null) { dRepresentationDescriptor.setName((String) valueOfUnknownFeature); } } else if (owner instanceof DRepresentation && FEATURE_NAME_LABEL.equals(unkownFeature.getName())) { representationToNameMap.put((DRepresentation) owner, (String) valueOfUnknownFeature); } }
Source:
public BluetoothAddress(String address) { if (address == null || address.length() != BD_ADDRESS_LENGTH) { throw new IllegalArgumentException("BT Address can not be null or zero length"); } for (int i = 0; i < BD_ADDRESS_LENGTH; i++) { char c = address.charAt(i); switch (i % 3) { case 0: case 1: if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) { break; } throw new IllegalArgumentException("BT Address must contain upper case hex values only"); case 2: if (c == ':') { break; } throw new IllegalArgumentException("BT Address bytes must be separated with colon"); } } this.address = address; }

Target:
public BluetoothAddress(String address) { if (address == null || address.length() != BD_ADDRESS_LENGTH) { throw new IllegalArgumentException("BT Address cannot be null and must be in format XX:XX:XX:XX:XX:XX"); } for (int i = 0; i < BD_ADDRESS_LENGTH; i++) { char c = address.charAt(i); switch (i % 3) { case 0: case 1: if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) { break; } throw new IllegalArgumentException("BT Address must contain upper case hex values only"); case 2: if (c == ':') { break; } throw new IllegalArgumentException("BT Address bytes must be separated with colon"); } } this.address = address; }
Source:
private boolean isBoolean(String value) { return "true".equals(value) || "false".equals(value); }

Target:
private boolean isBoolean(String value) { return "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value); }
Source:
private void fixDiskDevices(VM vm, Map<DiskImage, DiskImage> diskMappings) { Map<Guid, Guid> diskIdMappings = new HashMap<>(); diskMappings.forEach((source, destination) -> diskIdMappings.put(source.getId(), destination.getId())); List<VmDevice> diskDevices = vm.getStaticData().getManagedDeviceMap().values().stream() .filter(dev -> dev.getType() == VmDeviceGeneralType.DISK && VmDeviceType.DISK.getName().equals(dev.getDevice())) .collect(Collectors.toList()); diskDevices.forEach(diskDevice -> { Guid sourceDiskId = diskDevice.getDeviceId(); Guid destinationDiskId = diskIdMappings.get(sourceDiskId); if (destinationDiskId != null) { vm.getStaticData().getManagedDeviceMap().remove(sourceDiskId); diskDevice.setDeviceId(destinationDiskId); vm.getStaticData().getManagedDeviceMap().put(destinationDiskId, diskDevice); } }); }

Target:
private void fixDiskDevices(VM vm, Map<DiskImage, DiskImage> diskMappings) { Map<Guid, Guid> diskIdMappings = new HashMap<>(); diskMappings.forEach((source, destination) -> diskIdMappings.put(source.getId(), destination.getId())); List<VmDevice> diskDevices = vm.getStaticData().getManagedDeviceMap().values().stream() .filter(VmDeviceCommonUtils::isDisk) .collect(Collectors.toList()); diskDevices.forEach(diskDevice -> { Guid sourceDiskId = diskDevice.getDeviceId(); Guid destinationDiskId = diskIdMappings.get(sourceDiskId); if (destinationDiskId != null) { vm.getStaticData().getManagedDeviceMap().remove(sourceDiskId); diskDevice.setDeviceId(destinationDiskId); vm.getStaticData().getManagedDeviceMap().put(destinationDiskId, diskDevice); } }); }
Source:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock()) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { List<Network> networks = getNetworkDao().getAllForCluster(vds.getVdsGroupId()); for (Network net : networks) { NetworkClusterHelper.setStatus(vds.getVdsGroupId(), net); } return null; } }); if (vds.getHighlyAvailableIsConfigured()) { SetHaMaintenanceModeVDSCommandParameters param = new SetHaMaintenanceModeVDSCommandParameters(vds, HaMaintenanceMode.LOCAL, false); if (!runVdsCommand(VDSCommandType.SetHaMaintenanceMode, param).getSucceeded()) { haMaintenanceFailed = true; } } } } logMonitorLockReleased("Activate"); List<String> serviceList = new ArrayList<>(); serviceList.add("glusterd"); runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(getParameters().getVdsId(), serviceList, "restart")); }

Target:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock()) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { List<Network> networks = getNetworkDao().getAllForCluster(vds.getVdsGroupId()); for (Network net : networks) { NetworkClusterHelper.setStatus(vds.getVdsGroupId(), net); } return null; } }); if (vds.getHighlyAvailableIsConfigured()) { SetHaMaintenanceModeVDSCommandParameters param = new SetHaMaintenanceModeVDSCommandParameters(vds, HaMaintenanceMode.LOCAL, false); if (!runVdsCommand(VDSCommandType.SetHaMaintenanceMode, param).getSucceeded()) { haMaintenanceFailed = true; } } } } logMonitorLockReleased("Activate"); if (vds.getVdsGroupSupportsGlusterService()) { List<String> serviceList = new ArrayList<>(); serviceList.add("glusterd"); runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), serviceList, "restart")); } }
Source:
public void initializeTextUtilities() { fontTitle = new Font("Calibri", Font.BOLD, 60); typeFontTitle = new TrueTypeFont(fontTitle, true); fontPlayer = new Font("Calibri", Font.BOLD, 40); typeFontPlayer = new TrueTypeFont(fontPlayer, true); gameOverText = "GAME OVER"; gameWonText = "GAME COMPLETED"; gameContinueText = "CONTINUE"; }

Target:
private void initializeTextUtilities() { fontTitle = new Font("Calibri", Font.BOLD, 60); typeFontTitle = new TrueTypeFont(fontTitle, true); fontPlayer = new Font("Calibri", Font.BOLD, 40); typeFontPlayer = new TrueTypeFont(fontPlayer, true); gameContinueText = "CONTINUE"; }
Source:
public void enableHighNotifications(Consumer<float[]> callback) { Consumer<byte[]> callbackHigh = new Consumer<byte[]>() { @Override public void accept(byte[] t) { callback.accept(calculateHighData(t)); } }; try { this.gattResources.get(HIGH_PRIORITY_ARRAY).getGattService() .findCharacteristic(XdkGatt.UUID_XDK_HIGH_DATA_RATE_HIGH_PRIORITY_ARREY) .enableValueNotifications(callbackHigh); } catch (KuraException e) { logger.error("Notification enable failed", e); } }

Target:
public void enableHighNotifications(Consumer<float[]> callback) { Consumer<byte[]> callbackHigh = valueBytes -> callback.accept(calculateHighData(valueBytes)); try { this.gattResources.get(HIGH_PRIORITY_ARRAY).getGattService() .findCharacteristic(XdkGatt.UUID_XDK_HIGH_DATA_RATE_HIGH_PRIORITY_ARREY) .enableValueNotifications(callbackHigh); } catch (KuraException e) { logger.error("Notification enable failed", e); } }
Source:
public void testAddFeed() throws Exception { uiTestUtils.addHostedFeedData(); final Feed feed = uiTestUtils.hostedFeeds.get(0); openNavDrawer(); onView(withText(R.string.add_feed_label)).perform(click()); onView(withId(R.id.addViaUrlButton)).perform(scrollTo(), click()); onView(withId(R.id.text)).perform(replaceText(feed.getDownload_url())); onView(withText(R.string.confirm_label)).perform(scrollTo(), click()); Espresso.closeSoftKeyboard(); onView(withText(R.string.subscribe_label)).perform(click()); onView(isRoot()).perform(waitForView(withId(R.id.butShowSettings), 5000)); }

Target:
public void testAddFeed() throws Exception { uiTestUtils.addHostedFeedData(); final Feed feed = uiTestUtils.hostedFeeds.get(0); openNavDrawer(); onView(withText(R.string.add_feed_label)).perform(click()); onView(withId(R.id.addViaUrlButton)).perform(scrollTo(), click()); onView(withId(R.id.urlEditText)).perform(replaceText(feed.getDownload_url())); onView(withText(R.string.confirm_label)).perform(scrollTo(), click()); Espresso.closeSoftKeyboard(); onView(withText(R.string.subscribe_label)).perform(click()); onView(isRoot()).perform(waitForView(withId(R.id.butShowSettings), 5000)); }
Source:
default public boolean isSatisfied() { return true; }

Target:
default boolean isSatisfied() { return true; }
Source:
public Observable<Result<T>> show(final FragmentManager manager) { return Observable.create(new Observable.OnSubscribe<Result<T>>() { @Override public void call(rx.Subscriber<? super Result<T>> subscriber) { final long key = subscriberVault.store(subscriber); storeSubscriberKey(key); subscriber.add(new Subscription() { @Override public void unsubscribe() { subscriberVault.remove(key); } @Override public boolean isUnsubscribed() { return !subscriberVault.containsKey(key); } }); show(manager, null); } }); }

Target:
public Observable<Result<T>> show(final FragmentManager manager) { return Observable.create(new Observable.OnSubscribe<Result<T>>() { @Override public void call(Subscriber<? super Result<T>> subscriber) { final long key = subscriberVault.store(subscriber); storeSubscriberKey(key); subscriber.add(new Subscription() { @Override public void unsubscribe() { subscriberVault.remove(key); } @Override public boolean isUnsubscribed() { return !subscriberVault.containsKey(key); } }); show(manager, null); } }); }
Source:
public void changeFileContent(String pathToFile, String content) throws IOException { ghRepo.getFileContent(String.format("/%s", pathToFile)).update(content, "change - " + content); }

Target:
public void changeFileContent(String pathToFile, String content) throws IOException { changeFileContent(pathToFile, content, format("Change file %s", pathToFile)); }
Source:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText( R.string.invalid_username_password).toString()); } urlopen = login(); try { List<NameValuePair> postData = new ArrayList<NameValuePair>(); postData.add(new BasicNameValuePair("homeForm:balance","Saldo")); postData.add(new BasicNameValuePair("homeForm","homeForm")); response = urlopen.open(ACCOUNTS_URL,postData); Document doc = Jsoup.parse(response); ArrayList<Account> accounts = parseAccounts(doc); if (!accounts.isEmpty()) { Account firstAccount = accounts.get(0); addAccountDetails(firstAccount, doc); firstAccount.setTransactions(parseTransactions(response)); } for (int i = 1; i < accounts.size(); i++) { Account account = accounts.get(i); response = urlopen.open(TRANSACTIONS_URL, createTransactionParams(account)); addAccountDetails(account, Jsoup.parse(response)); account.setTransactions(parseTransactions(response)); } this.setAccounts(accounts); } finally { super.updateComplete(); } }

Target:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText( R.string.invalid_username_password).toString()); } urlopen = login(); List<NameValuePair> postData = new ArrayList<NameValuePair>(); postData.add(new BasicNameValuePair("homeForm:balance","Saldo")); postData.add(new BasicNameValuePair("homeForm","homeForm")); response = urlopen.open(ACCOUNTS_URL,postData); Document doc = Jsoup.parse(response); ArrayList<Account> accounts = parseAccounts(doc); if (!accounts.isEmpty()) { Account firstAccount = accounts.get(0); addAccountDetails(firstAccount, doc); firstAccount.setTransactions(parseTransactions(response)); } for (int i = 1; i < accounts.size(); i++) { Account account = accounts.get(i); response = urlopen.open(TRANSACTIONS_URL, createTransactionParams(account)); addAccountDetails(account, Jsoup.parse(response)); account.setTransactions(parseTransactions(response)); } this.setAccounts(accounts); super.updateComplete(); }
Source:
private static void loadSingle( LocalDate marketDataDate, ResourceLocator resource, ImmutableMap.Builder<QuoteId, Double> builder) { try { CsvFile csv = CsvFile.of(resource.getCharSource(), true); for (int i = 0; i < csv.rowCount(); i++) { String dateText = csv.field(i, DATE_FIELD); LocalDate date = LocalDate.parse(dateText); if (date.equals(marketDataDate)) { String schemeStr = csv.field(i, SYMBOLOGY_FIELD); String tickerStr = csv.field(i, TICKER_FIELD); String fieldNameStr = csv.field(i, FIELD_NAME_FIELD); String valueStr = csv.field(i, VALUE_FIELD); double value = Double.valueOf(valueStr); StandardId id = StandardId.of(schemeStr, tickerStr); FieldName fieldName = fieldNameStr.isEmpty() ? FieldName.MARKET_VALUE : FieldName.of(fieldNameStr); builder.put(QuoteId.of(id, MarketDataFeed.NONE, fieldName), value); } } } catch (RuntimeException ex) { throw new IllegalArgumentException( Messages.format("Error processing resource as CSV file: {}", resource), ex); } }

Target:
private static void loadSingle( LocalDate marketDataDate, ResourceLocator resource, ImmutableMap.Builder<QuoteId, Double> builder) { try { CsvFile csv = CsvFile.of(resource.getCharSource(), true); for (int i = 0; i < csv.rowCount(); i++) { String dateText = csv.field(i, DATE_FIELD); LocalDate date = LocalDate.parse(dateText); if (date.equals(marketDataDate)) { String symbologyStr = csv.field(i, SYMBOLOGY_FIELD); String tickerStr = csv.field(i, TICKER_FIELD); String fieldNameStr = csv.field(i, FIELD_NAME_FIELD); String valueStr = csv.field(i, VALUE_FIELD); double value = Double.valueOf(valueStr); StandardId id = StandardId.of(symbologyStr, tickerStr); FieldName fieldName = fieldNameStr.isEmpty() ? FieldName.MARKET_VALUE : FieldName.of(fieldNameStr); builder.put(QuoteId.of(id, MarketDataFeed.NONE, fieldName), value); } } } catch (RuntimeException ex) { throw new IllegalArgumentException( Messages.format("Error processing resource as CSV file: {}", resource), ex); } }
Source:
public static int requestAudioFocus( @NonNull AudioManager audioManager, @NonNull AudioFocusRequestCompat focusRequest) { if (focusRequest == null) { throw new IllegalArgumentException("AudioFocusRequestCompat must not be null"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return audioManager.requestAudioFocus(focusRequest.getAudioFocusRequest()); } else { return audioManager.requestAudioFocus( focusRequest.getOnAudioFocusChangeListener(), focusRequest.getAudioAttributesCompat().getLegacyStreamType(), focusRequest.getFocusGain()); } }

Target:
public static int requestAudioFocus( @NonNull AudioManager audioManager, @NonNull AudioFocusRequestCompat focusRequest) { if (audioManager == null) { throw new IllegalArgumentException("AudioManager must not be null"); } if (focusRequest == null) { throw new IllegalArgumentException("AudioFocusRequestCompat must not be null"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return audioManager.requestAudioFocus(focusRequest.getAudioFocusRequest()); } else { return audioManager.requestAudioFocus( focusRequest.getOnAudioFocusChangeListener(), focusRequest.getAudioAttributesCompat().getLegacyStreamType(), focusRequest.getFocusGain()); } }
Source:
public static Long getCount(String tenantName) { return tenantCallsCount.get(tenantName).get(); }

Target:
public static long getCount(String tenantName) { return tenantCallsCount.get(tenantName).get(); }
Source:
protected List<AttributeStatement> createAcpAttributeStatements(CallbackProperties properties) { final List<AttributeStatement> statements = new ArrayList<>(); Attribute acpAttribute; Attribute iacpAttribute; final String acp = properties.getAcpAttribute(); final String iacp = properties.getIacpAttribute(); if (NullChecker.isNotNullish(acp)) { acpAttribute = OpenSAML2ComponentBuilder.getInstance() .createAttribute(SamlConstants.ATTRIBUTE_FRIENDLY_NAME_XUA_ACP, SamlConstants.ATTRIBUTE_NAME_XUA_ACP, SamlConstants.URI_NAME_FORMAT, Arrays.asList(acp)); statements .addAll(OpenSAML2ComponentBuilder.getInstance().createAttributeStatement(Arrays.asList(acpAttribute))); } if(NullChecker.isNotNullish(iacp)) { iacpAttribute = OpenSAML2ComponentBuilder.getInstance() .createAttribute(SamlConstants.ATTRIBUTE_FRIENDLY_NAME_XUA_IACP, SamlConstants.ATTRIBUTE_NAME_XUA_IACP, SamlConstants.URI_NAME_FORMAT, Arrays.asList(iacp)); statements .addAll(OpenSAML2ComponentBuilder.getInstance().createAttributeStatement(Arrays.asList(iacpAttribute))); } return statements; }

Target:
protected List<AttributeStatement> createAcpAttributeStatements(CallbackProperties properties) { final List<AttributeStatement> statements = new ArrayList<>(); Attribute acpAttribute; Attribute iacpAttribute; final String acp = properties.getAcpAttribute(); final String iacp = properties.getIacpAttribute(); if (StringUtils.isNotEmpty(acp)) { acpAttribute = OpenSAML2ComponentBuilder.getInstance() .createAttribute(SamlConstants.ATTRIBUTE_FRIENDLY_NAME_XUA_ACP, SamlConstants.ATTRIBUTE_NAME_XUA_ACP, SamlConstants.URI_NAME_FORMAT, Arrays.asList(acp)); statements .addAll(OpenSAML2ComponentBuilder.getInstance().createAttributeStatement(Arrays.asList(acpAttribute))); } if(StringUtils.isNotEmpty(iacp)) { iacpAttribute = OpenSAML2ComponentBuilder.getInstance() .createAttribute(SamlConstants.ATTRIBUTE_FRIENDLY_NAME_XUA_IACP, SamlConstants.ATTRIBUTE_NAME_XUA_IACP, SamlConstants.URI_NAME_FORMAT, Arrays.asList(iacp)); statements .addAll(OpenSAML2ComponentBuilder.getInstance().createAttributeStatement(Arrays.asList(iacpAttribute))); } return statements; }
Source:
public void writeTo(Appendable appendable) throws IOException { try (JsonOutput json = new Json().newOutput(appendable)) { json.beginObject(); Map<String, Object> first = getOss(); if (first == null) { first = (Map<String, Object>) stream().findFirst() .orElse(new ImmutableCapabilities()) .asMap(); } json.name("desiredCapabilities"); json.write(first, MAP_TYPE); json.name("capabilities"); json.beginObject(); json.name("desiredCapabilities"); json.write(first, MAP_TYPE); json.name("firstMatch"); json.beginArray(); getW3C().forEach(map -> json.write(map, MAP_TYPE)); json.endArray(); json.endObject(); writeMetaData(json); json.endObject(); } }

Target:
public void writeTo(Appendable appendable) throws IOException { try (JsonOutput json = new Json().newOutput(appendable)) { json.beginObject(); Map<String, Object> first = getOss(); if (first == null) { first = (Map<String, Object>) stream().findFirst() .orElse(new ImmutableCapabilities()) .asMap(); } json.name(DESIRED_CAPABILITIES); json.write(first, MAP_TYPE); json.name(CAPABILITIES); json.beginObject(); json.name(DESIRED_CAPABILITIES); json.write(first, MAP_TYPE); json.name(FIRST_MATCH); json.beginArray(); getW3C().forEach(map -> json.write(map, MAP_TYPE)); json.endArray(); json.endObject(); writeMetaData(json); json.endObject(); } }
Source:
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithMsalAccount(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(new AuthenticationRequiredException("Interactive authentication is needed to " + "acquire token. Call Authenticate to initiate the device code authentication.")); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); }

Target:
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithPublicClientCache(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(logger.logExceptionAsError(new AuthenticationRequiredException("Interactive " + "authentication is needed to acquire token. Call Authenticate to initiate the device " + "code authentication.", request))); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); }
Source:
public PDataType getDataType() { if (baseType == null) { PDataType elementType = null; for (int i = 0; i < children.size(); i++) { Expression child = children.get(i); if (child.getDataType() != elementType) { elementType = child.getDataType(); } } baseType = elementType; } return PDataType.fromTypeId(baseType.getSqlType() + Types.ARRAY); }

Target:
public PDataType getDataType() { return PDataType.fromTypeId(baseType.getSqlType() + Types.ARRAY); }
Source:
public String contents() throws IOException { return wrapped.contents(); }

Target:
public String contents() { try { return wrapped.contents(); } catch (IOException e) { throw new IllegalStateException(e); } }
Source:
private String extractDefaultValue(String tok) { int startDefault = -1; if (tok.startsWith(DEFAULT_NODE)) { startDefault = DEFAULT_NODE.length(); } else if (tok.startsWith(DEFAULT_ATTACHMENT)) { startDefault = DEFAULT_ATTACHMENT.length(); } int endDefault = tok.indexOf(']'); if ((startDefault != -1) && (endDefault != -1)) { int hitsLocation = tok.indexOf('|'); if ((hitsLocation >= 0) && (hitsLocation < endDefault)) { defaultHits = Integer.parseInt(tok.substring(hitsLocation + 1, endDefault)); defaultValue = tok.substring(startDefault, hitsLocation); } else { defaultValue = tok.substring(startDefault, endDefault); } if (tok.startsWith(DEFAULT_NODE)) { tok = "+" + tok.substring(endDefault + 1); } else if (tok.startsWith(DEFAULT_ATTACHMENT)) { tok = "+%" + tok.substring(endDefault + 1); } else { throw new IllegalStateException("Unexpected state in default value extraction"); } } return tok; }

Target:
String extractDefaultValue(String tok) { int startDefault = -1; if (tok.startsWith(DEFAULT_NODE)) { startDefault = DEFAULT_NODE.length(); } else if (tok.startsWith(DEFAULT_ATTACHMENT)) { startDefault = DEFAULT_ATTACHMENT.length(); } int endDefault = tok.indexOf(']'); if ((startDefault != -1) && (endDefault != -1)) { int hitsLocation = tok.indexOf('|'); if ((hitsLocation >= 0) && (hitsLocation < endDefault)) { defaultHits = Integer.parseInt(tok.substring(hitsLocation + 1, endDefault)); defaultValue = tok.substring(startDefault, hitsLocation); } else { defaultValue = tok.substring(startDefault, endDefault); } if (tok.startsWith(DEFAULT_NODE)) { tok = "+" + tok.substring(endDefault + 1); } else if (tok.startsWith(DEFAULT_ATTACHMENT)) { tok = "+%" + tok.substring(endDefault + 1); } else { throw new IllegalStateException("Unexpected state in default value extraction"); } } return tok; }
Source:
public boolean deleteProjectHandleResolver(IProjectHandleResolver resolver) { ProjectHandleResolverDTO resolverDto = mapper.mapProjectHandleResolver(resolver); resolverDao.deleteDTO(resolverDto); return true; }

Target:
public boolean deleteProjectHandleResolver(IProjectHandleResolver resolver) { if (resolverDao.getProjectsForResolverId(resolver.getId()).size() > 0) { return false; } ProjectHandleResolverDTO resolverDto = mapper.mapProjectHandleResolver(resolver); resolverDao.deleteDTO(resolverDto); return true; }
Source:
private NonBlockingStatsDClient(NonBlockingStatsDClient client) { this.prefix = client.prefix; this.handler = client.handler; this.constantTagsRendered = client.constantTagsRendered; this.clientChannel = client.clientChannel; this.statsDProcessor = client.statsDProcessor; this.statsDSender = client.statsDSender; }

Target:
private NonBlockingStatsDClient(NonBlockingStatsDClient client) throws StatsDClientException { prefix = client.prefix; handler = client.handler; constantTagsRendered = client.constantTagsRendered; clientChannel = client.clientChannel; try { statsDProcessor = createProcessor(client.statsDProcessor); statsDSender = new StatsDSender( client.statsDSender, statsDProcessor.getBufferPool(), statsDProcessor.getOutboundQueue()); } catch (Exception e) { throw new StatsDClientException("Failed to instantiate StatsD client copy", e); } telemetry = new Telemetry(client.telemetry.getTags(), statsDProcessor); executor.submit(statsDProcessor); executor.submit(statsDSender); }
Source:
private GenerateAccessTokenResponse generateAccessToken() throws IOException { IAMCredentials IAMCredentials = new IAMCredentials(transport, new JacksonFactory(), initializer); GenerateAccessTokenRequest content = new GenerateAccessTokenRequest(); content.setScope(CredentialFactory.GCS_SCOPES); content.setLifetime(DEFAULT_ACCESS_TOKEN_LIFETIME); IAMCredentials.Projects.ServiceAccounts.GenerateAccessToken generateAccessTokenReq = IAMCredentials.projects() .serviceAccounts() .generateAccessToken(DEFAULT_SERVICE_ACCOUNT_NAME_PREFIX + serviceAccountName, content); GenerateAccessTokenResponse response = generateAccessTokenReq.execute(); checkNotNull(response.getAccessToken(), "Access Token cannot be null!"); return response; }

Target:
private GenerateAccessTokenResponse generateAccessToken() throws IOException { GenerateAccessTokenRequest requestContent = new GenerateAccessTokenRequest() .setScope(scopes) .setLifetime(DEFAULT_ACCESS_TOKEN_LIFETIME); GenerateAccessToken request = new IAMCredentials(transport, JSON_FACTORY, initializer) .projects() .serviceAccounts() .generateAccessToken(serviceAccountResource, requestContent); GenerateAccessTokenResponse response = request.execute(); checkNotNull(response.getAccessToken(), "Access Token cannot be null!"); return response; }
Source:
void wereBetween() { Command fiveMinsAgo = requestFactory.createCommand(StringValue.getDefaultInstance(), minutesAgo(5)); Command twoMinsAgo = requestFactory.createCommand(Int64Value.getDefaultInstance(), minutesAgo(2)); Command thirtySecondsAgo = requestFactory.createCommand(BoolValue.getDefaultInstance(), secondsAgo(30)); Command twentySecondsAgo = requestFactory.createCommand(BoolValue.getDefaultInstance(), secondsAgo(20)); Command fiveSecondsAgo = requestFactory.createCommand(BoolValue.getDefaultInstance(), secondsAgo(5)); Iterable<Command> filter = Stream.of(fiveMinsAgo, twoMinsAgo, thirtySecondsAgo, twentySecondsAgo, fiveSecondsAgo) .filter(wereWithinPeriod(minutesAgo(3), secondsAgo(10)) ::apply) .collect(toList()); assertEquals(3, StreamSupport.stream(filter.spliterator(), false) .count()); }

Target:
void wereBetween() { Command fiveMinsAgo = requestFactory.createCommand(STR_MSG, minutesAgo(5)); Command twoMinsAgo = requestFactory.createCommand(INT_64_MSG, minutesAgo(2)); Command thirtySecondsAgo = requestFactory.createCommand(BOOL_MSG, secondsAgo(30)); Command twentySecondsAgo = requestFactory.createCommand(BOOL_MSG, secondsAgo(20)); Command fiveSecondsAgo = requestFactory.createCommand(BOOL_MSG, secondsAgo(5)); long filteredCommands = Stream.of(fiveMinsAgo, twoMinsAgo, thirtySecondsAgo, twentySecondsAgo, fiveSecondsAgo) .filter(wereWithinPeriod(minutesAgo(3), secondsAgo(10)) ::apply) .count(); assertEquals(3, filteredCommands); }
Source:
public CreateRequest process(CreateRequest request) throws StopProcessingException { Subject ownerSubject = getSubject(); List<Metacard> metacards = request .getMetacards() .stream() .filter((m) -> aclMetacardTypes.contains(m.getMetacardType().getName())) .collect(Collectors.toList()); boolean missingOwner = metacards .stream() .filter(metacard -> StringUtils.isEmpty(AccessControlUtil.getOwner(metacard))) .findFirst() .isPresent(); if (missingOwner && isGuest(ownerSubject)) { throw new StopProcessingException( "Guest user not allowed to create access-controlled resources"); } metacards.forEach( metacard -> { String owner = AccessControlUtil.getOwner(metacard) != null ? AccessControlUtil.getOwner(metacard) : subjectIdentity.getUniqueIdentifier(ownerSubject); AccessControlUtil.setOwner(metacard, owner); AccessControlUtil.setAccessAdministrator(metacard, owner); }); return request; }

Target:
public CreateRequest process(CreateRequest request) throws StopProcessingException { Subject ownerSubject = getSubject(); List<Metacard> metacards = request .getMetacards() .stream() .filter((m) -> aclMetacardTypes.contains(m.getMetacardType().getName())) .filter((m) -> !m.getTags().contains(SYSTEM_TEMPLATE)) .collect(Collectors.toList()); boolean missingOwner = metacards .stream() .filter(metacard -> StringUtils.isEmpty(AccessControlUtil.getOwner(metacard))) .findFirst() .isPresent(); if (missingOwner && isGuest(ownerSubject)) { throw new StopProcessingException( "Guest user not allowed to create access-controlled resources"); } metacards.forEach( metacard -> { String owner = AccessControlUtil.getOwner(metacard) != null ? AccessControlUtil.getOwner(metacard) : subjectIdentity.getUniqueIdentifier(ownerSubject); AccessControlUtil.setOwner(metacard, owner); AccessControlUtil.setAccessAdministrator(metacard, owner); }); return request; }
Source:
public void removeAllViewsInLayout() { int count = getChildCount(); for (int i = count - 1; i >= 0; i--) { final View view = getChildAt(i); if (view.getAnimation() != null || (mTransitioningFragmentViews != null && mTransitioningFragmentViews.contains(view))) { addDisappearingFragmentView(view); } } super.removeAllViewsInLayout(); }

Target:
public void removeAllViewsInLayout() { for (int i = getChildCount() - 1; i > 0; i--) { final View view = getChildAt(i); addDisappearingFragmentView(view); } super.removeAllViewsInLayout(); addView(mHoldView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); }
Source:
private ExpressionLike(ExpressionLike other) { super(OpTypes.LIKE); this.nodes = other.nodes; this.likeObject = other.likeObject; this.noOptimisation = true; }

Target:
private ExpressionLike(ExpressionLike other) { super(OpTypes.LIKE); this.nodes = other.nodes; this.likeObject = other.likeObject; }
Source:
public Node<V> build() { for (Map.Entry<Long, Long> entry : idToParent.entrySet()) { Node<V> node = idToNode.get(entry.getKey()); Node<V> parent = idToNode.get(entry.getValue()); if (parent == null) { if (rootNode == null) rootNode = new Node<>(); rootNode.addChild(node); } else { parent.addChild(node); } } return rootNode != null ? rootNode : new Node<>(); }

Target:
public Node<V> build() { for (Map.Entry<Long, Long> entry : idToParent.entrySet()) { Node<V> node = idToNode.get(entry.getKey()); Node<V> parent = idToNode.get(entry.getValue()); if (parent == null) { if (rootNode == null) { rootNode = new Node<>(); rootNode.missingRootDummyNode = true; } rootNode.addChild(node); } else { parent.addChild(node); } } return rootNode != null ? rootNode : new Node<>(); }
Source:
private static KeyStore loadTrustStore(File trustStorePath, Optional<String> trustStorePassword) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { List<X509Certificate> certificateChain = PemReader.readCertificateChain(trustStorePath); if (!certificateChain.isEmpty()) { trustStore.load(null, null); for (X509Certificate certificate : certificateChain) { X500Principal principal = certificate.getSubjectX500Principal(); trustStore.setCertificateEntry(principal.getName("RFC2253"), certificate); } } } catch (IOException | GeneralSecurityException e) { } try (InputStream in = new FileInputStream(trustStorePath)) { trustStore.load(in, trustStorePassword.map(String::toCharArray).orElse(null)); } return trustStore; }

Target:
private static KeyStore loadTrustStore(File trustStorePath, Optional<String> trustStorePassword) throws IOException, GeneralSecurityException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { List<X509Certificate> certificateChain = PemReader.readCertificateChain(trustStorePath); if (!certificateChain.isEmpty()) { trustStore.load(null, null); for (X509Certificate certificate : certificateChain) { X500Principal principal = certificate.getSubjectX500Principal(); trustStore.setCertificateEntry(principal.getName(), certificate); } return trustStore; } } catch (IOException | GeneralSecurityException ignored) { } try (InputStream in = new FileInputStream(trustStorePath)) { trustStore.load(in, trustStorePassword.map(String::toCharArray).orElse(null)); } return trustStore; }
Source:
public boolean supports(AuthenticationToken token) { if (!(token instanceof BaseAuthenticationToken)) { LOGGER.debug( "The supplied authentication token is not an instance of BaseAuthenticationToken. Sending back not supported."); return false; } BaseAuthenticationToken authToken = (BaseAuthenticationToken) token; Object credentials = authToken.getCredentials(); if (credentials == null || authToken.getType() != AuthenticationTokenType.PKI) { LOGGER.debug( "The supplied authentication token has null/empty credentials. Sending back no supported."); return false; } LOGGER.debug("Token is supported by {}.", token.getClass(), PKIRealm.class.getName()); return true; }

Target:
public boolean supports(AuthenticationToken token) { if (!(token instanceof BaseAuthenticationToken)) { LOGGER.debug( "The supplied authentication token is not an instance of BaseAuthenticationToken. Sending back not supported."); return false; } BaseAuthenticationToken authToken = (BaseAuthenticationToken) token; Object credentials = authToken.getCredentials(); Object principal = authToken.getPrincipal(); if (authToken.getType() != AuthenticationTokenType.PKI) { LOGGER.debug( "The supplied authentication token has null/empty credentials. Sending back no supported."); return false; } if (credentials instanceof X509Certificate[] && principal instanceof X500Principal) { LOGGER.debug("Token is supported by {}.", token.getClass(), PKIRealm.class.getName()); return true; } return false; }