auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCleanStateAfterInit() throws NoWorkTreeException, GitAPIException { Git parentGit = Git.wrap(parentRepository.getRepository()); Status status = parentGit .status() .setWorkingTreeIt( new AdaptableFileTreeIterator(parentRepository .getRepository(), parentFile.getWorkspace() .getRoot())).call(); assertTrue(status.isClean()); }

Target:
public void testCleanStateAfterInit() throws NoWorkTreeException, GitAPIException { Git parentGit = Git.wrap(parentRepository.getRepository()); Status status = parentGit.status().setWorkingTreeIt(treeIt).call(); assertTrue(status.isClean()); }
Source:
public void testListDeployment() throws Exception { final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup); server.enqueue(jsonResponse("/listdeployments.json")); List<Deployment> deployments = deploymentApi.list(); assertTrue(deployments.size() > 0); }

Target:
public void testListDeployment() throws Exception { final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup); server.enqueue(jsonResponse("/listdeployments.json")); List<Deployment> deployments = deploymentApi.list(); assertTrue(deployments.size() > 0); assertSent(server, "GET", "/subscriptions/" + subscriptionId + "/resourcegroups/" + resourceGroup + "/providers/microsoft.resources/deployments?api-version=2016-02-01"); }
Source:
protected String readFile(String fileLocation) throws APIManagerIntegrationTestException { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(fileLocation))); String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } catch (IOException ioE) { throw new APIManagerIntegrationTestException("IOException when reading the file from:" + fileLocation, ioE); } }

Target:
protected String readFile(String fileLocation) throws APIManagerIntegrationTestException { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(new File(fileLocation))); String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } catch (IOException ioE) { throw new APIManagerIntegrationTestException("IOException when reading the file from:" + fileLocation, ioE); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { log.warn("Error when closing the buffer reade which used to reed the file:" + fileLocation + ". Error:" + e.getMessage()); } } } }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.homeAsUp: return true; case R.id.menu_page_save: app.getFunnelManager().getSavedPagesFunnel(model.getTitle().getSite()).logSaveNew(); if (model.getCurEntry().getSource() == HistoryEntry.SOURCE_SAVED_PAGE) { refreshPage(true); } else { savePage(); } return true; case R.id.menu_page_share: contextMenuListener.onShareLink(model.getTitle()); return true; case R.id.menu_page_other_languages: Intent langIntent = new Intent(); langIntent.setClass(getActivity(), LangLinksActivity.class); langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE); langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle()); getActivity().startActivityForResult(langIntent, PageActivity.ACTIVITY_REQUEST_LANGLINKS); return true; case R.id.menu_page_find_in_page: showFindInPage(); return true; case R.id.menu_page_font_and_theme: getPageActivity().showThemeChooser(); return true; case R.id.menu_page_show_tabs: tabsProvider.enterTabMode(); return true; default: return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.homeAsUp: return true; case R.id.menu_page_save: app.getFunnelManager().getSavedPagesFunnel(model.getTitle().getSite()).logSaveNew(); if (model.getCurEntry().getSource() == HistoryEntry.SOURCE_SAVED_PAGE) { refreshPage(true); } else { savePage(); } return true; case R.id.menu_page_share: ShareUtils.shareText(getActivity(), model.getTitle()); return true; case R.id.menu_page_other_languages: Intent langIntent = new Intent(); langIntent.setClass(getActivity(), LangLinksActivity.class); langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE); langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle()); getActivity().startActivityForResult(langIntent, PageActivity.ACTIVITY_REQUEST_LANGLINKS); return true; case R.id.menu_page_find_in_page: showFindInPage(); return true; case R.id.menu_page_font_and_theme: getPageActivity().showThemeChooser(); return true; case R.id.menu_page_show_tabs: tabsProvider.enterTabMode(); return true; default: return super.onOptionsItemSelected(item); } }
Source:
void shutdown() throws InterruptedException { LOG.info("Synchronous shutdown requested"); if (!statusRef.compareAndSet(RUNNING, PREPARING_TO_SHUTDOWN)) { shutdownLatch.await(); } else { doStopServices(); } }

Target:
void shutdown() throws InterruptedException { LOG.debug("Synchronous shutdown requested"); if (!statusRef.compareAndSet(RUNNING, PREPARING_TO_SHUTDOWN)) { shutdownLatch.await(); } else { doStopServices(); } }
Source:
public Integer getDownloadingVideosCountForSection(String enrollmentId, String chapter, String section, final DataCallback<Integer> callback) { DbOperationGetCount op = new DbOperationGetCount(false, DbStructure.Table.DOWNLOADS, new String[]{DbStructure.Column.DM_ID}, DbStructure.Column.DOWNLOADED + "=? AND " + DbStructure.Column.EID + "=? AND " + DbStructure.Column.CHAPTER + "=? AND " + DbStructure.Column.SECTION + "=? AND " + DbStructure.Column.USERNAME + "=?", new String[]{String.valueOf(DownloadedState.DOWNLOADING.ordinal()), enrollmentId, chapter, section, username()}, null); op.setCallback(callback); return enqueue(op); }

Target:
public int getDownloadingVideosCountForSection(String enrollmentId, String chapter, String section, final DataCallback<Integer> callback) { DbOperationGetCount op = new DbOperationGetCount(false, DbStructure.Table.DOWNLOADS, new String[]{DbStructure.Column.DM_ID}, DbStructure.Column.DOWNLOADED + "=? AND " + DbStructure.Column.EID + "=? AND " + DbStructure.Column.CHAPTER + "=? AND " + DbStructure.Column.SECTION + "=? AND " + DbStructure.Column.USERNAME + "=?", new String[]{String.valueOf(DownloadedState.DOWNLOADING.ordinal()), enrollmentId, chapter, section, username()}, null); op.setCallback(callback); return enqueue(op); }
Source:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); releaseYoutubePlayer(); addOrRemoveYoutubePlayerFragment(VideoUtil.isAPIYoutubeSupported(getContext())); attempts = 0; }

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); releaseYoutubePlayer(); if (VideoUtil.isYoutubeAPISupported(getContext())) { youTubePlayerFragment = new YouTubePlayerSupportFragment(); getChildFragmentManager().beginTransaction().replace(R.id.player_container, youTubePlayerFragment, "player").commit(); } attempts = 0; }
Source:
void setUp() { bibtex = new BibDatabaseContext(); bibtex.setMode(BibDatabaseMode.BIBTEX); biblatex = new BibDatabaseContext(); biblatex.setMode(BibDatabaseMode.BIBLATEX); checker = new EditionChecker(bibtex, true); checkerb = new EditionChecker(biblatex, true); entry = new BibEntry(); }

Target:
void setUp() { bibtex = new BibDatabaseContext(); bibtex.setMode(BibDatabaseMode.BIBTEX); biblatex = new BibDatabaseContext(); biblatex.setMode(BibDatabaseMode.BIBLATEX); checker = new EditionChecker(bibtex, true); checkerb = new EditionChecker(biblatex, true); }
Source:
public boolean requiresWorkspaceForPolling() { final AccurevMode accurevMode = AccurevMode.findMode(this); final boolean needSlaveForPolling = !DESCRIPTOR.isPollOnMaster() || accurevMode.isRequiresWorkspace(); if(!needSlaveForPolling) { return needSlaveForPolling; } skipNextPoll = false; if (AccuRevSCMPollListener.getLastProject() != null) { AbstractProject<?, ?> project = AccuRevSCMPollListener.getLastProject(); AccuRevSCMPollListener.clearLastProject(); if(project.isBuilding()) { skipNextPoll = true; return false; } } return needSlaveForPolling; }

Target:
public boolean requiresWorkspaceForPolling() { if (!DESCRIPTOR.isPollOnMaster() || (AccurevMode.findMode(this).isRequiresWorkspace()) || (activeProject != null && activeProject.isBuilding())) { return false; } activeProject = null; return true; }
Source:
public void findAllSortedAsync_listOnSubObjectField() { Realm realm = looperThread.realm; String[] fieldNames = new String[2]; fieldNames[0] = AllTypes.FIELD_REALMOBJECT + "." + Dog.FIELD_AGE; fieldNames[1] = AllTypes.FIELD_REALMOBJECT + "." + Dog.FIELD_AGE; Sort[] sorts = new Sort[2]; sorts[0] = Sort.ASCENDING; sorts[1] = Sort.ASCENDING; populateTestRealm(realm, TEST_DATA_SIZE); RealmResults<AllTypes> results = realm.where(AllTypes.class) .findAllSorted(fieldNames, sorts); looperThread.keepStrongReference.add(results); results.addChangeListener(new RealmChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> results) { assertEquals(0, results.get(0).getColumnRealmObject().getAge()); assertEquals(TEST_DATA_SIZE - 1, results.get(TEST_DATA_SIZE - 1).getColumnRealmObject().getAge()); looperThread.testComplete(); } }); }

Target:
public void findAllSortedAsync_listOnSubObjectField() { Realm realm = looperThread.realm; String[] fieldNames = new String[2]; fieldNames[0] = AllTypes.FIELD_REALMOBJECT + "." + Dog.FIELD_AGE; fieldNames[1] = AllTypes.FIELD_REALMOBJECT + "." + Dog.FIELD_AGE; Sort[] sorts = new Sort[2]; sorts[0] = Sort.ASCENDING; sorts[1] = Sort.ASCENDING; populateTestRealm(realm, TEST_DATA_SIZE); RealmResults<AllTypes> results = realm.where(AllTypes.class) .findAllSortedAsync(fieldNames, sorts); looperThread.keepStrongReference.add(results); results.addChangeListener(new RealmChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> results) { assertEquals(0, results.get(0).getColumnRealmObject().getAge()); assertEquals(TEST_DATA_SIZE - 1, results.get(TEST_DATA_SIZE - 1).getColumnRealmObject().getAge()); looperThread.testComplete(); } }); }
Source:
protected void initContainersTable() { containersTable = new EntityModelCellTable<>(false, true); AbstractTextColumn<GuestContainer> idColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getId().toString(); } }; AbstractTextColumn<GuestContainer> namesColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return StringUtils.join(row.getNames(), ", "); } }; AbstractTextColumn<GuestContainer> imageColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getImage(); } }; AbstractTextColumn<GuestContainer> commandColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getCommand(); } }; AbstractTextColumn<GuestContainer> statusColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getStatus(); } }; containersTable.addColumn(idColumn, constants.idContainer()); containersTable.addColumn(namesColumn, constants.namesContainer()); containersTable.addColumn(imageColumn, constants.imageContainer()); containersTable.addColumn(commandColumn, constants.commandContainer()); containersTable.addColumn(statusColumn, constants.statusContainer()); containersTable.setRowData(new ArrayList<EntityModel>()); containersTable.setWidth("100%", true); containersTable.setSelectionModel(new NoSelectionModel()); }

Target:
protected void initContainersTable() { containersTable = new EntityModelCellTable<>(false, true); containersTable.addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getId().toString(); } }, constants.idContainer()); containersTable.addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return StringUtils.join(row.getNames(), ", "); } }, constants.namesContainer()); containersTable.addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getImage(); } }, constants.imageContainer()); containersTable.addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getCommand(); } }, constants.commandContainer()); containersTable.addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getStatus(); } }, constants.statusContainer()); containersTable.setRowData(new ArrayList<EntityModel>()); containersTable.setWidth("100%", true); containersTable.setSelectionModel(new NoSelectionModel()); }
Source:
public void canDoActionFailsOnCompat() { cmd = spy(createTestCommand(volumeId1)); prepareMocks(cmd); doReturn(UNSUPPORTED_VERSION).when(vdsGroup).getCompatibilityVersion(); assertFalse(cmd.canDoAction()); }

Target:
public void canDoActionFailsOnCompat() { cmd = spy(createTestCommand(volumeId1)); prepareMocks(cmd); doReturn(UNSUPPORTED_VERSION).when(vdsGroup).getCompatibilityVersion(); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.GLUSTER_TASKS_NOT_SUPPORTED_FOR_CLUSTER_LEVEL.toString())); }
Source:
public List<QueryResult<CohortAclEntry>> getAcls(String studyStr, List<String> cohortList, boolean silent, String sessionId) throws CatalogException { MyResourceIds resource = getIds(cohortList, studyStr, sessionId); List<QueryResult<CohortAclEntry>> cohortAclList = new ArrayList<>(resource.getResourceIds().size()); for (Long cohortId : resource.getResourceIds()) { try { QueryResult<CohortAclEntry> allCohortAcls = authorizationManager.getAllCohortAcls(resource.getStudyId(), cohortId, resource.getUser()); allCohortAcls.setId(String.valueOf(cohortId)); cohortAclList.add(allCohortAcls); } catch (CatalogException e) { if (silent) { cohortAclList.add(new QueryResult<>(studyStr, 0, 0, 0, "", e.toString(), new ArrayList<>(0))); } else { throw e; } } } return cohortAclList; }

Target:
public List<QueryResult<CohortAclEntry>> getAcls(String studyStr, List<String> cohortList, boolean silent, String sessionId) throws CatalogException { MyResourceIds resource = getIds(cohortList, studyStr, sessionId); List<QueryResult<CohortAclEntry>> cohortAclList = new ArrayList<>(resource.getResourceIds().size()); List<Long> resourceIds = resource.getResourceIds(); for (int i = 0; i < resourceIds.size(); i++) { Long cohortId = resourceIds.get(i); try { QueryResult<CohortAclEntry> allCohortAcls = authorizationManager.getAllCohortAcls(resource.getStudyId(), cohortId, resource.getUser()); allCohortAcls.setId(String.valueOf(cohortId)); cohortAclList.add(allCohortAcls); } catch (CatalogException e) { if (silent) { cohortAclList.add(new QueryResult<>(cohortList.get(i), 0, 0, 0, "", e.toString(), new ArrayList<>(0))); } else { throw e; } } } return cohortAclList; }
Source:
private void fireNewSessionEvents() { final String sessionId = Long.toHexString(getSessionId()); for (final IZkStateListener stateListener : _stateListener) { _eventThread.send(new ZkEvent("New session event sent to " + stateListener, sessionId) { @Override public void run() throws Exception { stateListener.handleNewSession(sessionId); } }); } }

Target:
private void fireNewSessionEvents() { for (final IZkStateListener stateListener : _stateListener) { _eventThread.send(new ZkEvent("New session event sent to " + stateListener) { @Override public void run() throws Exception { stateListener.handleNewSession(null); } }); } }
Source:
public void close() throws IOException { mScanner.close(); mCloser.close(); }

Target:
public void close() throws IOException { closeScanner(mScanner); }
Source:
public FileSinkCommittableSerializer( SimpleVersionedSerializer<InProgressFileWriter.PendingFileRecoverable> pendingFileSerializer, SimpleVersionedSerializer<InProgressFileWriter.InProgressFileRecoverable> inProgressFileSerializer) { this.pendingFileSerializer = pendingFileSerializer; this.inProgressFileSerializer = inProgressFileSerializer; }

Target:
public FileSinkCommittableSerializer( SimpleVersionedSerializer<InProgressFileWriter.PendingFileRecoverable> pendingFileSerializer, SimpleVersionedSerializer<InProgressFileWriter.InProgressFileRecoverable> inProgressFileSerializer) { this.pendingFileSerializer = checkNotNull(pendingFileSerializer); this.inProgressFileSerializer = checkNotNull(inProgressFileSerializer); }
Source:
public synchronized int getCapacity() { return capacity; }

Target:
public int getCapacity() { return capacity; }
Source:
public void limit_withSortAndDistinct() { realm.executeTransaction(r -> { for (int i = 0; i < 5; i++) { r.createObject(AllTypes.class).setColumnLong(i % 5); } }); RealmResults<AllTypes> results = realm.where(AllTypes.class) .sort(AllTypes.FIELD_LONG, Sort.DESCENDING) .distinct(AllTypes.FIELD_LONG) .limit(2) .findAll(); assertEquals(2, results.size()); assertEquals(4, results.first().getColumnLong()); assertEquals(3, results.last().getColumnLong()); results = realm.where(AllTypes.class) .limit(2) .distinct(AllTypes.FIELD_LONG) .sort(AllTypes.FIELD_LONG, Sort.DESCENDING) .findAll(); assertEquals(2, results.size()); assertEquals(1, results.first().getColumnLong()); assertEquals(0, results.last().getColumnLong()); results = realm.where(AllTypes.class) .distinct(AllTypes.FIELD_LONG) .limit(2) .sort(AllTypes.FIELD_LONG, Sort.DESCENDING) .findAll(); assertEquals(2, results.size()); assertEquals(1, results.first().getColumnLong()); assertEquals(0, results.last().getColumnLong()); }

Target:
public void limit_withSortAndDistinct() { realm.beginTransaction(); RealmList<AllJavaTypes> list = realm.createObject(AllJavaTypes.class, -1).getFieldList(); for (int i = 0; i < 5; i++) { AllJavaTypes obj = realm.createObject(AllJavaTypes.class, i); obj.setFieldLong(i); list.add(obj); } realm.commitTransaction(); RealmResults<AllJavaTypes> results = list.where() .sort(AllJavaTypes.FIELD_LONG, Sort.DESCENDING) .distinct(AllJavaTypes.FIELD_LONG) .limit(2) .findAll(); assertEquals(2, results.size()); assertEquals(4, results.first().getFieldLong()); assertEquals(3, results.last().getFieldLong()); results = list.where() .limit(2) .distinct(AllJavaTypes.FIELD_LONG) .sort(AllJavaTypes.FIELD_LONG, Sort.DESCENDING) .findAll(); assertEquals(2, results.size()); assertEquals(1, results.first().getFieldLong()); assertEquals(0, results.last().getFieldLong()); results = list.where() .distinct(AllJavaTypes.FIELD_LONG) .limit(2) .sort(AllJavaTypes.FIELD_LONG, Sort.DESCENDING) .findAll(); assertEquals(2, results.size()); assertEquals(1, results.first().getFieldLong()); assertEquals(0, results.last().getFieldLong()); }
Source:
public void close() { if (receiver == null) return; try { receiver.close().whenCompleteAsync((voidargs, error) -> { try { if (error != null) { logger.error("Exception during receiver close phase: " + error.toString()); } ehClient.closeSync(); } catch (Exception e) { logger.error("Exception during ehclient close phase: " + e.toString()); } }).get(); } catch (InterruptedException | ExecutionException e) { logger.warn("Exception occured during close phase: " + e.toString()); } executorService.shutdown(); logger.info("closed eventhub receiver: partitionId=" + partitionId); ehClient = null; receiver = null; executorService = null; }

Target:
public void close() { try { if (receiver != null) { receiver.closeSync(); } } catch (EventHubException e) { logger.warn("Exception occurred while closing PartitionReceiver: " + e.toString()); } try { if (ehClient != null) { ehClient.closeSync(); } } catch (EventHubException e) { logger.warn("Exception occurred while closing EventHubClient: " + e.toString()); } executorService.shutdown(); try { executorService.awaitTermination(2, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.warn("Exception occurred while terminating ExecutorService: " + e.toString()); } logger.info("closed eventhub receiver: partitionId=" + partitionId); ehClient = null; receiver = null; executorService = null; }
Source:
public void createBucket(String bucketName) throws IOException { logger.atFine().log("%s.create(%s)", delegateClassName, bucketName); delegate.createBucket(bucketName); }

Target:
public void createBucket(String bucketName) throws IOException { logger.atFine().log("%s.createBucket(%s)", delegateClassName, bucketName); delegate.createBucket(bucketName); }
Source:
protected void configure() { super.configure(); bind(new TypeLiteral<ComputeServiceAdapter<VMDeployment, VMHardware, VMImage, Location>>() { }).to(AzureComputeServiceAdapter.class); bind(new TypeLiteral<Function<VMImage, org.jclouds.compute.domain.Image>>() { }).to(VMImageToImage.class); bind(new TypeLiteral<Function<VMHardware, Hardware>>() { }).to(VMHardwareToHardware.class); bind(new TypeLiteral<Function<VMDeployment, NodeMetadata>>() { }).to(DeploymentToNodeMetadata.class); bind(new TypeLiteral<Function<Location, org.jclouds.domain.Location>>() { }).to(LocationToLocation.class); install(new LocationsFromComputeServiceAdapterModule<VMDeployment, VMHardware, VMImage, Location>() { }); bind(CreateNodesInGroupThenAddToSet.class).to(CreateResourceGroupThenCreateNodes.class); }

Target:
protected void configure() { super.configure(); bind(new TypeLiteral<ComputeServiceAdapter<VMDeployment, VMHardware, VMImage, Location>>() { }).to(AzureComputeServiceAdapter.class); bind(new TypeLiteral<Function<VMImage, org.jclouds.compute.domain.Image>>() { }).to(VMImageToImage.class); bind(new TypeLiteral<Function<VMHardware, Hardware>>() { }).to(VMHardwareToHardware.class); bind(new TypeLiteral<Function<VMDeployment, NodeMetadata>>() { }).to(DeploymentToNodeMetadata.class); bind(new TypeLiteral<Function<Location, org.jclouds.domain.Location>>() { }).to(LocationToLocation.class); bind(ComputeService.class).to(AzureComputeService.class); install(new LocationsFromComputeServiceAdapterModule<VMDeployment, VMHardware, VMImage, Location>() { }); bind(CreateNodesInGroupThenAddToSet.class).to(CreateResourceGroupThenCreateNodes.class); }
Source:
private boolean checkNativeType( Value value, NativeType nativeType ) { if ( nativeType == NativeType.ANY ) { return true; } else if ( nativeType == NativeType.DOUBLE ) { return value.isDouble() || value.isInt(); } else if ( nativeType == NativeType.LONG ) { return value.isInt() || value.isLong(); } else if ( nativeType == NativeType.BOOL ) { return value.isBool(); } else if ( nativeType == NativeType.INT ) { return value.isInt(); } else if ( nativeType == NativeType.STRING ) { return value.isString(); } else if ( nativeType == NativeType.VOID ) { return value.valueObject() == null; } else if ( nativeType == NativeType.RAW ) { return value.isByteArray(); } return false; }

Target:
private boolean checkNativeType( Value value, NativeType nativeType ) { switch( nativeType ) { case ANY: return true; case DOUBLE: return value.isDouble() || value.isInt(); case LONG: return value.isLong() || value.isInt(); case BOOL: return value.isBool(); case INT: return value.isInt(); case STRING: return value.isString(); case VOID: return value.valueObject() == null; case RAW: return value.isByteArray(); } return false; }
Source:
public void returnsCorrectInputWithUrl() throws Exception { final Path file = BodyUrlTest.createTempFile(); try { final byte[] bytes = new Utf8String("URL returnsCorrectInput!").asBytes(); try (InputStream input = new InputOf(bytes).stream()) { Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING); } final Body.Url input = new Body.Url(file.toUri().toURL()); MatcherAssert.assertThat( "Body content of Body.Url doesn't provide the correct bytes", new BytesOf(input).asBytes(), new IsEqual<>(bytes) ); } finally { Files.deleteIfExists(file); } }

Target:
public void returnsCorrectInputWithUrl() throws Exception { try (TempFile file = new TempFile()) { final Bytes body = new Utf8String("URL returnsCorrectInput!"); try (OutputStream outStream = new OutputTo(file.value()).stream()) { new LengthOf( new TeeInput(body, new OutputTo(outStream)) ).intValue(); } final Body.Url input = new Body.Url(file.value().toUri().toURL()); MatcherAssert.assertThat( "Body content of Body.Url doesn't provide the correct bytes", new BytesOf(input).asBytes(), new IsEqual<>(body.asBytes()) ); } }
Source:
public void close() throws Exception { if (scopeCleaner.close()) { LOGGER.info("closing PreDestroyMonitor..."); synchronized(cleanupActions) { List<Map.Entry<Object, UnscopedCleanupAction>> actions = new ArrayList<>(cleanupActions.entrySet()); Collections.sort(actions, (a,b)->Long.compare(b.getValue().ordinal, a.getValue().ordinal)); for (Map.Entry<Object, UnscopedCleanupAction> action : actions) { action.getValue().call(action.getKey()); } if (actions.size() > 0) { LOGGER.warn("predestroy action invoked for unscoped instances", actions.size()); Map<Object, Long> actionsBySource = actions.stream().map(Map.Entry::getValue).collect( Collectors.groupingBy(UnscopedCleanupAction::getContext, Collectors.counting())); for (Map.Entry<Object, Long> entry : actionsBySource.entrySet()) { LOGGER.warn(" including objects from source '{}'", entry.getValue(), entry.getKey()); } } actions.clear(); cleanupActions.clear(); } scopeBindings.clear(); scopeBindings = Collections.emptyMap(); } else { LOGGER.warn("PreDestroyMonitor.close() invoked but instance is not running"); } }

Target:
public void close() throws Exception { if (scopeCleaner.close()) { LOGGER.info("closing PreDestroyMonitor..."); List<Map.Entry<Object, UnscopedCleanupAction>> actions = new ArrayList<>(cleanupActions.entrySet()); if (actions.size() > 0) { LOGGER.warn("invoking predestroy action for unscoped instances", actions.size()); actions.stream().map(Map.Entry::getValue).collect( Collectors.groupingBy(UnscopedCleanupAction::getContext, Collectors.counting())).forEach((source, count)->{ LOGGER.warn(" including objects from source '{}'", count, source); }); } actions.stream().sorted(Map.Entry.comparingByValue()).forEach(action->{ Optional.ofNullable(action.getKey()).ifPresent(obj->action.getValue().call(obj)); }); actions.clear(); cleanupActions.clear(); scopeBindings.clear(); scopeBindings = Collections.emptyMap(); } else { LOGGER.warn("PreDestroyMonitor.close() invoked but instance is not running"); } }
Source:
public ObjectId insert(int type, byte[] data, int off, int len, boolean createDuplicate) throws IOException { ObjectId id = idFor(type, data, off, len); if (!createDuplicate && db.has(id)) { return id; } else { File tmp = toTemp(type, data, off, len); return insertOneObject(tmp, id, createDuplicate); } }

Target:
ObjectId insert(int type, byte[] data, int off, int len, boolean createDuplicate) throws IOException { ObjectId id = idFor(type, data, off, len); if (!createDuplicate && db.has(id)) { return id; } else { File tmp = toTemp(type, data, off, len); return insertOneObject(tmp, id, createDuplicate); } }
Source:
public boolean useNullForMissingParameters() { return false; }

Target:
protected boolean useNullForMissingParameters() { return false; }
Source:
protected void handleDownload(Request req) throws IOException { String[] arch = (String[]) req.getParams().get("arch"); String archSuffix = ""; if (arch != null && arch.length > 0 && !arch[0].equals("amd64")) { archSuffix = "-" + arch[0]; } log.debug("Client is requesting item [{}]", req.getClient(), req.getItemName() + archSuffix); ConfigItem item = itemRegistry.getConfigItem(req.getItemName() + archSuffix); if (item == null) { log.debug("Item does not exist", req.getItemName() + archSuffix); item = itemRegistry.getConfigItem(req.getItemName()); if (item != null) { log.debug("Item exists", req.getItemName()); } } if (item == null) { log.info("Client requested unknown item [{}]", req.getClient(), req.getItemName()); req.setResponseCode(Request.NOT_FOUND); return; } if (!versionManager.isAssigned(req.getClient(), req.getItemName())) { if (item.isDynamicallyApplied()) { ConfigUpdateRequest updateRequest = new ConfigUpdateRequest(req.getClient()).withDeferredTrigger(true); updateRequest.addItem(req.getItemName()); versionManager.updateConfig(updateRequest); } else { log.error("Client requesting non-assigned item [{}]", req.getClient(), req.getItemName()); req.setResponseCode(Request.NOT_FOUND); return; } } log.info("Processing for client [{}]", req.getItemName(), req.getClient()); item.handleRequest(req); }

Target:
protected void handleDownload(Request req) throws IOException { ConfigItem item = retrieveItem(req); if (item == null) { log.info("Client requested unknown item [{}]", req.getClient(), req.getItemName()); req.setResponseCode(Request.NOT_FOUND); return; } if (!versionManager.isAssigned(req.getClient(), req.getItemName())) { if (item.isDynamicallyApplied()) { ConfigUpdateRequest updateRequest = new ConfigUpdateRequest(req.getClient()).withDeferredTrigger(true); updateRequest.addItem(req.getItemName()); versionManager.updateConfig(updateRequest); } else { log.error("Client requesting non-assigned item [{}]", req.getClient(), req.getItemName()); req.setResponseCode(Request.NOT_FOUND); return; } } log.info("Processing for client [{}]", req.getItemName(), req.getClient()); item.handleRequest(req); }
Source:
public String getRunningFlowIds() { Set<Runnable> inProgressTasks = executorService.getInProgressTasks(); List<Integer> runningFlowIds = new ArrayList<Integer>(inProgressTasks.size()); for (Runnable task : inProgressTasks) { Integer execId = submittedFlows.get(task); if (execId != null) { runningFlowIds.add(execId); } else { logger.warn("getRunningFlowIds: got null execId for task: " + task); } } Collections.sort(runningFlowIds); return runningFlowIds.toString(); }

Target:
public String getRunningFlowIds() { Set<Runnable> inProgressTasks = executorService.getInProgressTasks(); List<Integer> runningFlowIds = new ArrayList<Integer>(inProgressTasks.size()); for (Runnable task : inProgressTasks) { Integer execId = submittedFlows.get((Future<?>) task); if (execId != null) { runningFlowIds.add(execId); } else { logger.warn("getRunningFlowIds: got null execId for task: " + task); } } Collections.sort(runningFlowIds); return runningFlowIds.toString(); }
Source:
public String removeSuffix(String loaderFileName, char suffixTerm) { return loaderFileName.substring(0, loaderFileName.lastIndexOf(suffixTerm)); }

Target:
private String removeSuffix(String loaderFileName, char suffixTerm) { return loaderFileName.substring(0, loaderFileName.lastIndexOf(suffixTerm)); }
Source:
private AuditLogable auditEventIpv4GatewayOutOfRange(NetworkAttachment attachment, IPv4Address address) { AuditLogable event = new AuditLogableImpl(); event.setClusterId(getCluster().getId()); event.setClusterName(getCluster().getName()); event.setVdsName(getVdsName()); event.addCustomValue("Interface", attachment.getNicName()); event.addCustomValue("Gateway", address.getGateway()); return event; }

Target:
private AuditLogable auditEventIpv4GatewayOutOfRange(NetworkAttachment attachment, IPv4Address address) { AuditLogable event = new AuditLogableImpl(); event.setVdsId(getVdsId()); event.setClusterName(getCluster().getName()); event.setVdsName(getVdsName()); event.addCustomValue("Interface", attachment.getNicName()); event.addCustomValue("Gateway", address.getGateway()); return event; }
Source:
public void testCookieAuthWithoutRetry() throws IOException { if(IGNORE_AUTH_HEADERS){ System.err.println("Ignore cookie filters"); return; } CookieFilter filter = new CookieFilter(System.getProperty("test.couch.username"),System.getProperty("test.couch.password")); CouchConfig config = getCouchConfig("cookie_test"); HttpConnection conn = new HttpConnection("POST", config.getRootUri().toURL(), "application/json"); conn.responseFilters.add(filter); conn.requestFilters.add(filter); ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); Assert.assertEquals(bis.available(), data.getBytes().length); conn.setRequestBody(bis); conn.execute(); Assert.assertEquals(bis.available(), 0); Assert.assertEquals(2, conn.getResponseCode() / 100); JSONHelper helper = new JSONHelper(); Map<String,Object> jsonRes = helper.fromJson(new InputStreamReader(conn.getConnection() .getInputStream())); Assert.assertTrue(jsonRes.containsKey("ok")); Assert.assertTrue((Boolean)jsonRes.get("ok")); Assert.assertTrue(jsonRes.containsKey("id")); Assert.assertTrue(jsonRes.containsKey("rev")); }

Target:
public void testCookieAuthWithoutRetry() throws IOException { Assume.assumeFalse(IGNORE_AUTH_HEADERS); CookieFilter filter = new CookieFilter(System.getProperty("test.couch.username"), System.getProperty("test.couch.password")); CouchConfig config = getCouchConfig("cookie_test"); HttpConnection conn = new HttpConnection("POST", config.getRootUri().toURL(), "application/json"); conn.responseFilters.add(filter); conn.requestFilters.add(filter); ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); Assert.assertEquals(bis.available(), data.getBytes().length); conn.setRequestBody(bis); conn.execute(); Assert.assertEquals(bis.available(), 0); Assert.assertEquals(2, conn.getConnection().getResponseCode() / 100); JSONHelper helper = new JSONHelper(); Map<String,Object> jsonRes = helper.fromJson(new InputStreamReader(conn.getConnection() .getInputStream())); Assert.assertTrue(jsonRes.containsKey("ok")); Assert.assertTrue((Boolean)jsonRes.get("ok")); Assert.assertTrue(jsonRes.containsKey("id")); Assert.assertTrue(jsonRes.containsKey("rev")); }
Source:
void validateAuthority(final URL authorizationEndpoint) throws AuthenticationException { verifyAuthorityValidInstance(authorizationEndpoint); if (AuthorityValidationMetadataCache.containsAuthorityHost(authorizationEndpoint)) { return; } final String authorityHost = authorizationEndpoint.getHost().toLowerCase(Locale.US); final String trustedHost; if (AAD_WHITELIST_HOSTS.contains(authorizationEndpoint.getHost().toLowerCase(Locale.US))) { trustedHost = authorityHost; } else { trustedHost = TRUSTED_QUERY_INSTANCE; } try { sLock = getLock(); sLock.lock(); performInstanceDiscovery(authorizationEndpoint, trustedHost); } finally { sLock.unlock(); } }

Target:
void validateAuthority(final URL authorizationEndpoint) throws AuthenticationException { verifyAuthorityValidInstance(authorizationEndpoint); if (AuthorityValidationMetadataCache.containsAuthorityHost(authorizationEndpoint)) { return; } final String authorityHost = authorizationEndpoint.getHost().toLowerCase(Locale.US); final String trustedHost; if (AAD_WHITELISTED_HOSTS.contains(authorizationEndpoint.getHost().toLowerCase(Locale.US))) { trustedHost = authorityHost; } else { trustedHost = TRUSTED_QUERY_INSTANCE; } try { sLock = getLock(); sLock.lock(); performInstanceDiscovery(authorizationEndpoint, trustedHost); } finally { sLock.unlock(); } }
Source:
private Logger configureLevels() { final Logger root = loggerContext.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); root.getLoggerContext().reset(); final LevelChangePropagator propagator = new LevelChangePropagator(); propagator.setContext(root.getLoggerContext()); propagator.setResetJUL(true); root.getLoggerContext().addListener(propagator); root.setLevel(level); for (Map.Entry<String, Level> entry : loggers.entrySet()) { loggerContext.getLogger(entry.getKey()).setLevel(entry.getValue()); } return root; }

Target:
private Logger configureLevels() { final Logger root = loggerContext.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); loggerContext.reset(); final LevelChangePropagator propagator = new LevelChangePropagator(); propagator.setContext(loggerContext); propagator.setResetJUL(true); loggerContext.addListener(propagator); root.setLevel(level); for (Map.Entry<String, Level> entry : loggers.entrySet()) { loggerContext.getLogger(entry.getKey()).setLevel(entry.getValue()); } return root; }
Source:
private static JsonNode extractAuthJson(final Path configPath) throws IOException { final ObjectMapper mapper = new ObjectMapper(); final JsonNode config = mapper.readTree(configPath.toFile()); if (config.has("auths")) { return config.get("auths"); } return config; }

Target:
private static JsonNode extractAuthJson(final Path configPath) throws IOException { final JsonNode config = MAPPER.readTree(configPath.toFile()); if (config.has("auths")) { return config.get("auths"); } return config; }
Source:
private void updateAutoSendStatus() { LiveData<List<WorkInfo>> statuses = WorkManager.getInstance().getWorkInfosForUniqueWorkLiveData("AutoSendWorker"); statuses.observe(this, workStatuses -> { if (workStatuses != null) { for (WorkInfo status : workStatuses) { if (status.getState().equals(WorkInfo.State.RUNNING)) { autoSendOngoing = true; return; } } autoSendOngoing = false; } }); }

Target:
private void updateAutoSendStatus() { LiveData<List<WorkInfo>> statuses = WorkManager.getInstance().getWorkInfosForUniqueWorkLiveData(SchedulerFormUpdateAndSubmitManager.AUTO_SEND_TAG); statuses.observe(this, workStatuses -> { if (workStatuses != null) { for (WorkInfo status : workStatuses) { if (status.getState().equals(WorkInfo.State.RUNNING)) { autoSendOngoing = true; return; } } autoSendOngoing = false; } }); }
Source:
static ModelNode execute(final ManagementClient managementClient, final ModelNode op) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); assertTrue(response.isDefined()); ModelNode outcome = response.get(ModelDescriptionConstants.OUTCOME); assertTrue(outcome.isDefined()); if (!ModelDescriptionConstants.SUCCESS.equals(outcome.asString())) { System.err.println(response); } assertEquals(ModelDescriptionConstants.SUCCESS, outcome.asString()); return response.get(ModelDescriptionConstants.RESULT); }

Target:
static ModelNode execute(final ManagementClient managementClient, final ModelNode op) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); assertTrue(response.isDefined()); if (!Operations.isSuccessfulOutcome(response)) { Assert.fail(Operations.getFailureDescription(response).asString()); } return response.get(ModelDescriptionConstants.RESULT); }
Source:
public Set<T> getModifiableItems(MethodLocation newItemsLocation) { return new AbstractSet<T>() { @Nonnull @Override public Iterator<T> iterator() { final Iterator<T> it = getImmutableItems().iterator(); return new Iterator<T>() { private @Nullable T currentItem = null; @Override public boolean hasNext() { return it.hasNext(); } @Override public T next() { currentItem = it.next(); return currentItem; } @Override public void remove() { if (currentItem != null) { currentItem.setLocation(null); } it.remove(); } }; } @Override public int size() { return getImmutableItems().size(); } @Override public boolean add(@Nonnull T item) { if (item.isPlaced()) { throw new IllegalArgumentException(addLocatedItemError()); } item.setLocation(newItemsLocation); getMutableItems().add(item); return true; } }; }

Target:
public Set<T> getModifiableItems(MethodLocation newItemsLocation) { return new AbstractSet<T>() { @Nonnull @Override public Iterator<T> iterator() { final Iterator<T> it = getItems().iterator(); return new Iterator<T>() { private @Nullable T currentItem = null; @Override public boolean hasNext() { return it.hasNext(); } @Override public T next() { currentItem = it.next(); return currentItem; } @Override public void remove() { if (currentItem != null) { currentItem.setLocation(null); } it.remove(); } }; } @Override public int size() { return getItems().size(); } @Override public boolean add(@Nonnull T item) { if (item.isPlaced()) { throw new IllegalArgumentException(getAddLocatedItemError()); } item.setLocation(newItemsLocation); addItem(item); return true; } }; }
Source:
private void updateMetrics(Instant arrivalTime, Instant outputTime) { messagesCounter.inc(); processingTimeHistogram.update(Duration.between(arrivalTime, outputTime).toMillis()); }

Target:
private void updateMetrics(Instant arrivalTime, Instant outputTime) { numEvents.inc(); processingTime.update(Duration.between(arrivalTime, outputTime).toNanos() / 1000L); }
Source:
protected void initVm() { if (!isInitVmRequired()) { return; } fetchVmDisksFromDb(); updateVmDevicesOnRun(); updateGraphicsAndDisplayInfos(); getVm().setRunAndPause(getParameters().getRunAndPause() == null ? getVm().isRunAndPause() : getParameters().getRunAndPause()); getVm().setConsoleUserId(null); updateVmInit(); if (!StringUtils.isEmpty(getParameters().getFloppyPath()) && isPayloadExists(VmDeviceType.FLOPPY)) { vmPayload = null; } updateVmGuestAgentVersion(); if (getVm().getCpuName() == null) { if (getVm().getCustomCpuName() != null) { getVm().setCpuName(getVm().getCustomCpuName()); } else { getVm().setCpuName(getCpuFlagsManagerHandler().getCpuId( getVm().getClusterCpuName(), getVm().getCompatibilityVersion())); } } else if (getVm().isUseHostCpuFlags()) { getVm().setCpuName(getVds().getCpuFlags()); } if (getVm().getEmulatedMachine() == null) { getVm().setEmulatedMachine(getEffectiveEmulatedMachine()); } }

Target:
protected void initVm() { if (!isInitVmRequired()) { return; } fetchVmDisksFromDb(); updateVmDevicesOnRun(); updateGraphicsAndDisplayInfos(); getVm().setRunAndPause(getParameters().getRunAndPause() == null ? getVm().isRunAndPause() : getParameters().getRunAndPause()); getVm().setConsoleUserId(null); updateVmInit(); if (!StringUtils.isEmpty(getParameters().getFloppyPath()) && isPayloadExists(VmDeviceType.FLOPPY)) { vmPayload = null; } updateVmGuestAgentVersion(); if (!getVm().isUseHostCpuFlags() && getVm().getCpuName() == null) { if (getVm().getCustomCpuName() != null) { getVm().setCpuName(getVm().getCustomCpuName()); } else { getVm().setCpuName(getCpuFlagsManagerHandler().getCpuId( getVm().getClusterCpuName(), getVm().getCompatibilityVersion())); } } if (getVm().getEmulatedMachine() == null) { getVm().setEmulatedMachine(getEffectiveEmulatedMachine()); } }
Source:
ImmutableList<AnalyzedCheckConstraint> checkConstraints() { return checkConstraints; }

Target:
List<CheckConstraint<Symbol>> checkConstraints() { return checkConstraints; }
Source:
public void run() { Thread.currentThread().setName( "JobRunner-" + this.jobId + "-" + executionId); if (handleNonReadyStatus()) { return; } createAttachmentFile(); createLogger(); boolean errorFound = false; errorFound |= delayExecution(); errorFound |= blockOnPipeLine(); node.setStartTime(System.currentTimeMillis()); if (!errorFound && !isKilled()) { fireEvent(Event.create(this, Type.JOB_STARTED, null, false)); try { loader.uploadExecutableNode(node, props); } catch (ExecutorManagerException e1) { logger.error("Error writing initial node properties"); } if (prepareJob()) { writeStatus(); fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false); runJob(); } else { changeStatus(Status.FAILED); logError("Job run failed preparing the job."); } } node.setEndTime(System.currentTimeMillis()); if (isKilled()) { changeStatus(Status.KILLED); } logInfo("Finishing job " + this.jobId + " attempt: " + node.getAttempt() + " at " + node.getEndTime() + " with status " + node.getStatus()); int attempNo = node.getAttempt(); fireEvent(Event.create(this, Type.JOB_FINISHED), false); finalizeLogFile(attempNo); finalizeAttachmentFile(); writeStatus(); }

Target:
public void run() { Thread.currentThread().setName( "JobRunner-" + this.jobId + "-" + executionId); if (handleNonReadyStatus()) { return; } createAttachmentFile(); createLogger(); boolean errorFound = false; errorFound |= delayExecution(); errorFound |= blockOnPipeLine(); node.setStartTime(System.currentTimeMillis()); if (!errorFound && !isKilled()) { fireEvent(Event.create(this, Type.JOB_STARTED, null, false)); try { loader.uploadExecutableNode(node, props); } catch (ExecutorManagerException e1) { logger.error("Error writing initial node properties"); } if (prepareJob()) { writeStatus(); fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false); runJob(); } else { changeStatus(Status.FAILED); logError("Job run failed preparing the job."); } } node.setEndTime(System.currentTimeMillis()); if (isKilled()) { changeStatus(Status.KILLED); } int attemptNo = node.getAttempt(); logInfo("Finishing job " + this.jobId + " attempt: " + attemptNo + " at " + node.getEndTime() + " with status " + node.getStatus()); fireEvent(Event.create(this, Type.JOB_FINISHED), false); finalizeLogFile(attemptNo); finalizeAttachmentFile(); writeStatus(); }
Source:
public SimpleStatementBuilder builder() { return SimpleStatement.builder(asCql()).setIdempotence(IS_IDEMPOTENT); }

Target:
public SimpleStatementBuilder builder() { return SimpleStatement.builder(asCql()).setIdempotence(true); }
Source:
public AEBaseSlabBlock( AEBaseBlock block, int meta, EnumSet<AEFeature> features, boolean isDoubleSlab, String name ) { super( isDoubleSlab, block.getMaterial() ); this.block = block; this.meta = meta; this.name = name; this.isDoubleSlab = isDoubleSlab; this.setBlockName( "appliedenergistics2." + name ); this.setHardness( block.getBlockHardness( null, 0, 0, 0 ) ); this.setResistance( block.getExplosionResistance( null ) * 5.0F / 3.0F ); this.setStepSound( block.stepSound ); this.useNeighborBrightness = true; if (!isDoubleSlab) { this.dSlabs = new AEBaseSlabBlock( block, meta, features, true, name + ".double" ).setSlabs(this); this.slabs = this; } else { this.dSlabs = this; } this.features = isDoubleSlab ? new SlabBlockFeatureHandler( features, this ) : new SlabBlockFeatureHandler( features, this ); }

Target:
public AEBaseSlabBlock( AEBaseBlock block, int meta, EnumSet<AEFeature> features, boolean isDoubleSlab, String name ) { super( isDoubleSlab, block.getMaterial() ); this.block = block; this.meta = meta; this.name = name; this.setBlockName( "appliedenergistics2." + name ); this.setHardness( block.getBlockHardness( null, 0, 0, 0 ) ); this.setResistance( block.getExplosionResistance( null ) * 5.0F / 3.0F ); this.setStepSound( block.stepSound ); this.useNeighborBrightness = true; if (!field_150004_a) this.doubleSlabs = new AEBaseSlabBlock( block, meta, features, true, name + ".double" ).setSlabs(this); this.features = !field_150004_a ? new SlabBlockFeatureHandler( features, this ) : null; }
Source:
public void processTextFieldChange(String text) { int curTextFieldLength = text.length(); if (curTextFieldLength > 0) { if (curTextFieldLength > previousTextFieldLength) { char lastChar = text.charAt(curTextFieldLength - 1); String[] textArray = text.trim().split(" "); String finalLabel = textArray[textArray.length - 1]; if (lastChar == ' ') { if (hasHighlightedLabel()) { listOfSpecifiedLabels.add(getHighlightedLabelName().get().getActualName()); toggleHighlightedLabel(); } else { listOfSpecifiedLabels.add(null); listOfRemovedExclusiveLabels.add(null); } } else { updateBottomLabelsWithRawQuery(finalLabel); updatePossibleLabel(); } } else { char lastChar = text.charAt(curTextFieldLength - 1); if (lastChar != ' ' && previousLastChar == ' ' && !listOfSpecifiedLabels.isEmpty()) { int lastIndex = listOfSpecifiedLabels.size() - 1; String lastLabel = listOfSpecifiedLabels.get(lastIndex); listOfSpecifiedLabels.remove(lastIndex); if (lastLabel != null) { updateTopLabels(lastLabel, !resultList.get(lastLabel)); } ArrayList<String> listOfRemovedLabels = listOfRemovedExclusiveLabels.get(lastIndex); listOfRemovedExclusiveLabels.remove(lastIndex); if (listOfRemovedLabels != null) { listOfRemovedLabels.stream() .forEach(labelName -> { updateTopLabels(labelName, true); }); } } if (lastChar == ' ') { removePossibleLabel(); } else { String[] textArray = text.trim().split(" "); String finalLabel = textArray[textArray.length - 1]; updateBottomLabelsWithRawQuery(finalLabel); updatePossibleLabel(); } } previousTextFieldLength = curTextFieldLength; previousLastChar = text.charAt(curTextFieldLength - 1); } else { removePossibleLabel(); } populatePanes(); }

Target:
public void processTextFieldChange(String text) { if (isEmpty(text)) { handleNoQuery(); } else if (isCharAdded(text)) { handleCharAddition(text); } else { handleCharRemoval(text); } updatePreviousTextFieldInfo(text); populatePanes(); }