auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void beforeTest() throws Exception { try { waitForSystemReady(); List<String> featurePolicies = new ArrayList<>(); featurePolicies.addAll(Arrays.asList(getDefaultRequiredApps())); featurePolicies.addAll(FEATURES_TO_FILTER); featurePolicies.replaceAll( featureName -> featureName + "=\"<LINK_0>\""); List<String> servicePolicies = new ArrayList<>(SERVICES_TO_FILTER); servicePolicies.addAll(SERVICES_TO_FILTER); servicePolicies.replaceAll( serviceName -> serviceName + "=\"<LINK_0>\""); String adminConfigPolicyPid = "org.codice.ddf.admin.config.policy.AdminConfigPolicy"; Configuration config = getAdminConfig().getConfiguration(adminConfigPolicyPid); config.setBundleLocation( "mvn:ddf.admin.core/admin-core-configpolicy/" + System.getProperty("ddf.version")); Dictionary properties = new Hashtable<>(); properties.put("featurePolicies", featurePolicies.toArray(new String[0])); properties.put("servicePolicies", servicePolicies.toArray(new String[0])); configureService(adminConfigPolicyPid, properties, getAdminConfig()); } catch (Exception e) { LoggingUtils.failWithThrowableStacktrace(e, "Failed in @BeforeExam: "); } }

Target:
public void beforeTest() throws Exception { try { waitForSystemReady(); List<String> featurePolicies = new ArrayList<>(); featurePolicies.addAll(Arrays.asList(getDefaultRequiredApps())); featurePolicies.addAll(FEATURES_TO_FILTER); featurePolicies.replaceAll( featureName -> featureName + "=\"<LINK_0>\""); List<String> servicePolicies = new ArrayList<>(SERVICES_TO_FILTER); servicePolicies.replaceAll( serviceName -> serviceName + "=\"<LINK_0>\""); String adminConfigPolicyPid = "org.codice.ddf.admin.config.policy.AdminConfigPolicy"; Configuration config = getAdminConfig().getConfiguration(adminConfigPolicyPid); config.setBundleLocation( "mvn:ddf.admin.core/admin-core-configpolicy/" + System.getProperty("ddf.version")); configureAdminConfigPolicy(featurePolicies, servicePolicies, getAdminConfig()); } catch (Exception e) { LoggingUtils.failWithThrowableStacktrace(e, "Failed in @BeforeExam: "); } }
Source:
protected void authenticateWithSSO(HttpServletRequest req, HttpServletResponse resp) throws ServletException { try { req.setAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY, schemes); HttpSession session = req.getSession(false); Deque<AuthenticationProfile> stack = null; if (session != null) { stack = (Deque<AuthenticationProfile>) session.getAttribute(STACK_ATTR); } if (stack == null) { stack = new ArrayDeque<>(); stack.addAll(profiles); } String username = doAuth(req, resp); if (StringUtils.isNotEmpty(username)) { Map<String, Object> response = SSOOAuthServiceUtils.loginOnBehalf(req, resp, username, scope); FiltersHelper.isStatusOk(response); createUserSession(req, FiltersHelper.getPayloadForToken(req, resp, (String) response.get("access_token"))); } } catch (Exception e) { log.error(e.getMessage()); log.debug("External Authentication with SSO failed", e); } }

Target:
protected void authenticateWithSSO(HttpServletRequest req, HttpServletResponse resp) throws ServletException { try { req.setAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY, schemes); HttpSession session = req.getSession(false); Deque<AuthenticationProfile> stack = null; if (session != null) { stack = (Deque<AuthenticationProfile>) session.getAttribute(STACK_ATTR); } if (stack == null) { stack = new ArrayDeque<>(); stack.addAll(profiles); } String username = doAuth(req, resp); if (StringUtils.isNotEmpty(username)) { Map<String, Object> response = SSOOAuthServiceUtils.loginOnBehalf(resp, username, scope); FiltersHelper.isStatusOk(response); SSOUtils.createUserSession(req, FiltersHelper.getPayloadForToken(resp, (String) response.get("access_token")), false); } } catch (Exception e) { log.error("Cannot authenticate using External Authentication: {}", e.getMessage()); log.debug("Cannot authenticate using External Authentication", e); } }
Source:
protected Map<String, Pair<String, String>> getSharedLocks() { if (getDisk() == null) { return null; } switch (getDisk().getVmEntityType()) { case VM: return createSharedLocksForVmDisk(); case TEMPLATE: return createSharedLocksForTemplateDisk(); default: return null; } }

Target:
protected Map<String, Pair<String, String>> getSharedLocks() { if (getDisk() == null) { return null; } switch (getDisk().getVmEntityType()) { case VM: return createSharedLocksForVmDisk(); case TEMPLATE: return createSharedLocksForTemplateDisk(); default: log.warnFormat("No shared locks are taken while removing disk of entity: {0}", getDisk().getVmEntityType()); return null; } }
Source:
protected void executeCommand() { final Guid macPoolId = getParameters().getId(); deletedMacPool = macPoolDao.get(getParameters().getId()); macPoolDao.remove(macPoolId); MacPoolPerDC.getInstance().removePool(macPoolId); getReturnValue().setSucceeded(true); }

Target:
protected void executeCommand() { final Guid macPoolId = getParameters().getId(); deletedMacPool = getMacPoolDAO().get(getParameters().getId()); getMacPoolDAO().remove(macPoolId); MacPoolPerDc.getInstance().removePool(macPoolId); getReturnValue().setSucceeded(true); }
Source:
public void verify_notification_on_branch() throws Exception { RuleDto rule = ruleDbTester.insertRule(newRuleDto()); ComponentDto project = componentDbTester.insertMainBranch(); ComponentDto branch = componentDbTester.insertProjectBranch(project); ComponentDto file = componentDbTester.insertComponent(newFileDto(branch)); DefaultIssue issue = issueDbTester.insertIssue(IssueTesting.newIssue(rule.getDefinition(), branch, file)).setSeverity(MAJOR).toDefaultIssue(); IssueChangeContext context = IssueChangeContext.createUser(new Date(), "john"); issueFieldsSetter.setSeverity(issue, BLOCKER, context); underTest.saveIssue(dbTester.getSession(), issue, context, "increase severity"); verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture()); IssueChangeNotification issueChangeNotification = notificationArgumentCaptor.getValue(); assertThat(issueChangeNotification.getFieldValue("key")).isEqualTo(issue.key()); assertThat(issueChangeNotification.getFieldValue("projectKey")).isEqualTo(project.getDbKey()); assertThat(issueChangeNotification.getFieldValue("projectName")).isEqualTo(project.longName()); assertThat(issueChangeNotification.getFieldValue("branch")).isEqualTo(branch.getBranch()); }

Target:
public void verify_notification_on_branch() throws Exception { RuleDto rule = ruleDbTester.insertRule(newRuleDto()); ComponentDto project = componentDbTester.insertMainBranch(); ComponentDto branch = componentDbTester.insertProjectBranch(project); ComponentDto file = componentDbTester.insertComponent(newFileDto(branch)); DefaultIssue issue = issueDbTester.insertIssue(IssueTesting.newIssue(rule.getDefinition(), branch, file)).setSeverity(MAJOR).toDefaultIssue(); IssueChangeContext context = IssueChangeContext.createUser(new Date(), "john"); issueFieldsSetter.setSeverity(issue, BLOCKER, context); underTest.saveIssue(dbTester.getSession(), issue, context, "increase severity"); verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture()); IssueChangeNotification issueChangeNotification = notificationArgumentCaptor.getValue(); assertThat(issueChangeNotification.getFieldValue("key")).isEqualTo(issue.key()); assertThat(issueChangeNotification.getFieldValue("projectKey")).isEqualTo(project.getDbKey()); assertThat(issueChangeNotification.getFieldValue("projectName")).isEqualTo(project.name()); assertThat(issueChangeNotification.getFieldValue("branch")).isEqualTo(branch.getBranch()); }
Source:
public void onClusterAdded(String clusterName) { incrementClusterAddedCount(clusterName); }

Target:
public void onClusterAdded(String clusterName) { AtomicInteger counter = clusterAddedCounter.computeIfAbsent(clusterName, (name) -> new AtomicInteger()); counter.incrementAndGet(); }
Source:
public void testPutMultipartByteSource() throws Exception { long length = 33554432 + 1; BlobStore blobStore = view.getBlobStore(); MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm( getMinimumMultipartBlobSize(), blobStore.getMaximumMultipartPartSize(), blobStore.getMaximumNumberOfParts()); assertThat(algorithm.calculateChunkSize(length)).isLessThan(length); ByteSource byteSource = TestUtils.randomByteSource().slice(0, length); Payload payload = new ByteSourcePayload(byteSource); payload.getContentMetadata().setContentMD5(Hashing.md5().hashBytes(byteSource.read())); testPut(payload, payload, length, new PutOptions().multipart(true)); }

Target:
public void testPutMultipartByteSource() throws Exception { long length = 32 * 1024 * 1024 + 1; BlobStore blobStore = view.getBlobStore(); MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm( blobStore.getMinimumMultipartPartSize(), blobStore.getMaximumMultipartPartSize(), blobStore.getMaximumNumberOfParts()); assertThat(algorithm.calculateChunkSize(length)).isLessThan(length); ByteSource byteSource = TestUtils.randomByteSource().slice(0, length); Payload payload = new ByteSourcePayload(byteSource); HashCode hashCode = byteSource.hash(Hashing.md5()); testPut(payload, hashCode, payload, length, new PutOptions().multipart(true)); }
Source:
public void deleteSnapshot(final INodesInPath iip, final String snapshotName, INode.ReclaimContext reclaimContext, long now) throws IOException { final INodeDirectory srcRoot = getSnapshottableRoot(iip); if (fsdir.isSnapshotDeletionOrdered()) { final DirectorySnapshottableFeature snapshottable = srcRoot.getDirectorySnapshottableFeature(); final Snapshot snapshot = snapshottable.getSnapshotByName( srcRoot, snapshotName); final int earliest = snapshottable.getDiffs().iterator().next() .getSnapshotId(); if (snapshot.getId() != earliest) { final XAttr snapshotXAttr = buildXAttr(); final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1); xattrs.add(snapshotXAttr); FSDirXAttrOp.unprotectedSetXAttrs(fsdir, INodesInPath.append(iip, snapshot.getRoot(), DFSUtil.string2Bytes(snapshotName)), xattrs, EnumSet.of(XAttrSetFlag.CREATE, XAttrSetFlag.REPLACE)); return; } final INodeDirectoryAttributes first = snapshottable.getDiffs().getFirstSnapshotINode(); if (snapshot.getRoot() != first) { throw new IllegalStateException("Failed to delete snapshot " + snapshotName + " from " + srcRoot.getFullPathName() + " since " + snapshotName + " is not the first snapshot (=" + first + ")"); } } srcRoot.removeSnapshot(reclaimContext, snapshotName, now); numSnapshots.getAndDecrement(); }

Target:
public void deleteSnapshot(final INodesInPath iip, final String snapshotName, INode.ReclaimContext reclaimContext, long now) throws IOException { final INodeDirectory srcRoot = getSnapshottableRoot(iip); if (isSnapshotDeletionOrdered()) { final DirectorySnapshottableFeature snapshottable = srcRoot.getDirectorySnapshottableFeature(); final Snapshot snapshot = snapshottable.getSnapshotByName( srcRoot, snapshotName); final int earliest = snapshottable.getDiffs().getFirst().getSnapshotId(); if (snapshot.getId() != earliest) { final XAttr snapshotXAttr = buildXAttr(); final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1); xattrs.add(snapshotXAttr); FSDirXAttrOp.unprotectedSetXAttrs(fsdir, INodesInPath.append(iip, snapshot.getRoot(), DFSUtil.string2Bytes(snapshotName)), xattrs, EnumSet.of(XAttrSetFlag.CREATE, XAttrSetFlag.REPLACE)); return; } assertFirstSnapshot(srcRoot, snapshottable, snapshot); } srcRoot.removeSnapshot(reclaimContext, snapshotName, now, this); numSnapshots.getAndDecrement(); }
Source:
public String toString() { return toStringHelper("").omitNullValues().add("id", id).add("name", name).toString(); }

Target:
public String toString() { return toStringHelper(this).omitNullValues().add("id", id).add("name", name).toString(); }
Source:
public boolean isApplicableForDwx(CloudSubnet cloudSubnet) { return cloudSubnet.getType() == null || PUBLIC.equals(cloudSubnet.getType()) || SubnetType.PRIVATE.equals(cloudSubnet.getType()) || SubnetType.DWX.equals(cloudSubnet.getType()); }

Target:
public boolean isApplicableForDwx(CloudSubnet cloudSubnet) { return cloudSubnet.getType() == null || PUBLIC.equals(cloudSubnet.getType()) || PRIVATE.equals(cloudSubnet.getType()) || DWX.equals(cloudSubnet.getType()); }
Source:
public Page getNextPage() { if (isFinished()) { return null; } long start = System.nanoTime(); Page page = pageReader.next(); Block[] blocks = new Block[hiveColumnIndexes.length]; for (int fieldId = 0; fieldId < blocks.length; fieldId++) { if (hiveColumnIndexes[fieldId] >= page.getChannelCount()) { throw new PrestoException( NOT_SUPPORTED, "schema mismatched table is not supported for PageFile format"); } blocks[fieldId] = page.getBlock(hiveColumnIndexes[fieldId]); } readTimeNanos += System.nanoTime() - start; completedPositions += page.getPositionCount(); long pageSizeInBytes = page.getSizeInBytes(); completedBytes += pageSizeInBytes; memoryUsageBytes = Math.max(memoryUsageBytes, pageSizeInBytes); return new Page(page.getPositionCount(), blocks); }

Target:
public Page getNextPage() { if (isFinished()) { return null; } long start = System.nanoTime(); Page page = pageReader.next(); Block[] blocks = new Block[hiveColumnIndexes.length]; for (int fieldId = 0; fieldId < blocks.length; fieldId++) { if (hiveColumnIndexes[fieldId] >= page.getChannelCount()) { throw new PrestoException( NOT_SUPPORTED, "schema evolution is not supported for PageFile format"); } blocks[fieldId] = page.getBlock(hiveColumnIndexes[fieldId]); } readTimeNanos += System.nanoTime() - start; completedPositions += page.getPositionCount(); long pageSizeInBytes = page.getSizeInBytes(); completedBytes += pageSizeInBytes; memoryUsageBytes = Math.max(memoryUsageBytes, pageSizeInBytes); return new Page(page.getPositionCount(), blocks); }
Source:
public void onMomPolicyChange(@Observes @MomPolicyUpdate final VDSGroup cluster) { if (cluster == null || cluster.getCompatibilityVersion().compareTo(Version.v3_4) < 0) return; List<VDS> activeHostsInCluster = DbFacade.getInstance() .getVdsDao() .getAllForVdsGroupWithStatus(cluster.getId(), VDSStatus.Up); List<Callable<VDSReturnValue>> callables = new LinkedList<>(); for (final VDS vds : activeHostsInCluster) { callables.add(new Callable<VDSReturnValue>() { @Override public VDSReturnValue call() { VDSReturnValue retVal = new VDSReturnValue(); try { retVal = resourceManagerProvider.get().runVdsCommand(VDSCommandType.SetMOMPolicyParameters, new MomPolicyVDSParameters(vds, cluster.isEnableBallooning(), cluster.isEnableKsm(), cluster.isKsmMergeAcrossNumaNodes()) ); } catch (VdcBLLException e) { log.error("Could not update MoM policy on host '{}'", vds.getName()); retVal.setSucceeded(false); } return retVal; } }); } if (callables.size() > 0) ThreadPoolUtil.invokeAll(callables); }

Target:
public void onMomPolicyChange(@Observes @MomPolicyUpdate final VDSGroup cluster) { if (cluster == null || cluster.getCompatibilityVersion().compareTo(Version.v3_4) < 0) return; List<VDS> activeHostsInCluster = vdsDAO.getAllForVdsGroupWithStatus(cluster.getId(), VDSStatus.Up); List<Callable<Object>> callables = new LinkedList<>(); for (final VDS vds : activeHostsInCluster) { callables.add(new Callable<Object>() { @Override public Object call() { try { resourceManagerProvider.get().runVdsCommand(VDSCommandType.SetMOMPolicyParameters, new MomPolicyVDSParameters(vds, cluster.isEnableBallooning(), cluster.isEnableKsm(), cluster.isKsmMergeAcrossNumaNodes()) ); } catch (VdcBLLException e) { log.error("Could not update MoM policy on host '{}'", vds.getName()); } return null; } }); } if (callables.size() > 0) ThreadPoolUtil.invokeAll(callables); }
Source:
public AddDiskCommand(T parameters) { super(parameters); parameters.getDiskInfo().setId(Guid.NewGuid()); parameters.setEntityId(parameters.getDiskInfo().getId()); isAddToVm = !Guid.Empty.equals(parameters.getVmId()); }

Target:
public AddDiskCommand(T parameters) { super(parameters); parameters.getDiskInfo().setId(Guid.NewGuid()); parameters.setEntityId(parameters.getDiskInfo().getId()); }
Source:
private void registerContainerDeletionSyncTask(StateMachineEngine engine) { if (cloudConfig.cloudContainerCompactionEnabled) { Map<String, TaskFactory> taskFactoryMap = new HashMap<>(); taskFactoryMap.put(DeprecatedContainerCloudSyncTask.class.getSimpleName(), new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new DeprecatedContainerCloudSyncTask(accountService, storeConfig.storeContainerDeletionRetentionDays, cloudDestination, vcrMetrics); } }); if (!taskFactoryMap.isEmpty()) { if (engine.registerStateModelFactory(TaskConstants.STATE_MODEL_NAME, new TaskStateModelFactory(manager, taskFactoryMap))) { logger.info("Container deletion sync task registered with helix."); } else { logger.error("Container deletion sync task registration with helix failed."); } } } }

Target:
private void registerContainerDeletionSyncTask(StateMachineEngine engine) { if (cloudConfig.cloudContainerCompactionEnabled) { Map<String, TaskFactory> taskFactoryMap = new HashMap<>(); taskFactoryMap.put(DeprecatedContainerCloudSyncTask.class.getSimpleName(), new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new DeprecatedContainerCloudSyncTask(accountService, storeConfig.storeContainerDeletionRetentionDays, cloudDestination, vcrMetrics); } }); if (!taskFactoryMap.isEmpty()) { if (engine.registerStateModelFactory(TaskConstants.STATE_MODEL_NAME, new TaskStateModelFactory(manager, taskFactoryMap))) { logger.info("Container deletion sync task registered with helix."); } else { vcrMetrics.deprecationSyncTaskRegistrationFailureCount.inc(); logger.error("Container deletion sync task registration with helix failed."); } } } }
Source:
public MCWeatherType getPlayerWeather() { return MCWeatherType.valueOf(p.getPlayerWeather().name()); }

Target:
public MCWeather getPlayerWeather() { return BukkitMCWeather.getConvertor().getAbstractedEnum(p.getPlayerWeather()); }
Source:
public CloudBackupManager(CloudConfig cloudConfig, ReplicationConfig replicationConfig, ClusterMapConfig clusterMapConfig, StoreConfig storeConfig, StoreKeyFactory storeKeyFactory, ClusterMap clusterMap, VirtualReplicatorCluster virtualReplicatorCluster, ScheduledExecutorService scheduler, ConnectionPool connectionPool, MetricRegistry metricRegistry, NotificationSystem requestNotification, StoreKeyConverterFactory storeKeyConverterFactory, String transformerClassName) throws ReplicationException { super(replicationConfig, clusterMapConfig, storeKeyFactory, clusterMap, scheduler, virtualReplicatorCluster.getDataNodeId(), connectionPool, metricRegistry, requestNotification, storeKeyConverterFactory, transformerClassName); }

Target:
public CloudBackupManager(CloudConfig cloudConfig, ReplicationConfig replicationConfig, ClusterMapConfig clusterMapConfig, StoreConfig storeConfig, StoreKeyFactory storeKeyFactory, ClusterMap clusterMap, VirtualReplicatorCluster virtualReplicatorCluster, ScheduledExecutorService scheduler, ConnectionPool connectionPool, MetricRegistry metricRegistry, NotificationSystem requestNotification, StoreKeyConverterFactory storeKeyConverterFactory, String transformerClassName) throws ReplicationException { super(replicationConfig, clusterMapConfig, storeKeyFactory, clusterMap, scheduler, virtualReplicatorCluster.getCurrentDataNodeId(), connectionPool, metricRegistry, requestNotification, storeKeyConverterFactory, transformerClassName); }
Source:
private String getCanonicalHeadersString(List<HttpHeaderField> headers) { if (headers != null && !headers.isEmpty()) { headers.removeIf( h -> h == null || h.getName() == null || h.getName().trim().isEmpty() || h.getValue() == null); return headers.stream() .sorted((h1, h2) -> h1.getName().compareTo(h2.getName())) .map(h -> h.getName().trim() + "=" + h.getValue().trim()) .collect(Collectors.joining("|")); } return ""; }

Target:
private String getCanonicalHeadersString(List<HttpHeaderField> headers) { return headers.stream() .sorted((h1, h2) -> h1.getName().compareTo(h2.getName())) .map(h -> h.getName().trim() + "=" + h.getValue().trim()) .collect(Collectors.joining("|")); }
Source:
private void validateNetworkExclusiveOnIface(VdsNetworkInterface iface, NetworkType networkType) { String ifaceName = NetworkUtils.StripVlan(iface.getName()); if (ifacesWithExclusiveNetwork.containsKey(ifaceName)) { if ((networkType == NetworkType.VLAN && ifacesWithExclusiveNetwork.get(ifaceName) == NetworkType.VM) || networkType != NetworkType.VLAN) { addViolation(VdcBllMessages.NETWORK_INTERFACES_NOT_EXCLUSIVELY_USED_BY_NETWORK, ifaceName); } } if (networkType != NetworkType.VLAN) { ifacesWithExclusiveNetwork.put(ifaceName, networkType); } }

Target:
private void validateNetworkExclusiveOnIface(VdsNetworkInterface iface, NetworkType networkType) { String ifaceName = NetworkUtils.StripVlan(iface.getName()); List<NetworkType> networksOnIface = ifacesWithExclusiveNetwork.get(ifaceName); if (networksOnIface == null) { networksOnIface = new ArrayList<SetupNetworksHelper.NetworkType>(); ifacesWithExclusiveNetwork.put(ifaceName, networksOnIface); } if ((networkType == NetworkType.VLAN && networksOnIface.contains(NetworkType.VM)) || (networkType == NetworkType.VM && !networksOnIface.isEmpty())) { addViolation(VdcBllMessages.NETWORK_INTERFACES_NOT_EXCLUSIVELY_USED_BY_NETWORK, ifaceName); } networksOnIface.add(networkType); }
Source:
public CouchDbConsentDecision(final ConsentDecision c) { setAttributes(c.getAttributes()); setPrincipal(c.getPrincipal()); setCreatedDate(c.getCreatedDate()); setId(c.getId()); setOptions(c.getOptions()); setReminder(c.getReminder()); setReminderTimeUnit(c.getReminderTimeUnit()); setService(c.getService()); if (getId() < 0) { setId(SecureRandom.getInstanceStrong().nextLong()); } }

Target:
public CouchDbConsentDecision(final ConsentDecision c) { setAttributes(c.getAttributes()); setPrincipal(c.getPrincipal()); setCreatedDate(c.getCreatedDate()); setId(c.getId()); setOptions(c.getOptions()); setReminder(c.getReminder()); setReminderTimeUnit(c.getReminderTimeUnit()); setService(c.getService()); if (getId() < 0) { setId(Math.abs(RandomUtils.getNativeInstance().nextLong())); } }
Source:
public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password); if(u != null) { Authentication auth; try { UserDetails userDetails = u.getUserDetailsForImpersonation(); if (UserDetailsHelper.isFullyActive(userDetails)) { auth = u.impersonate(userDetails); SecurityListener.fireAuthenticated(userDetails); } else { LOGGER.log(INFO, "API token matched for user {0} but the account is [enable={1}, accountNonExpired={2}, accountNonLocked={3}, credentialsNonExpired={4}]", new Object[]{ username, userDetails.isEnabled(), userDetails.isAccountNonExpired(), userDetails.isAccountNonLocked(), userDetails.isCredentialsNonExpired() }); return null; } } catch (UsernameNotFoundException x) { LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true); return auth; } return null; }

Target:
public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password); if(u != null) { Authentication auth; try { UserDetails userDetails = u.getUserDetailsForImpersonation(); if (UserDetailsHelper.isFullyActive(userDetails)) { auth = u.impersonate(userDetails); SecurityListener.fireAuthenticated(userDetails); } else { LOGGER.log(INFO, "API token matched for user {0} but the account is [enabled={1}, accountNonExpired={2}, accountNonLocked={3}, credentialsNonExpired={4}]", new Object[]{ username, userDetails.isEnabled(), userDetails.isAccountNonExpired(), userDetails.isAccountNonLocked(), userDetails.isCredentialsNonExpired() }); return null; } } catch (UsernameNotFoundException x) { LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true); return auth; } return null; }
Source:
public List<Repository> clearCache(Collection<String> repositories) throws HistoryException { List<Repository> repos = getReposFromString(repositories); HistoryCache cache = historyCache; for (Repository r : repos) { try { cache.clear(r); LOGGER.log(Level.INFO, "History cache for {0} cleared.", r.getDirectoryName()); } catch (HistoryException e) { LOGGER.log(Level.WARNING, "Clearing history cache for repository {0} failed: {1}", new Object[]{r.getDirectoryName(), e.getLocalizedMessage()}); } } return repos; }

Target:
public List<Repository> clearCache(Collection<String> repositories) throws HistoryException { List<Repository> repos = new ArrayList<>(); HistoryCache cache = historyCache; if (!useCache()) { return repos; } for (Repository r : getReposFromString(repositories)) { try { cache.clear(r); repos.add(r); LOGGER.log(Level.INFO, "History cache for {0} cleared.", r.getDirectoryName()); } catch (HistoryException e) { LOGGER.log(Level.WARNING, "Clearing history cache for repository {0} failed: {1}", new Object[]{r.getDirectoryName(), e.getLocalizedMessage()}); } } return repos; }
Source:
public void setUp() { subject = mock(Subject.class); accessPlugin = new ShareableMetacardAccessPlugin() { @Override protected Subject getSubject() { return subject; } }; ShareableMetacardImpl.setShareableMetacardType( new MetacardTypeImpl( "metacard.sharing", Arrays.asList(new SecurityAttributes(), new CoreAttributes()))); }

Target:
public void setUp() { subject = mock(Subject.class); accessPlugin = new ShareableMetacardAccessPlugin() { @Override protected Subject getSubject() { return subject; } }; }
Source:
public void onCustomizedStateConfigChange( CustomizedStateConfig customizedStateConfig, NotificationContext context) { HelixManager helixManager = context.getManager(); List<String> customizedStates = getEnabledCustomizedStates(helixManager); Map<String, LiveInstance> liveInstanceMap = helixManager.getHelixDataAccessor() .getChildValuesMap(helixManager.getHelixDataAccessor().keyBuilder().liveInstances()); List<String> liveInstances = liveInstanceMap.values().stream() .map(liveInstance -> liveInstance.getInstanceName()).collect(Collectors.toList()); for (String customizedState : customizedStates) { for (String instance : liveInstances) { addCustomizedStateListeners(helixManager, customizedState, instance); } } logger.info( "START: GenericClusterController.onCustomizedStateConfigChange() for cluster " + _clusterName); notifyCaches(context, ChangeType.CUSTOMIZED_STATE_CONFIG); pushToEventQueues(ClusterEventType.CustomizeStateAggregationConfigChange, context, Collections.<String, Object> emptyMap()); logger.info( "END: GenericClusterController.onCustomizedStateConfigChange() for cluster " + _clusterName); }

Target:
public void onCustomizedStateConfigChange( CustomizedStateConfig customizedStateConfig, NotificationContext context) { logger.info( "START: GenericClusterController.onCustomizedStateConfigChange() for cluster " + _clusterName); notifyCaches(context, ChangeType.CUSTOMIZED_STATE_CONFIG); pushToEventQueues(ClusterEventType.CustomizeStateConfigChange, context, Collections.<String, Object> emptyMap()); logger.info( "END: GenericClusterController.onCustomizedStateConfigChange() for cluster " + _clusterName); }
Source:
public Optional<Object> apply( final Object... args ) { if(args.length == 0) { return Optional.empty(); } Object arg = args[0]; if(arg != null) { if(arg instanceof Integer) { return Optional.<Object>of( java.lang.Math.abs( (Integer) arg )); } else if(arg instanceof Double) { return Optional.<Object>of( java.lang.Math.abs( (Double) arg )); } } return Optional.empty(); }

Target:
public Optional<Object> apply( final Object... args ) { if(args.length == 0) { return Optional.empty(); } Object arg = args[0]; if(arg != null) { if(arg instanceof Integer) { return Optional.<Object>of( java.lang.Math.abs( (Integer) arg )); } else if(arg instanceof Double) { return Optional.<Object>of( java.lang.Math.abs( (Double) arg )); } else if(arg instanceof Long) { return Optional.<Object>of( java.lang.Math.abs( (Long) arg )); } } return Optional.empty(); }
Source:
public void testSetDMNModel() { picker.setDMNModel(dmnModel); verify(qNameFieldConverter).setDMNModel(eq(dmnModel)); verify(typeSelector).clear(); final BuiltInType[] bits = BuiltInType.values(); verify(picker, times(bits.length)).makeTypeSelector(builtInTypeCaptor.capture()); final List<BuiltInType> builtInTypes = new ArrayList<>(Arrays.asList(bits)); builtInTypes.removeAll(builtInTypeCaptor.getAllValues()); assertTrue(builtInTypes.isEmpty()); final List<ItemDefinition> itemDefinitions = definitions.getItemDefinition(); verify(picker, times(itemDefinitions.size())).makeTypeSelector(itemDefinitionCaptor.capture()); itemDefinitions.removeAll(itemDefinitionCaptor.getAllValues()); assertTrue(itemDefinitions.isEmpty()); }

Target:
public void testSetDMNModel() { picker.setDMNModel(dmnModel); verify(qNameFieldConverter).setDMNModel(eq(dmnModel)); verify(typeSelector).clear(); final BuiltInType[] bits = BuiltInType.values(); verify(picker, times(bits.length)).makeTypeSelector(builtInTypeCaptor.capture()); final List<BuiltInType> builtInTypes = new ArrayList<>(Arrays.asList(bits)); assertFalse(builtInTypes.isEmpty()); builtInTypes.removeAll(builtInTypeCaptor.getAllValues()); assertTrue(builtInTypes.isEmpty()); final List<ItemDefinition> itemDefinitions = definitions.getItemDefinition(); verify(picker, times(itemDefinitions.size())).makeTypeSelector(itemDefinitionCaptor.capture()); assertFalse(itemDefinitions.isEmpty()); itemDefinitions.removeAll(itemDefinitionCaptor.getAllValues()); assertTrue(itemDefinitions.isEmpty()); }
Source:
public void shouldConcatenateOneNonEmptyList() { final List<Integer> list = Collections.unmodifiableList( IntStream.range(0, 4) .boxed() .collect(Collectors.toList()) ); final List<Integer> actual = ListOps.concat(list); final List<Integer> expected = IntStream.range(0, 4) .boxed() .collect(Collectors.toList()); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }

Target:
public void shouldConcatenateOneNonEmptyList() { final List<Integer> list = Collections.unmodifiableList( Arrays.asList(0, 1, 2, 3, 4) ); final List<Integer> actual = ListOps.concat(list); final List<Integer> expected = Arrays.asList(0, 1, 2, 3, 4); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }
Source:
private void close(SelectionKey key) { Transmission transmission = getTransmission(key); if (transmission != null) { logger.debug("Closing connection from {}", transmission.getConnectionId()); this.disconnected.add(transmission.getConnectionId()); this.keyMap.remove(transmission.getConnectionId()); activeConnections.set(this.keyMap.size()); try { transmission.close(); if (pendingSslHandshakes.contains(transmission.getConnectionId())) { pendingSslHandshakes.remove(transmission.getConnectionId()); sslHandshakeTimer.remove(transmission.getConnectionId()); } } catch (IOException e) { logger.error("IOException thrown during closing of transmission with connectionId :", transmission.getConnectionId(), e); } } else { key.attach(null); key.cancel(); SocketAddress address = null; try { SocketChannel socketChannel = channel(key); address = socketChannel.socket().getRemoteSocketAddress(); socketChannel.socket().close(); socketChannel.close(); } catch (IOException e) { metrics.selectorCloseSocketErrorCount.inc(); logger.error("Exception closing connection to remote host :", address, e); } } this.metrics.selectorConnectionClosed.inc(); }

Target:
private void close(SelectionKey key) { Transmission transmission = getTransmission(key); if (transmission != null) { logger.debug("Closing connection from {}", transmission.getConnectionId()); this.disconnected.add(transmission.getConnectionId()); this.keyMap.remove(transmission.getConnectionId()); numActiveConnections.set(keyMap.size()); unreadyConnections.remove(transmission.getConnectionId()); try { transmission.close(); } catch (IOException e) { logger.error("IOException thrown during closing of transmission with connectionId :", transmission.getConnectionId(), e); } } else { key.attach(null); key.cancel(); SocketAddress address = null; try { SocketChannel socketChannel = channel(key); address = socketChannel.socket().getRemoteSocketAddress(); socketChannel.socket().close(); socketChannel.close(); } catch (IOException e) { metrics.selectorCloseSocketErrorCount.inc(); logger.error("Exception closing connection to remote host :", address, e); } } this.metrics.selectorConnectionClosed.inc(); }
Source:
public Roles mapRoles(Roles rolesToMap) { Roles res = new MappedRoles(rolesToMap, this.reverseRoleMap); if (keepMapped) { res = res.or(rolesToMap.and(keyRoles)); } if (keepNonMapped) { res = res.or(rolesToMap.minus(keyRoles)); } return res; }

Target:
public Roles mapRoles(Roles rolesToMap) { if (!initialized) { throw log.roleMappedNotInitialized(); } return new MappedRoles(rolesToMap, this.reverseRoleMap); }
Source:
public int hashCode() { return Objects.hashCode(tableName, null != addNewColumn ? Objects.hashCode(addNewColumn) : addNewColumn, null != alterTableOpType ? Objects.hashCode(alterTableOpType) : alterTableOpType, null != columnName ? Objects.hashCode(columnName) : columnName, null != newColumnName ? Objects.hashCode(newColumnName) : newColumnName, null != newTableName ? Objects.hashCode(newTableName) : newTableName, null != tableName ? Objects.hashCode(tableName) : tableName, null != properties ? Objects.hashCode(properties) : properties, null != columnNames ? Objects.hashCode(columnNames) : columnNames, null != partitionValues ? Objects.hashCode(partitionValues) : partitionValues, null != location ? Objects.hashCode(location) : location ); }

Target:
public int hashCode() { return Objects.hashCode(tableName, addNewColumn, alterTableOpType, columnName, newColumnName, newTableName, tableName, properties, partitionColumns, partitionValues, location, isPurge); }
Source:
public Map<String, List<String>> getRoutingData() throws InvalidRoutingDataException { Map<String, List<String>> routingData = new HashMap<>(); List<String> allRealmAddresses; try { allRealmAddresses = _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH); } catch (ZkNoNodeException e) { throw new InvalidRoutingDataException( "Routing data directory ZNode " + MetadataStoreRoutingConstants.ROUTING_DATA_PATH + " does not exist. Routing ZooKeeper address: " + _zkAddress); } for (String realmAddress : allRealmAddresses) { ZNRecord record = _zkClient.readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + realmAddress); if (record != null) { List<String> shardingKeys = record.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY); routingData .put(realmAddress, shardingKeys != null ? shardingKeys : Collections.emptyList()); } } return routingData; }

Target:
public Map<String, List<String>> getRoutingData() throws InvalidRoutingDataException { Map<String, List<String>> routingData = new HashMap<>(); List<String> allRealmAddresses; try { allRealmAddresses = _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH); } catch (ZkNoNodeException e) { throw new InvalidRoutingDataException( "Routing data directory ZNode " + MetadataStoreRoutingConstants.ROUTING_DATA_PATH + " does not exist. Routing ZooKeeper address: " + _zkAddress); } if (allRealmAddresses != null) { for (String realmAddress : allRealmAddresses) { ZNRecord record = _zkClient .readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + realmAddress); if (record != null) { List<String> shardingKeys = record.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY); routingData .put(realmAddress, shardingKeys != null ? shardingKeys : Collections.emptyList()); } } } return routingData; }
Source:
private List<Container> pickOpportunisticContainersToKill( ContainerId containerToStartId) { List<Container> extraOpportContainersToKill = new ArrayList<>(); ResourceUtilization resourcesToFreeUp = resourcesToFreeUp( containerToStartId); Iterator<Container> reverseContainerIterator = new LinkedList<>(scheduledToRunContainers.values()).descendingIterator(); while(reverseContainerIterator.hasNext() && !hasSufficientResources(resourcesToFreeUp)) { Container runningCont = reverseContainerIterator.next(); if (runningCont.getContainerTokenIdentifier().getExecutionType() == ExecutionType.OPPORTUNISTIC) { if (oppContainersMarkedForKill.containsKey( runningCont.getContainerId())) { continue; } extraOpportContainersToKill.add(runningCont); ResourceUtilizationManager.decreaseResourceUtilization( getContainersMonitor(), resourcesToFreeUp, runningCont.getResource()); } } if (!hasSufficientResources(resourcesToFreeUp)) { LOG.warn("There are no sufficient resources to start guaranteed [{}]" + "even after attempting to kill all running" + "opportunistic containers.", containerToStartId); } return extraOpportContainersToKill; }

Target:
private List<Container> pickOpportunisticContainersToKill( ContainerId containerToStartId) { List<Container> extraOpportContainersToKill = new ArrayList<>(); ResourceUtilization resourcesToFreeUp = resourcesToFreeUp( containerToStartId); Iterator<Container> lifoIterator = new LinkedList<>( runningContainers.values()).descendingIterator(); while(lifoIterator.hasNext() && !hasSufficientResources(resourcesToFreeUp)) { Container runningCont = lifoIterator.next(); if (runningCont.getContainerTokenIdentifier().getExecutionType() == ExecutionType.OPPORTUNISTIC) { if (oppContainersToKill.containsKey( runningCont.getContainerId())) { continue; } extraOpportContainersToKill.add(runningCont); ContainersMonitor.decreaseResourceUtilization( getContainersMonitor(), resourcesToFreeUp, runningCont.getResource()); } } if (!hasSufficientResources(resourcesToFreeUp)) { LOG.warn("There are no sufficient resources to start guaranteed [{}]" + "at the moment. Opportunistic containers are in the process of" + "being killed to make room.", containerToStartId); } return extraOpportContainersToKill; }
Source:
private void parseIncompleteRoot(CommonTree root) throws ParseException { List<CommonTree> children = root.getChildren(); List<CommonTree> events = new ArrayList<>(); if (!fHasBeenParsed) { throw new ParseException("You need to run generate first"); } pushScope(); for (CommonTree child : children) { final int type = child.getType(); switch (type) { case CTFParser.DECLARATION: parseRootDeclaration(child); break; case CTFParser.TRACE: throw new ParseException("Trace block defined here, please use generate and not generateFragment to parse this fragment"); case CTFParser.STREAM: parseStream(child); break; case CTFParser.EVENT: events.add(child); break; case CTFParser.CLOCK: parseClock(child); break; case CTFParser.ENV: parseEnvironment(child); break; case CTFParser.CALLSITE: parseCallsite(child); break; default: childTypeError(child); } } parseEvents(!Iterables.isEmpty(fTrace.getStreams()), events); popScope(); }

Target:
private void parseIncompleteRoot(CommonTree root) throws ParseException { if (!fHasBeenParsed) { throw new ParseException("You need to run generate first"); } List<CommonTree> children = root.getChildren(); List<CommonTree> events = new ArrayList<>(); pushScope(); for (CommonTree child : children) { final int type = child.getType(); switch (type) { case CTFParser.DECLARATION: parseRootDeclaration(child); break; case CTFParser.TRACE: throw new ParseException("Trace block defined here, please use generate and not generateFragment to parse this fragment"); case CTFParser.STREAM: parseStream(child); break; case CTFParser.EVENT: events.add(child); break; case CTFParser.CLOCK: parseClock(child); break; case CTFParser.ENV: parseEnvironment(child); break; case CTFParser.CALLSITE: parseCallsite(child); break; default: childTypeError(child); } } parseEvents(events, !Iterables.isEmpty(fTrace.getStreams())); popScope(); }
Source:
private EventLogCategory getEventLogCategory(final Map<String, String> parameters) { if (parameters.containsKey(PlatformSmartmeteringKeys.EVENT_TYPE)) { return EventLogCategory.fromValue(parameters.get(PlatformSmartmeteringKeys.EVENT_TYPE)); } return DEFAULT_EVENT_LOG_CATEGORY; }

Target:
private EventLogCategory getEventLogCategory(final Map<String, String> parameters) { return Helpers.getEnum(parameters, PlatformSmartmeteringKeys.EVENT_TYPE, EventLogCategory.class, DEFAULT_EVENT_LOG_CATEGORY); }
Source:
protected int getTitle(boolean move) { return move ? R.string.crypt_decrypting : R.string.crypt_encrypting; }

Target:
protected int getTitle(boolean move) { return R.string.crypt_encrypting; }
Source:
public void testPingPongFlowControlWhenAutoReadIsDisabled() { String text1 = "Hello, world #1"; String text2 = "Hello, world #2"; String text3 = "Hello, world #3"; String text4 = "Hello, world #4"; EmbeddedChannel channel = new EmbeddedChannel(); channel.config().setAutoRead(false); channel.pipeline().addLast(new FlowControlHandler()); channel.pipeline().addLast(new WebSocketProtocolHandler() { }); channel.writeInbound( new PingWebSocketFrame(Unpooled.copiedBuffer(text1, UTF_8)), new TextWebSocketFrame(text2), new TextWebSocketFrame(text3), new PingWebSocketFrame(Unpooled.copiedBuffer(text4, UTF_8)) ); assertNull(channel.readInbound()); assertNull(channel.readOutbound()); channel.read(); PongWebSocketFrame response1 = channel.readOutbound(); assertEquals(text1, response1.content().toString(UTF_8)); TextWebSocketFrame message2 = channel.readInbound(); assertEquals(text2, message2.text()); assertNull(channel.readInbound()); assertNull(channel.readOutbound()); channel.read(); TextWebSocketFrame message3 = channel.readInbound(); assertEquals(text3, message3.text()); assertNull(channel.readInbound()); assertNull(channel.readOutbound()); response1.release(); message2.release(); message3.release(); assertFalse(channel.finish()); }

Target:
public void testPingPongFlowControlWhenAutoReadIsDisabled() { String text1 = "Hello, world #1"; String text2 = "Hello, world #2"; String text3 = "Hello, world #3"; String text4 = "Hello, world #4"; EmbeddedChannel channel = new EmbeddedChannel(); channel.config().setAutoRead(false); channel.pipeline().addLast(new FlowControlHandler()); channel.pipeline().addLast(new WebSocketProtocolHandler() { }); assertFalse(channel.writeInbound( new PingWebSocketFrame(Unpooled.copiedBuffer(text1, UTF_8)), new TextWebSocketFrame(text2), new TextWebSocketFrame(text3), new PingWebSocketFrame(Unpooled.copiedBuffer(text4, UTF_8)) )); assertNull(channel.readInbound()); assertNull(channel.readOutbound()); channel.read(); PongWebSocketFrame response1 = channel.readOutbound(); assertEquals(text1, response1.content().toString(UTF_8)); TextWebSocketFrame message2 = channel.readInbound(); assertEquals(text2, message2.text()); assertNull(channel.readInbound()); assertNull(channel.readOutbound()); channel.read(); TextWebSocketFrame message3 = channel.readInbound(); assertEquals(text3, message3.text()); assertNull(channel.readInbound()); assertNull(channel.readOutbound()); response1.release(); message2.release(); message3.release(); assertFalse(channel.finish()); }
Source:
public void testLocationIndex() { final double small = 5e-7; final double big = 2e-6; locationIndexCase(makeList(), new LatLng(0, 0), -1); locationIndexCase(makeList(1, 2), new LatLng(1, 2), 0); locationIndexCase(makeList(1, 2), new LatLng(3, 5), -1); locationIndexCase(makeList(1, 2, 3, 5), new LatLng(1, 2), 0); locationIndexCase(makeList(1, 2, 3, 5), new LatLng(3, 5), 1); locationIndexCase(makeList(1, 2, 3, 5), new LatLng(4, 6), -1); locationIndexCase(makeList(0, 90-small, 0, 90, 0, 90+small), new LatLng(0, 90), 0); locationIndexCase(makeList(0, 90-big, 0, 90, 0, 90+big), new LatLng(0, 90), 1); locationIndexCase(makeList(0, 90-small, 0, 90, 0, 90+small), new LatLng(0, 90+big), -1); }

Target:
public void testLocationIndex() { locationIndexCase(makeList(), new LatLng(0, 0), -1); locationIndexCase(makeList(1, 2), new LatLng(1, 2), 0); locationIndexCase(makeList(1, 2), new LatLng(3, 5), -1); locationIndexCase(makeList(1, 2, 3, 5), new LatLng(1, 2), 0); locationIndexCase(makeList(1, 2, 3, 5), new LatLng(3, 5), 0); locationIndexCase(makeList(1, 2, 3, 5), new LatLng(4, 6), -1); locationIndexCase(makeList(0, 80, 0, 90, 0, 100), new LatLng(0, 80), 0); locationIndexCase(makeList(0, 80, 0, 90, 0, 100), new LatLng(0, 85), 0); locationIndexCase(makeList(0, 80, 0, 90, 0, 100), new LatLng(0, 90), 0); locationIndexCase(makeList(0, 80, 0, 90, 0, 100), new LatLng(0, 95), 1); locationIndexCase(makeList(0, 80, 0, 90, 0, 100), new LatLng(0, 100), 1); locationIndexCase(makeList(0, 80, 0, 90, 0, 100), new LatLng(0, 110), -1); }
Source:
public String extractScoreTypeFqn( final DataObject dataObject, final Path dataObjectPath ) { String superClassName = dataObject.getSuperClassName(); if ( superClassName.matches( "(\\w+\\.)*AbstractSolution<(\\w+\\.)*\\w+>" ) ) { String scoreType = superClassName.substring( superClassName.indexOf( "<" ) + 1, superClassName.lastIndexOf( ">" ) ); final String scoreTypeFqn; if ( scoreType.contains( "." ) ) { scoreTypeFqn = scoreType; } else { KieProject kieProject = kieProjectService.resolveProject( dataObjectPath ); Set<String> imports = dataObject.getImports().stream().map( i -> i.getName() ).collect( Collectors.toSet() ); ClassLoader projectClassLoader = classLoaderHelper.getProjectClassLoader( kieProject ); ClassTypeResolver classTypeResolver = new ClassTypeResolver( imports, projectClassLoader ); try { scoreTypeFqn = classTypeResolver.getFullTypeName( scoreType ); } catch ( ClassNotFoundException e ) { return null; } } return scoreTypeFqn; } return null; }

Target:
public String extractScoreTypeFqn( final DataObject dataObject, final Path dataObjectPath ) { Matcher matcher = ABSTRACT_SOLUTION_PATTERN.matcher( dataObject.getSuperClassName() ); if ( matcher.matches() ) { String scoreType = matcher.group( 1 ); final String scoreTypeFqn; if ( scoreType.contains( "." ) ) { scoreTypeFqn = scoreType; } else { KieProject kieProject = kieProjectService.resolveProject( dataObjectPath ); Set<String> imports = dataObject.getImports().stream().map( i -> i.getName() ).collect( Collectors.toSet() ); ClassLoader projectClassLoader = classLoaderHelper.getProjectClassLoader( kieProject ); ClassTypeResolver classTypeResolver = new ClassTypeResolver( imports, projectClassLoader ); try { scoreTypeFqn = classTypeResolver.getFullTypeName( scoreType ); } catch ( ClassNotFoundException e ) { return null; } } return scoreTypeFqn; } return null; }
Source:
void writeFileDirectories() throws Exception { metaData.setDefaultFileDirectory("\\Literature\\"); metaData.setUserFileDirectory("defaultOwner-user", "D:\\Documents"); metaData.setLaTexFileDirectory("defaultOwner-user", "D:\\Documents"); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals(OS.NEWLINE + "@Comment{jabref-meta: fileDirectory:\\\\Literature\\\\;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory-defaultOwner-user:D:\\\\Documents;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: fileDirectoryldefaultOwner-user:D:\\\\Documents;}" + OS.NEWLINE, stringWriter.toString()); }

Target:
void writeFileDirectories() throws Exception { metaData.setDefaultFileDirectory("\\Literature\\"); metaData.setUserFileDirectory("defaultOwner-user", "D:\\Documents"); metaData.setLaTexFileDirectory("defaultOwner-user", Paths.get("D:\\Latex")); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals(OS.NEWLINE + "@Comment{jabref-meta: fileDirectory:\\\\Literature\\\\;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory-defaultOwner-user:D:\\\\Documents;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: fileDirectoryLatex-defaultOwner-user:D:\\\\Latex;}" + OS.NEWLINE, stringWriter.toString()); }