auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void processOptions(RepositoryState state) throws NoMessageException { if (committer == null) committer = new PersonIdent(repo); if (author == null && !amend) author = committer; if (state == RepositoryState.MERGING_RESOLVED) { try { RevWalk rw = new RevWalk(repo); parents = repo.readMergeHeads(); if (parents != null) for (int i = 0; i < parents.size(); i++) { RevObject ro = rw.parseAny(parents.get(i)); if (ro instanceof RevTag) parents.set(i, rw.peel(ro)); } } catch (IOException e) { throw new JGitInternalException(MessageFormat.format( JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_HEAD, e), e); } if (message == null) { try { message = repo.readMergeCommitMsg(); } catch (IOException e) { throw new JGitInternalException(MessageFormat.format( JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_MSG, e), e); } } } else if (state == RepositoryState.SAFE && message == null) { try { message = repo.readSquashCommitMsg(); if (message != null) repo.writeSquashCommitMsg(null ); } catch (IOException e) { throw new JGitInternalException(MessageFormat.format( JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_MSG, e), e); } } if (message == null) throw new NoMessageException(JGitText.get().commitMessageNotSpecified); }

Target:
private void processOptions(RepositoryState state) throws NoMessageException { if (committer == null) committer = new PersonIdent(repo); if (author == null && !amend) author = committer; if (state == RepositoryState.MERGING_RESOLVED) { try { parents = repo.readMergeHeads(); if (parents != null) for (int i = 0; i < parents.size(); i++) { RevObject ro = rw.parseAny(parents.get(i)); if (ro instanceof RevTag) parents.set(i, rw.peel(ro)); } } catch (IOException e) { throw new JGitInternalException(MessageFormat.format( JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_HEAD, e), e); } if (message == null) { try { message = repo.readMergeCommitMsg(); } catch (IOException e) { throw new JGitInternalException(MessageFormat.format( JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_MSG, e), e); } } } else if (state == RepositoryState.SAFE && message == null) { try { message = repo.readSquashCommitMsg(); if (message != null) repo.writeSquashCommitMsg(null ); } catch (IOException e) { throw new JGitInternalException(MessageFormat.format( JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_MSG, e), e); } } if (message == null) throw new NoMessageException(JGitText.get().commitMessageNotSpecified); }
Source:
public void testSTPoint() throws Exception { assertQuery("select st_as_text(st_point(1, 4))", "select 'POINT (1 4)'"); }

Target:
public void testSTPoint() throws Exception { assertFunction("ST_AsText(ST_Point(1, 4))", VARCHAR, "POINT (1 4)"); assertFunction("ST_AsText(ST_Point(122.3, 10.55))", VARCHAR, "POINT (122.3 10.55)"); }
Source:
private void handleBatchCallback( final SearchResult searchResult, final Repository repository, final NodeVersionQuery nodeVersionQuery ) { final List<NodeVersionDocumentId> toBeDeleted = Lists.newArrayList(); final long versionTotal = searchResult.getTotalHits(); if ( !this.repositoryCleanStarted ) { if ( listener != null ) { listener.vacuumingVersionRepository( repository.getId(), versionTotal ); } this.repositoryCleanStarted = true; } if ( searchResult.getHits().getSize() == 0 ) { return; } final NodeVersionQueryResult nodeVersionQueryResult = NodeVersionQueryResultFactory.create( nodeVersionQuery, searchResult ); nodeVersionQueryResult.getNodeVersionsMetadata().forEach( ( version ) -> { processVersion( repository, result, toBeDeleted, version ); if ( listener != null ) { listener.vacuumingVersion( 1L ); } } ); LOG.info( "Deleting: " + toBeDeleted.size() + " versions from repository: " + repository.getId() ); versionService.delete( toBeDeleted, InternalContext.from( ContextAccessor.current() ) ); }

Target:
private void handleBatchCallback( final SearchResult searchResult, final Repository repository, final NodeVersionQuery nodeVersionQuery ) { final List<NodeVersionDocumentId> toBeDeleted = Lists.newArrayList(); final long versionTotal = searchResult.getTotalHits(); if ( !this.repositoryCleanStarted ) { if ( listener != null ) { listener.vacuumingVersionRepository( repository.getId(), versionTotal ); } this.repositoryCleanStarted = true; } if ( searchResult.isEmpty() ) { return; } final NodeVersionQueryResult nodeVersionQueryResult = NodeVersionQueryResultFactory.create( nodeVersionQuery, searchResult ); nodeVersionQueryResult.getNodeVersionsMetadata().forEach( ( version ) -> { processVersion( repository, result, toBeDeleted, version ); if ( listener != null ) { listener.vacuumingVersion( 1L ); } } ); LOG.info( "Deleting: " + toBeDeleted.size() + " versions from repository: " + repository.getId() ); versionService.delete( toBeDeleted, InternalContext.from( ContextAccessor.current() ) ); }
Source:
public void getUserByActivationKey_shouldGetUserUsingActivationKey() { executeDataSet(XML_FILENAME); User user = userService.getUserByActivationKey("XbklsieiskeuztecEnPf"); assertNotNull("User with activationKey ", user); if(user!=null) { String[] tokens = user.getActivationKey().split(":"); assertEquals("XbklsieiskeuztecEnPf",tokens[0]); } }

Target:
public void getUserByActivationKey_shouldGetUserUsingActivationKey() { executeDataSet(XML_FILENAME); String key="XbklsieiskeuztecEnPf"; User user = userService.getUserByActivationKey(key); assertNotNull("User with activationKey ", user); String[] tokens = user.getActivationKey().split(":"); assertEquals(key,tokens[0]); }
Source:
private static List<File> listFiles(String directory, String suffix) { File dir = new File(directory); List<File> propFiles = new ArrayList<>(); if (!dir.exists()) { logger.warn("Directory {0} doesn't exists.", directory); return propFiles; } File[] dirFiles = dir.listFiles(); if (dirFiles != null) { for (File file : dirFiles) { if (file.getName().endsWith(suffix)) { propFiles.add(file); } } } return propFiles; }

Target:
private static List<File> listFiles(String directory, String suffix) { File dir = new File(directory); List<File> propFiles = new ArrayList<>(); if (!dir.exists()) { logger.warn("Directory doesn't exists.", directory); return propFiles; } File[] dirFiles = dir.listFiles(); if (dirFiles != null) { for (File file : dirFiles) { if (file.getName().endsWith(suffix)) { propFiles.add(file); } } } return propFiles; }
Source:
public void findFiles(final FileSelector selector, final boolean depthwise, final List<FileObject> selected) throws FileSystemException { if (forkJoinPool == null) { super.findFiles(selector, depthwise, selected); } else { try { if (exists()) { final DefaultFileSelectorInfo info = new DefaultFileSelectorInfo(); info.setBaseFolder(this); info.setDepth(0); info.setFile(this); selected.addAll(forkJoinPool.invoke(new TraverseTask(info, selector, depthwise))); } } catch (final Exception e) { throw new FileSystemException("vfs.provider/find-files.error", getName(), e); } } }

Target:
public void findFiles(final FileSelector selector, final boolean depthwise, final List<FileObject> selected) throws FileSystemException { if (forkJoinPool == null) { super.findFiles(selector, depthwise, selected); } else { try { if (exists()) { final DefaultFileSelectorInfo info = new DefaultFileSelectorInfo(); info.setBaseFolder(this); info.setDepth(0); info.setFile(this); selected.addAll(forkJoinPool.invoke(new TraverseFilesTask(info, selector, depthwise))); } } catch (final Exception e) { throw new FileSystemException("vfs.provider/find-files.error", getName(), e); } } }
Source:
public void teardown() { super.teardown(); if (windowBoundedService != null) { windowBoundedService.teardown(); } }

Target:
public void teardown() { if (windowBoundedService != null) { windowBoundedService.teardown(); } super.teardown(); }
Source:
public static void putObject_test6() throws Exception { if (!mintEnv) { System.out.println("Test: objectName with path segments: " + "putObject(String bucketName, String objectName, InputStream body, " + "long size, String contentType)"); } long startTime = System.currentTimeMillis(); try { String objectName = "/path/to/" + getRandomName(); try (final InputStream is = new ContentInputStream(1 * MB)) { client.putObject(bucketName, objectName, is, 1 * MB, customContentType); } client.removeObject(bucketName, objectName); mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, long size," + " String contentType)", "size: 1 MB, contentType: " + customContentType, startTime); } catch (Exception e) { mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size," + " String contentType)", "size: 1 MB, contentType: " + customContentType, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } }

Target:
public static void putObject_test6() throws Exception { if (!mintEnv) { System.out.println("Test: objectName with path segments: " + "putObject(String bucketName, String objectName, InputStream body, " + "long size, String contentType)"); } long startTime = System.currentTimeMillis(); try { String objectName = "/path/to/" + getRandomName(); try (final InputStream is = new ContentInputStream(3 * MB)) { client.putObject(bucketName, objectName, is, 1 * MB, customContentType); } client.removeObject(bucketName, objectName); mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, long size," + " String contentType)", "size: 1 MB, contentType: " + customContentType, startTime); } catch (Exception e) { mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size," + " String contentType)", "size: 1 MB, contentType: " + customContentType, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } }
Source:
@Test public void numberToStringCoersion() throws Exception { JsonReader reader = new JsonValueReader(Arrays.asList(0, 9223372036854775807L, 2.5d, 3.010f, "a", "5")); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("0"); assertThat(reader.nextString()).isEqualTo("9223372036854775807"); assertThat(reader.nextString()).isEqualTo("2.5"); assertThat(reader.nextString()).isEqualTo("3.01"); assertThat(reader.nextString()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("5"); reader.endArray(); }

Target:
@Test public void numberToStringCoersion() throws Exception { JsonReader reader = new JsonValueReader(Arrays.asList(0, 9223372036854775807L, 2.5d, 3.01f, "a", "5")); reader.beginArray(); assertThat(reader.nextString()).isEqualTo("0"); assertThat(reader.nextString()).isEqualTo("9223372036854775807"); assertThat(reader.nextString()).isEqualTo("2.5"); assertThat(reader.nextString()).isEqualTo("3.01"); assertThat(reader.nextString()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("5"); reader.endArray(); }
Source:
private void registerToServiceProvider(String hostName) throws Exception { PqsZookeeperConf pqsZookeeperConf = new PqsZookeeperConfImpl(getConf()); registry = new ZookeeperRegistry(); String zkConnectString = pqsZookeeperConf.getZkConnectString(); registry.registerServer(pqsZookeeperConf,getPort(),zkConnectString,hostName); }

Target:
public boolean registerToServiceProvider(String hostName) { boolean success = true ; try { LoadBalanceZookeeperConf loadBalanceConfiguration = getLoadBalanceConfiguration(); Preconditions.checkNotNull(loadBalanceConfiguration); this.registry = getRegistry(); Preconditions.checkNotNull(registry); String zkConnectString = loadBalanceConfiguration.getZkConnectString(); this.registry.registerServer(loadBalanceConfiguration, getPort(), zkConnectString, hostName); } catch(Throwable ex){ LOG.error("error while trying to register ",ex); success = false; } finally { return success; } }
Source:
private List<CloudResourceStatus> deleteResources(List<CloudResource> resources, CloudContext cloudContext, boolean force, AzureClient client, PersistenceNotifier persistenceNotifier) { List<CloudResourceStatus> deletedResourcesList = new ArrayList<>(); List<CloudResource> azureGenericResources = findResources(resources, List.of(AZURE_PRIVATE_ENDPOINT)); LOGGER.debug("Deleting dns zone groups and azure private endpoints {}", azureGenericResources); azureUtils.deleteGenericResources(client, azureGenericResources.stream().map(CloudResource::getReference).collect(Collectors.toList())); azureGenericResources.forEach(cr -> persistenceNotifier.notifyDeletion(cr, cloudContext)); findResources(resources, List.of(AZURE_DATABASE)) .forEach(r -> { LOGGER.debug("Deleting postgres server {}", r.getReference()); azureUtils.deleteDatabaseServer(client, r.getReference(), force); persistenceNotifier.notifyDeletion(r, cloudContext); deletedResourcesList.add(new CloudResourceStatus(CloudResource.builder() .type(AZURE_DATABASE) .name(r.getReference()) .build(), ResourceStatus.DELETED)); }); return deletedResourcesList; }

Target:
private List<CloudResourceStatus> deleteResources(List<CloudResource> resources, CloudContext cloudContext, boolean force, AzureClient client, PersistenceNotifier persistenceNotifier) { List<CloudResource> azureGenericResources = findResources(resources, List.of(AZURE_PRIVATE_ENDPOINT)); LOGGER.debug("Deleting dns zone groups and azure private endpoints {}", azureGenericResources); azureUtils.deleteGenericResources(client, azureGenericResources.stream().map(CloudResource::getReference).collect(Collectors.toList())); azureGenericResources.forEach(cr -> persistenceNotifier.notifyDeletion(cr, cloudContext)); return findResources(resources, List.of(AZURE_DATABASE)).stream() .map(r -> deleteDatabaseServerAndNotify(r, cloudContext, client, persistenceNotifier, force)) .collect(Collectors.toList()); }
Source:
private boolean autoGroupChanged(final ISPObsComponent oldObsComp, final TargetObsComp oldTOC) { final TargetObsComp newTOC = getDataObject(); if (oldTOC == null || newTOC == null) { return false; } final SPNodeKey oldNodeKey = ImOption.apply(oldObsComp).map(ISPObsComponent::getNodeKey).getOrNull(); final SPNodeKey newNodeKey = ImOption.apply(getNode()).map(ISPObsComponent::getNodeKey).getOrNull(); if (oldNodeKey == null || newNodeKey == null) { return false; } if (!oldNodeKey.equals(newNodeKey)) { return false; } final TargetEnvironment oldEnv = oldTOC.getTargetEnvironment(); final TargetEnvironment newEnv = newTOC.getTargetEnvironment(); final Option<GuideGroup> oldGpOpt = oldEnv.getGroups().headOption().filter(GuideGroup::isAutomatic); final Option<GuideGroup> newGpOpt = newEnv.getGroups().headOption().filter(GuideGroup::isAutomatic); return oldGpOpt.forall(oldGp -> newGpOpt.forall(newGp -> { final List<String> oldNames = oldGp.getTargets().map(SPTarget::getName).toList(); final List<String> newNames = newGp.getTargets().map(SPTarget::getName).toList(); return !(oldNames.size() == newNames.size() && oldNames.containsAll(newNames)); }) ); }

Target:
private boolean autoGroupChanged(final ISPObsComponent oldObsComp, final TargetObsComp oldTOC) { final TargetObsComp newTOC = getDataObject(); if (oldTOC == null || newTOC == null) { return false; } final SPNodeKey oldNodeKey = ImOption.apply(oldObsComp).map(ISPObsComponent::getNodeKey).getOrNull(); final SPNodeKey newNodeKey = ImOption.apply(getNode()).map(ISPObsComponent::getNodeKey).getOrNull(); if (oldNodeKey == null || newNodeKey == null) { return false; } if (!oldNodeKey.equals(newNodeKey)) { return false; } final GuideGroup oldAutoGroup = oldTOC.getTargetEnvironment().getGuideEnvironment().automaticGroup(); final GuideGroup newAutoGroup = newTOC.getTargetEnvironment().getGuideEnvironment().automaticGroup(); final Map<GuideProbe,Set<Target>> oldAutoTargets = extractGroupTargets(oldAutoGroup); final Map<GuideProbe,Set<Target>> newAutoTargets = extractGroupTargets(newAutoGroup); return !oldAutoTargets.equals(newAutoTargets); }
Source:
public void testFilterOptionsForConstraintTypeLiteralWhenConstraintValueIsFormula() { when(plugin.constraintValue()).thenReturn(BaseSingleFieldConstraint.TYPE_RET_VALUE); final String[] result = page.filterOptionsForConstraintTypeLiteral(OperatorsOracle.EXPLICIT_LIST_OPERATORS); final List<String> operators = Arrays.asList(result); assertFalse(operators.contains("in")); assertFalse(operators.contains("not in")); assertEquals(0, operators.size()); }

Target:
public void testFilterOptionsForConstraintTypeLiteralWhenConstraintValueIsFormula() { when(plugin.constraintValue()).thenReturn(BaseSingleFieldConstraint.TYPE_RET_VALUE); final String[] result = page.filterOptionsForConstraintTypeLiteral(OperatorsOracle.EXPLICIT_LIST_OPERATORS); final List<String> operators = Arrays.asList(result); assertEquals(0, operators.size()); }
Source:
public void shouldReturnErrorOnHostNameWithHttpsProtocolValidation() throws OperationException { String invalidHostname = "<LINK_0>"; ((InputValidator)presenter.hostNameValidator).validate(invalidHostname).getMessage(); verify(constant).invalidHostName(); }

Target:
public void shouldReturnErrorOnHostNameWithHttpsProtocolValidation() throws OperationException { String invalidHostname = "<LINK_0>"; when(constant.invalidHostName()).thenReturn("ErrorMessage"); String errorMessage = ((InputValidator)presenter.hostNameValidator).validate(invalidHostname).getMessage(); assertEquals("ErrorMessage", errorMessage); }
Source:
private static <T extends SpecificRecord>JavaRDD<T> filterAndParseResultToAvro(JavaRDD<? extends Result> source, ResultApprover resultApprover, OafEntityToAvroConverter<Result, T> entityConverter) { return parseResultToAvro(source.filter(x -> resultApprover.approve(x)), entityConverter); }

Target:
private static <T extends SpecificRecord>JavaRDD<T> filterAndParseResultToAvro(JavaRDD<? extends Result> source, ResultApprover resultApprover, OafEntityToAvroConverter<Result, T> entityConverter) { return parseResultToAvro(source.filter(resultApprover::approve), entityConverter); }
Source:
private Boolean isImageInFilteredList(List<Image> images, String expectedImageId) { for (Image image : images) { if (expectedImageId.equals(image.getId())) { return true; } } return false; }

Target:
private boolean isImageInFilteredList(List<Image> images, String expectedImageId) { for (Image image : images) { if (expectedImageId.equals(image.getId())) { return true; } } return false; }
Source:
public static <K, V> LinkedHashMap<K, V> of(K key, V value) { final HashMap<K, V> map = HashMap.of(key, value); final Queue<Tuple2<K, V>> list = Queue.of(Tuple.of(key, value)); return list.isEmpty() ? empty() : new LinkedHashMap<>(list, map); }

Target:
public static <K, V> LinkedHashMap<K, V> of(K key, V value) { final HashMap<K, V> map = HashMap.of(key, value); final Queue<Tuple2<K, V>> list = Queue.of(Tuple.of(key, value)); return new LinkedHashMap<>(list, map); }
Source:
void addSegment(LogSegment segment, boolean increaseUsedSegmentCount) { if (increaseUsedSegmentCount) { remainingUnallocatedSegments.decrementAndGet(); } if (LogSegmentNameHelper.COMPARATOR.compare(segment.getName(), activeSegment.getName()) >= 0) { throw new IllegalArgumentException( "Cannot add segments past the current active segment. Active segment is [" + activeSegment.getName() + "]. Tried to add [" + segment.getName() + "]"); } segmentsByName.put(segment.getName(), segment); }

Target:
void addSegment(LogSegment segment, boolean increaseUsedSegmentCount) { if (increaseUsedSegmentCount && remainingUnallocatedSegments.decrementAndGet() < 0) { remainingUnallocatedSegments.incrementAndGet(); throw new IllegalArgumentException("Cannot add any more log segments that contribute to used segment count"); } if (LogSegmentNameHelper.COMPARATOR.compare(segment.getName(), activeSegment.getName()) >= 0) { throw new IllegalArgumentException( "Cannot add segments past the current active segment. Active segment is [" + activeSegment.getName() + "]. Tried to add [" + segment.getName() + "]"); } segmentsByName.put(segment.getName(), segment); }
Source:
private boolean isEntityModelEmpty(EntityModel model) { return !(model.getEntity() != null && !model.getEntity().equals("")); }

Target:
private boolean isEntityModelEmpty(EntityModel model) { return !(!"".equals(model.getEntity())); }
Source:
private void subscribeChildChange(String path, NotificationContext.Type callbackType) { if (callbackType == NotificationContext.Type.INIT || callbackType == NotificationContext.Type.CALLBACK) { if (logger.isDebugEnabled()) { logger.debug(_manager.getInstanceName() + " subscribes child-change. path: " + path + ", listener: " + _listener); } if (callbackType == Type.INIT) { _zkClient.subscribeChildChanges(path, this); } else { _zkClient.subscribeChildChanges(path, this, true); } } else if (callbackType == NotificationContext.Type.FINALIZE) { logger.info(_manager.getInstanceName() + " unsubscribe child-change. path: " + path + ", listener: " + _listener); _zkClient.unsubscribeChildChanges(path, this); } }

Target:
private void subscribeChildChange(String path, NotificationContext.Type callbackType) { if (callbackType == NotificationContext.Type.INIT || callbackType == NotificationContext.Type.CALLBACK) { if (logger.isDebugEnabled()) { logger.debug(_manager.getInstanceName() + " subscribes child-change. path: " + path + ", listener: " + _listener); } ChildrenSubscribeResult childrenSubscribeResult = _zkClient.subscribeChildChanges(path, this, callbackType != Type.INIT); logger.debug("CallbackHandler subscribe data path result {}", this, path, childrenSubscribeResult.isInstalled()); if (!childrenSubscribeResult.isInstalled()) { logger.info("CallbackHandler subscribe data path failed!", this, path); } } else if (callbackType == NotificationContext.Type.FINALIZE) { logger.info(_manager.getInstanceName() + " unsubscribe child-change. path: " + path + ", listener: " + _listener); _zkClient.unsubscribeChildChanges(path, this); } }
Source:
public int moveOperations(final MemcachedNode toNode) { BlockingQueue<Operation> allOp = getAllOperations(); int opCount = allOp.size(); if (opCount > 0) { toNode.addAllOpToInputQ(allOp); getLogger().info("Total %d operations have been moved to %s", allOp.size(), toNode); } return opCount; }

Target:
public int moveOperations(final MemcachedNode toNode) { BlockingQueue<Operation> allOp = getAllOperations(); int opCount = allOp.size(); if (opCount > 0) { toNode.addAllOpToInputQ(allOp); getLogger().info("Total %d operations have been moved to %s", opCount, toNode); } return opCount; }
Source:
public void init() { if (productInfo == null) { GWTServiceLookup.getSystemService().getProductInfo(new AsyncCallback<ProductInfo>() { @Override public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError(MSG.view_aboutBox_failedToLoad(), caught); buildCoreUI(); } @Override public void onSuccess(ProductInfo result) { productInfo = result; isRHQ = (productInfo != null) && "RHQ".equals(productInfo.getShortName()); Window.setTitle(productInfo.getName()); buildCoreUI(); } }); } else { buildCoreUI(); } }

Target:
public void init() { if (productInfo == null) { GWTServiceLookup.getSystemService().getProductInfo(new AsyncCallback<ProductInfo>() { @Override public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError(MSG.view_aboutBox_failedToLoad(), caught); buildCoreUI(); } @Override public void onSuccess(ProductInfo result) { productInfo = result; rhq = (productInfo != null) && "RHQ".equals(productInfo.getShortName()); Window.setTitle(productInfo.getName()); buildCoreUI(); } }); } else { buildCoreUI(); } }
Source:
public void testIndexRowWithoutEmptyColumn() throws Exception { if (async) { return; } long scn; String dataTableName = generateUniqueName(); String indexTableName = generateUniqueName(); try (Connection conn = DriverManager.getConnection(getUrl())) { populateTable(dataTableName); Thread.sleep(1000); conn.createStatement().execute("CREATE INDEX " + indexTableName + " on " + dataTableName + " (val1) include (val2, val3)"); scn = EnvironmentEdgeManager.currentTimeMillis(); IndexRegionObserver.setFailDataTableUpdatesForTesting(true); conn.createStatement().execute("upsert into " + dataTableName + " values ('a', 'abc','abcc', 'abccd')"); commitWithException(conn); IndexRegionObserver.setFailDataTableUpdatesForTesting(false); TestUtil.doMajorCompaction(conn, indexTableName); } Properties props = new Properties(); props.setProperty("CurrentSCN", Long.toString(scn)); try (Connection connWithSCN = DriverManager.getConnection(getUrl(), props)) { String selectSql = "SELECT * from " + dataTableName + " WHERE val1 = 'ab'"; assertExplainPlan(connWithSCN, selectSql, dataTableName, indexTableName); ResultSet rs = connWithSCN.createStatement().executeQuery(selectSql); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals("ab", rs.getString(2)); assertEquals("abc", rs.getString(3)); assertEquals("abcd", rs.getString(4)); assertFalse(rs.next()); } }

Target:
public void testIndexRowWithoutEmptyColumn() throws Exception { if (async) { return; } long scn; String dataTableName = generateUniqueName(); String indexTableName = generateUniqueName(); try (Connection conn = DriverManager.getConnection(getUrl())) { populateTable(dataTableName); conn.createStatement().execute("CREATE INDEX " + indexTableName + " on " + dataTableName + " (val1) include (val2, val3)"); scn = EnvironmentEdgeManager.currentTimeMillis(); IndexRegionObserver.setFailDataTableUpdatesForTesting(true); conn.createStatement().execute("upsert into " + dataTableName + " values ('a', 'abc','abcc', 'abccd')"); commitWithException(conn); IndexRegionObserver.setFailDataTableUpdatesForTesting(false); TestUtil.doMajorCompaction(conn, indexTableName); } Properties props = new Properties(); props.setProperty("CurrentSCN", Long.toString(scn)); try (Connection connWithSCN = DriverManager.getConnection(getUrl(), props)) { String selectSql = "SELECT * from " + dataTableName + " WHERE val1 = 'ab'"; assertExplainPlan(connWithSCN, selectSql, dataTableName, indexTableName); ResultSet rs = connWithSCN.createStatement().executeQuery(selectSql); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals("ab", rs.getString(2)); assertEquals("abc", rs.getString(3)); assertEquals("abcd", rs.getString(4)); assertFalse(rs.next()); } }
Source:
protected boolean canDoAction() { boolean returnValue = canRemoveVds(getVdsId(), getReturnValue().getCanDoActionMessages()); StoragePool storagePool = getStoragePoolDAO().getForVds(getParameters().getVdsId()); if (returnValue && storagePool != null && storagePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!getStorageDomainDAO().getAllForStoragePool(storagePool.getId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_WITH_LOCAL_STORAGE); returnValue = false; } } if (returnValue && isGlusterEnabled()) { upServer = getClusterUtils().getUpServer(getVdsGroupId()); if (!getParameters().isForceAction()) { if (hasVolumeBricksOnServer()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); returnValue = false; } else if (upServer == null && clusterHasMultipleHosts()) { addCanDoActionMessage(String.format("$clusterName %1$s", getVdsGroup().getname())); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_UP_SERVER_FOUND); returnValue = false; } } else { if (hasVolumeBricksOnServer() && upServer != null ) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); returnValue = false; } } } return returnValue; }

Target:
protected boolean canDoAction() { boolean returnValue = canRemoveVds(getVdsId(), getReturnValue().getCanDoActionMessages()); StoragePool storagePool = getStoragePoolDAO().getForVds(getParameters().getVdsId()); if (returnValue && storagePool != null && storagePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!getStorageDomainDAO().getAllForStoragePool(storagePool.getId()).isEmpty()) { returnValue = failCanDoAction(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_WITH_LOCAL_STORAGE); } } if (returnValue && isGlusterEnabled()) { upServer = getClusterUtils().getUpServer(getVdsGroupId()); if (!getParameters().isForceAction()) { if (hasVolumeBricksOnServer()) { returnValue = failCanDoAction(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); } else if (upServer == null && clusterHasMultipleHosts()) { addCanDoActionMessage(String.format("$clusterName %1$s", getVdsGroup().getname())); returnValue = failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_UP_SERVER_FOUND); } } else { if (hasVolumeBricksOnServer() && upServer != null ) { returnValue = failCanDoAction(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); } } } return returnValue; }
Source:
protected void writeTestFileName(String name, boolean append) throws FileNotFoundException { File outFileName = new File(m_testNamesFile); if ( ! outFileName.exists() ) { append = false; } PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFileName, append))); ps.print(name); ps.close(); }

Target:
protected void writeTestFileName(String name, boolean append) throws FileNotFoundException { File outFileName = new File(m_testNamesFile); if ( ! outFileName.exists() ) { append = false; } try (PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFileName, append)))) { ps.print(name); } }
Source:
public void close() { if (accumulator == null) { accumulator = new SerializedListAccumulator<>(); } getRuntimeContext().addAccumulator(id, accumulator); }

Target:
public void close() { if (accumulator != null) { getRuntimeContext().addAccumulator(id, accumulator); } }
Source:
protected Object serializableProxy() { boolean allowLoadOutsideTransaction = isAllowLoadOutsideTransactionForSerialization(); return new SerializableProxy( getEntityName(), persistentClass, interfaces, getIdentifier(), ( isReadOnlySettingAvailable() ? Boolean.valueOf( isReadOnly() ) : isReadOnlyBeforeAttachedToSession() ), getSessionFactoryUuidForSerialization( allowLoadOutsideTransaction ), allowLoadOutsideTransaction, getIdentifierMethod, setIdentifierMethod, componentIdType ); }

Target:
protected Object serializableProxy() { return new SerializableProxy( getEntityName(), persistentClass, interfaces, getIdentifier(), ( isReadOnlySettingAvailable() ? Boolean.valueOf( isReadOnly() ) : isReadOnlyBeforeAttachedToSession() ), getSessionFactoryUuid(), isAllowLoadOutsideTransaction(), getIdentifierMethod, setIdentifierMethod, componentIdType ); }
Source:
public void initialize() { initializeGameTable(gameService.getGames().filtered(game -> game.getStatus() == GameStatus.PLAYING)); }

Target:
public void initialize() { initializeGameTable(gameService.getGames()); }
Source:
public void manageAirVectors() { for (int i = 0; i < this.tasks.size(); i++) { if (((FireComboStream) this.tasks.get(i)).isCancelled()) { this.tasks.remove(i); i--; } } if (this.tasks.size() == 0) { this.remove(); return; } for (int i = 0; i < this.tasks.size(); i++) { final FireComboStream fstream = (FireComboStream) this.tasks.get(i); final Location loc = fstream.getLocation(); if (GeneralMethods.isRegionProtectedFromBuild(this, loc)) { fstream.remove(); return; } if (!this.isTransparent(loc.getBlock())) { if (!this.isTransparent(loc.clone().add(0, 0.2, 0).getBlock())) { fstream.remove(); return; } } if (i % 3 == 0) { for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(loc, 2.5)) { if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { this.remove(); return; } if (!entity.equals(this.player) && !(entity instanceof Player && Commands.invincible.contains(((Player) entity).getName()))) { if (this.knockback != 0) { final Vector force = fstream.getLocation().getDirection(); GeneralMethods.setVelocity(entity, force.clone().multiply(this.knockback)); new HorizontalVelocityTracker(entity, this.player, 200l, this); entity.setFallDistance(0); } if(!this.affectedEntities.contains(entity)) { this.affectedEntities.add(entity); if (this.damage != 0) { if (entity instanceof LivingEntity) { if (fstream.getAbility().getName().equalsIgnoreCase("AirSweep")) { DamageHandler.damageEntity(entity, this.damage, this); } else { DamageHandler.damageEntity(entity, this.damage, this); } } } } } } } } }

Target:
public void manageAirVectors() { for (int i = 0; i < this.tasks.size(); i++) { if (((FireComboStream) this.tasks.get(i)).isCancelled()) { this.tasks.remove(i); i--; } } if (this.tasks.size() == 0) { this.remove(); return; } for (int i = 0; i < this.tasks.size(); i++) { final FireComboStream fstream = (FireComboStream) this.tasks.get(i); final Location loc = fstream.getLocation(); if (GeneralMethods.isRegionProtectedFromBuild(this, loc)) { fstream.remove(); return; } if (!this.isTransparent(loc.getBlock())) { if (!this.isTransparent(loc.clone().add(0, 0.2, 0).getBlock())) { fstream.remove(); return; } } if (i % 3 == 0) { for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(loc, 2.5)) { if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { this.remove(); return; } if (!entity.equals(this.player) && !(entity instanceof Player && Commands.invincible.contains(((Player) entity).getName()))) { if (this.knockback != 0) { final Vector force = fstream.getLocation().getDirection(); GeneralMethods.setVelocity(entity, force.clone().multiply(this.knockback)); new HorizontalVelocityTracker(entity, this.player, 200l, this); entity.setFallDistance(0); } if(!this.affectedEntities.contains(entity)) { this.affectedEntities.add(entity); if (this.damage != 0) { if (entity instanceof LivingEntity) { DamageHandler.damageEntity(entity, this.damage, this); } } } } } } } }
Source:
protected void doHandle(CommandContext ctx) { ctx.terminateSession(); System.exit(0); }

Target:
protected void doHandle(CommandContext ctx) { ctx.terminateSession(); }
Source:
public void save(OpenWorkpiece openWorkpiece) throws IOException { URI uri = openWorkpiece.getUri(); try (OutputStream out = ServiceManager.getFileService().write(uri, openWorkpiece.getLockResult())) { logger.info("Saving {}", uri.toString()); metsXmlElementAccess.save(openWorkpiece.getWorkpiece(), out); } }

Target:
public void save(OpenWorkpiece openWorkpiece) throws IOException { URI uri = openWorkpiece.getUri(); try (OutputStream out = ServiceManager.getFileService().write(uri, openWorkpiece.getLockResult())) { logger.info("Saving {}", uri.toString()); write(openWorkpiece.getWorkpiece(), out); } }
Source:
public int getBucket(Page page, int position) { long hash = 0; for (int i = 0; i < page.getChannelCount(); i++) { Block block = page.getBlock(i); long value = functions[i].hash(block, position); hash = (hash * 31) + value; } return positiveInt(hash) % bucketCount; }

Target:
public int getBucket(Page page, int position) { long hash = 0; for (int i = 0; i < page.getChannelCount(); i++) { Block block = page.getBlock(i); long value = functions[i].hash(block, position); hash = (hash * 31) + value; } return computeBucket(hash, bucketCount); }
Source:
public void executeTask( @NotNull final Map<String, Object> context ) throws GenieException { log.debug("Executing Command Task in the workflow."); super.executeTask(context); createEntityInstanceDirectory( this.jobExecEnv.getCommand().getId(), AdminResources.COMMAND ); createEntityInstanceConfigDirectory( this.jobExecEnv.getCommand().getId(), AdminResources.COMMAND ); createEntityInstanceDependenciesDirectory( this.jobExecEnv.getCommand().getId(), AdminResources.COMMAND ); final String commandSetupFile = jobExecEnv.getCommand().getSetupFile(); if (commandSetupFile != null && StringUtils.isNotBlank(commandSetupFile)) { final String localPath = super.buildLocalFilePath( this.jobWorkingDirectory, jobExecEnv.getCommand().getId(), commandSetupFile, FileType.SETUP, AdminResources.COMMAND ); this.fts.getFile(commandSetupFile, localPath); Utils.appendToWriter(writer, "# Sourcing setup file from command " + jobExecEnv.getCommand().getId()); Utils.appendToWriter(writer, JobConstants.SOURCE + localPath.replace(this.jobWorkingDirectory, "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}") + JobConstants.SEMICOLON_SYMBOL); Utils.appendToWriter(writer, " "); } for (final String configFile: jobExecEnv.getCommand().getConfigs()) { final String localPath = super.buildLocalFilePath( this.jobWorkingDirectory, jobExecEnv.getCommand().getId(), configFile, FileType.CONFIG, AdminResources.COMMAND ); this.fts.getFile(configFile, localPath); } }

Target:
public void executeTask( @NotNull final Map<String, Object> context ) throws GenieException, IOException { log.debug("Executing Command Task in the workflow."); super.executeTask(context); createEntityInstanceDirectory( this.jobExecEnv.getCommand().getId(), AdminResources.COMMAND ); createEntityInstanceConfigDirectory( this.jobExecEnv.getCommand().getId(), AdminResources.COMMAND ); createEntityInstanceDependenciesDirectory( this.jobExecEnv.getCommand().getId(), AdminResources.COMMAND ); final String commandSetupFile = jobExecEnv.getCommand().getSetupFile(); if (commandSetupFile != null && StringUtils.isNotBlank(commandSetupFile)) { final String localPath = super.buildLocalFilePath( this.jobWorkingDirectory, jobExecEnv.getCommand().getId(), commandSetupFile, FileType.SETUP, AdminResources.COMMAND ); this.fts.getFile(commandSetupFile, localPath); super.generateSetupFileSourceSnippet( jobExecEnv.getCommand().getId(), "Command:", localPath); } for (final String configFile: jobExecEnv.getCommand().getConfigs()) { final String localPath = super.buildLocalFilePath( this.jobWorkingDirectory, jobExecEnv.getCommand().getId(), configFile, FileType.CONFIG, AdminResources.COMMAND ); this.fts.getFile(configFile, localPath); } }
Source:
private boolean preUndeleteValidation(CloudBlobMetadata metadata, StoreKey key, Map<String, Object> updateFields) throws StoreException { validateAccountAndContainer(Collections.singletonMap(key.getID(), metadata), Collections.singletonList(key)); short requestedLifeVersion = (short) updateFields.get(FIELD_LIFE_VERSION); if (isVcr) { return metadata.getLifeVersion() < requestedLifeVersion; } if (metadata.isExpired()) { throw new StoreException("Id " + key + " already expired in cloud ", StoreErrorCodes.TTL_Expired); } else if (metadata.isUndeleted()) { throw new StoreException("Id " + key + " is already undeleted in cloud", StoreErrorCodes.ID_Undeleted); } else if (!metadata.isDeleted()) { throw new StoreException("Id " + key + " is not deleted yet in cloud ", StoreErrorCodes.ID_Not_Deleted); } else if (metadata.getDeletionTime() + TimeUnit.DAYS.toMillis(storeConfig.storeDeletedMessageRetentionHours) < System.currentTimeMillis()) { throw new StoreException("Id " + key + " already permanently deleted in cloud ", StoreErrorCodes.ID_Deleted_Permanently); } updateFields.put(FIELD_LIFE_VERSION, metadata.getLifeVersion() + 1); return true; }

Target:
private boolean preUndeleteValidation(CloudBlobMetadata metadata, StoreKey key, Map<String, Object> updateFields) throws StoreException { validateAccountAndContainer(Collections.singletonMap(key.getID(), metadata), Collections.singletonList(key)); short requestedLifeVersion = (short) updateFields.get(FIELD_LIFE_VERSION); if (isVcr) { return metadata.getLifeVersion() < requestedLifeVersion; } if (metadata.isExpired()) { throw new StoreException("Id " + key + " already expired in cloud ", StoreErrorCodes.TTL_Expired); } else if (metadata.isUndeleted()) { throw new StoreException("Id " + key + " is already undeleted in cloud", StoreErrorCodes.ID_Undeleted); } else if (!metadata.isDeleted()) { throw new StoreException("Id " + key + " is not deleted yet in cloud ", StoreErrorCodes.ID_Not_Deleted); } else if (metadata.getDeletionTime() + TimeUnit.HOURS.toMillis(storeConfig.storeDeletedMessageRetentionHours) < System.currentTimeMillis()) { throw new StoreException("Id " + key + " already permanently deleted in cloud ", StoreErrorCodes.ID_Deleted_Permanently); } updateFields.put(FIELD_LIFE_VERSION, metadata.getLifeVersion() + 1); return true; }
Source:
private XSDTypeDefinition searchType(SchemaIndex schemaIndex, String... typesNames) { for (String typeName : typesNames) { XSDTypeDefinition type = schemaIndex.getTypeDefinition(gml.qName(typeName)); if (type != null) { return type; } } LOGGER.warning(String.format("No type definition found for types [%s].", Arrays.stream(typesNames).collect(Collectors.joining(", ")))); return null; }

Target:
private XSDTypeDefinition searchType(SchemaIndex schemaIndex, String... typesNames) { for (String typeName : typesNames) { XSDTypeDefinition type = schemaIndex.getTypeDefinition(gml.qName(typeName)); if (type != null) { return type; } } LOGGER.fine(String.format("No type definition found for types [%s].", Arrays.stream(typesNames).collect(Collectors.joining(", ")))); return null; }
Source:
public D withSideInputs(List<String> sideInputs) { this.sideInputs = sideInputs; this.enableChangelog = false; this.changelogStream = null; return (D) this; }

Target:
public D withSideInputs(List<String> sideInputs) { this.sideInputs = sideInputs; this.enableChangelog = false; this.changelogStream = null; this.changelogReplicationFactor = null; return (D) this; }
Source:
private void handleException(Throwable e) { log.error(String.format("Failed to import certificate: %1$s", e.getMessage())); log.debug("Exception", e); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__PROVIDER_CERTIFICATE); }

Target:
private void handleException(Throwable e) { log.error(String.format("Failed to import certificate: %1$s", e.getMessage())); log.debug("Exception", e); throw new VdcBLLException(VdcBllErrors.PROVIDER_IMPORT_CERTIFICATE_ERROR, e.getMessage()); }
Source:
public static Value decode( long[] valueBlocks, int offset ) { long firstBlock = valueBlocks[offset]; int gtype = getGeometryType( firstBlock ); int dimension = getDimension( firstBlock ); if ( isFloatPrecision( firstBlock ) ) { throw new UnsupportedOperationException( "Float precision is unsupported in Geometry properties" ); } if ( dimension > 3 ) { throw new UnsupportedOperationException( "Points with more than 3 dimensions are not supported in the PropertyStore" ); } CoordinateReferenceSystem crs = CoordinateReferenceSystem.get( getCRSTable( firstBlock ), getCRSCode( firstBlock ) ); return find( gtype ).decode( crs, dimension, valueBlocks, offset ); }

Target:
public static Value decode( long[] valueBlocks, int offset ) { long firstBlock = valueBlocks[offset]; int gtype = getGeometryType( firstBlock ); int dimension = getDimension( firstBlock ); if ( isFloatPrecision( firstBlock ) ) { throw new UnsupportedOperationException( "Float precision is unsupported in Geometry properties" ); } if ( dimension > GeometryType.getMaxSupportedDimensions() ) { throw new UnsupportedOperationException( "Points with more than " + GeometryType.getMaxSupportedDimensions() + " dimensions are not supported" ); } CoordinateReferenceSystem crs = CoordinateReferenceSystem.get( getCRSTable( firstBlock ), getCRSCode( firstBlock ) ); return find( gtype ).decode( crs, dimension, valueBlocks, offset ); }
Source:
public HdfsToTeradataJob(String jobid, Props sysProps, Props jobProps, Logger log) throws RuntimeException { super(jobid, sysProps, jobProps, log); jobProps.put(TdchConstants.LIB_JARS_KEY, sysProps.get(TdchConstants.LIB_JARS_KEY)); TeraDataWalletInitializer.initialize(new File(getCwd()), new File(sysProps.get(TdchConstants.TD_WALLET_JAR))); }

Target:
public HdfsToTeradataJob(String jobid, Props sysProps, Props jobProps, Logger log) throws RuntimeException { super(jobid, sysProps, jobProps, log); jobProps.put(TdchConstants.LIB_JARS_KEY, sysProps.get(TdchConstants.LIB_JARS_KEY)); File tempDir = new File(sysProps.getString("azkaban.temp.dir", "temp")); TeraDataWalletInitializer.initialize(tempDir, new File(sysProps.get(TdchConstants.TD_WALLET_JAR))); }
Source:
public boolean containsResource() { return this.hasResource; }

Target:
public boolean containsResource() { return false; }
Source:
public Mono<ConfigurationSetting> deleteSetting(String key, String label) { return withContext( context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context)) .map(response -> response.getValue()); }

Target:
public Mono<ConfigurationSetting> deleteSetting(String key, String label) { return withContext( context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); }
Source:
public void testRequestTokenRenew() { Map<String, String> userDTO = new HashMap<>(); userDTO.put("username", user.getUsername()); userDTO.put("password", userCleartextPassword); given(). when(). content(userDTO).contentType(ContentType.JSON). post("/token"). then(). statusCode(HttpStatus.SC_OK); Optional<AuthenticationToken> authenticationToken = authenticationTokenRepository.findByUserUsername(user.getUsername()); Assert.assertTrue(authenticationToken.isPresent()); }

Target:
public void testRequestTokenRenew() { Map<String, String> userDTO = new HashMap<>(); userDTO.put("username", user.getUsername()); userDTO.put("password", userCleartextPassword); given(). when(). content(userDTO).contentType(ContentType.JSON). post("/token"). then(). statusCode(HttpStatus.SC_OK); AuthenticationToken authenticationToken1 = authenticationTokenRepository.findByUserUsername(user.getUsername()).orElse(null); given(). when(). content(userDTO).contentType(ContentType.JSON). post("/token"). then(). statusCode(HttpStatus.SC_OK); AuthenticationToken authenticationToken2 = authenticationTokenRepository.findByUserUsername(user.getUsername()).orElse(null); Assert.assertFalse(authenticationToken1.equals(authenticationToken2)); }
Source:
public synchronized void onEvent(TransactionEvent transactionEvent) { if (transactionEvent.getTypes().contains(EventType.ASSOCIATED)) { transactionDisassociatedFromApplication = false; } else if(transactionEvent.getTypes().contains(EventType.DISASSOCIATING)) { transactionDisassociatedFromApplication = true; } safeCloseEntityManager(); }

Target:
public synchronized void onEvent(TransactionEvent transactionEvent) { transactionDisassociatedFromApplication = transactionEvent.getTypes().contains(EventType.DISASSOCIATING); safeCloseEntityManager(); }
Source:
private String convertFipsUsStateNameToFipsUsStateCode(String fipsStateName) { Map<String, Object> fieldValues = new HashMap(); fieldValues.put("active", true); fieldValues.put("countryCode", KFSConstants.COUNTRY_CODE_UNITED_STATES); Collection<State> allStatesForUsFipsCountryCode = businessObjectService.findMatching(State.class, fieldValues); List<State> matchingStates = allStatesForUsFipsCountryCode.stream() .filter(stateItem -> stateItem.getName().equalsIgnoreCase(fipsStateName)) .filter(stateItem -> stateItem.isActive()) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); LOG.info("convertFipsUsStateNameToFipsUsStateCode: matchingStates = " + matchingStates.toString()); if (matchingStates.size() == 1) { LOG.info("convertFipsUsStateNameToFipsUsStateCode: stateCode being returned = " + matchingStates.get(0).getCode()); return matchingStates.get(0).getCode(); } else { LOG.info("convertFipsUsStateNameToFipsUsStateCode: fipsStateName being returned, could not find stateCode in Rice table = " + fipsStateName); return fipsStateName; } }

Target:
private String convertFipsUsStateNameToFipsUsStateCode(String fipsStateName) { Map<String, Object> fieldValues = new HashMap<>(); fieldValues.put("active", true); fieldValues.put("countryCode", KFSConstants.COUNTRY_CODE_UNITED_STATES); Collection<State> allStatesForUsFipsCountryCode = businessObjectService.findMatching(State.class, fieldValues); List<State> matchingStates = allStatesForUsFipsCountryCode.stream() .filter(stateItem -> stateItem.getName().equalsIgnoreCase(fipsStateName)) .filter(stateItem -> stateItem.isActive()) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); LOG.info("convertFipsUsStateNameToFipsUsStateCode: matchingStates = " + matchingStates.toString()); if (matchingStates.size() == 1) { LOG.info("convertFipsUsStateNameToFipsUsStateCode: stateCode being returned = " + matchingStates.get(0).getCode()); return matchingStates.get(0).getCode(); } else { LOG.info("convertFipsUsStateNameToFipsUsStateCode: fipsStateName being returned, could not find stateCode = " + fipsStateName); return fipsStateName; } }