auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void trustStoreFileChooserButton() { trustStoreFileChooserButton = new JButton(JWTI18n.getMessage("jwt.settings.filechooser.button")); trustStoreFileChooserButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { trustStoreFileChooser = new JFileChooser(); trustStoreFileChooser.setFileFilter( new FileFilter() { @Override public String getDescription() { <START> return "PKCS12 format"; <END> } @Override public boolean accept(File f) { return f.getName().endsWith(".p12") || f.isDirectory(); } }); trustStoreFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); String path = trustStoreFileChooserTextField.getText(); if (!path.isEmpty()) { File file = new File(path); if (file.exists()) { trustStoreFileChooser.setSelectedFile(file); } } if (trustStoreFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { final File selectedFile = trustStoreFileChooser.getSelectedFile(); trustStorePath = selectedFile.getAbsolutePath(); trustStoreFileChooserTextField.setText(selectedFile.getAbsolutePath()); } } }); }</code><technical_language>i18n</technical_language>

Target:
private void trustStoreFileChooserButton() { trustStoreFileChooserButton = new JButton(JWTI18n.getMessage("jwt.settings.filechooser.button")); trustStoreFileChooserButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { trustStoreFileChooser = new JFileChooser(); trustStoreFileChooser.setFileFilter( new FileFilter() { @Override public String getDescription() { return JWTI18n.getMessage( "jwt.settings.rsa.trustStoreFileDescription"); } @Override public boolean accept(File f) { return f.getName().endsWith(".p12") || f.isDirectory(); } }); trustStoreFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); String path = trustStoreFileChooserTextField.getText(); if (!path.isEmpty()) { File file = new File(path); if (file.exists()) { trustStoreFileChooser.setSelectedFile(file); } } if (trustStoreFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { final File selectedFile = trustStoreFileChooser.getSelectedFile(); trustStorePath = selectedFile.getAbsolutePath(); trustStoreFileChooserTextField.setText(selectedFile.getAbsolutePath()); } } }); }
Source:
<code>public void testTableFinish() { TableWriterNode.WriterTarget writerTarget = new TableWriterNode.WriterTarget() { @Override public String toString() { return null; } }; TableFinishNode tableFinishNode = new TableFinishNode( new PlanNodeId("1"), valuesNode, <START> writerTarget, <END> variableReferenceExpression, Optional.empty(), Optional.empty()); testValidation(tableFinishNode); }</code><technical_language>this variable replaced new TestingWriterTarget(),</technical_language>

Target:
public void testTableFinish() { TableFinishNode tableFinishNode = new TableFinishNode( new PlanNodeId("1"), valuesNode, new TestingWriterTarget(), VARIABLE_REFERENCE_EXPRESSION, Optional.empty(), Optional.empty()); testValidation(tableFinishNode); }
Source:
<code>public void onNewBatch(String topic, Cluster cluster, int prevPartition) { <START> synchronized (topicCounterMap) { <END> AtomicInteger counter = topicCounterMap.get(topic); topicCounterMap.put(topic, new AtomicInteger(counter.decrementAndGet())); } }</code><technical_language>replaced computeIfPresent</technical_language>

Target:
public void onNewBatch(String topic, Cluster cluster, int prevPartition) { topicCounterMap.computeIfPresent(topic, (k, v) -> new AtomicInteger(v.decrementAndGet())); }
Source:
<code>public void testImportSequenceFile_currentFormatWithHBase094Deserializer() throws Exception { String tableId = "test_" + UUID.randomUUID().toString(); File sequenceFile = tmpFolder.newFile(tableId); SequenceFileIoUtils.createFileWithData(sequenceFile, getTestData()); HBaseImportOptions options = createImportOptions( sequenceFile.getPath(), tableId, true ); options.setFilePattern(options.getFilePattern()); try (BigtableTableUtils tableUtils = tableUtilsFactory.createBigtableTableUtils( tableId, Bytes.toString(CF))) { assertFalse(tableUtils.isTableExists()); tableUtils.createEmptyTable(); try { doImport(options); fail("Expecting RuntimeException"); <START> } catch (RuntimeException expected) <END> } assertFalse(tableUtilsFactory.createBigtableTableUtils( tableId, Bytes.toString(CF)).isTableExists()); }</code><technical_language>nit: is a verify format error</technical_language>

Target:
public void testImportSequenceFile_currentFormatWithHBase094Deserializer() throws Exception { String tableId = "test_" + UUID.randomUUID().toString(); File sequenceFile = tmpFolder.newFile(tableId); SequenceFileIoUtils.createFileWithData(sequenceFile, getTestData()); HBaseImportOptions options = createImportOptions( sequenceFile.getPath(), tableId, true ); options.setFilePattern(options.getFilePattern()); try (BigtableTableUtils tableUtils = tableUtilsFactory.createBigtableTableUtils( tableId, Bytes.toString(CF))) { assertFalse(tableUtils.isTableExists()); tableUtils.createEmptyTable(); try { doImport(options); fail("Expecting failure."); } catch (Throwable expected) { } } assertFalse(tableUtilsFactory.createBigtableTableUtils( tableId, Bytes.toString(CF)).isTableExists()); }
Source:
<code>public ManagedClass infer(Class javaClass) { List<Property> properties = propertyScanner.scan(javaClass); Property foundIdProperty = findIdProperty(properties); if (foundIdProperty != null) { <START> logger.info("javersType type of " +javaClass.getSimpleName()+"(id:"+foundIdProperty.getName()+") inferred as Entity"); <END> return new Entity(javaClass, properties, foundIdProperty); } else { logger.info("javersType of " +javaClass.getSimpleName() + " inferred as ValueObject"); return new ValueObject(javaClass, properties); } }</code><technical_language><LINK_0></technical_language>

Target:
public ManagedClass infer(Class javaClass) { List<Property> properties = propertyScanner.scan(javaClass); Property foundIdProperty = findIdProperty(properties); if (foundIdProperty != null) { logger.info("javersType type of {}(id:{}) inferred as Entity", javaClass.getSimpleName(), foundIdProperty.getName()); return new Entity(javaClass, properties, foundIdProperty); } else { logger.info("javersType of inferred as ValueObject", javaClass.getSimpleName()); return new ValueObject(javaClass, properties); } }
Source:
<code>public void removeAllAttributes(PerunSession sess, UserExtSource ues) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException { List<Attribute> attributes = getAttributes(sess, ues); User user; try { user = getPerunBl().getUsersManagerBl().getUserByUserExtSource(sess, ues); } catch (UserNotExistsException ex) { throw new ConsistencyErrorException("Can't get user for userExtSource" + ues); } getAttributesManagerImpl().removeAllAttributes(sess, ues); <START> getPerunBl().getAuditer().log(sess, "All attributes removed for assigned to {}", ues, user); <END> for(Attribute attribute : attributes) attribute.setValue(null); try { checkAttributesValue(sess, ues, attributes); this.checkAttributesDependencies(sess, ues, null, attributes); } catch(WrongAttributeAssignmentException ex) { throw new ConsistencyErrorException(ex); } for(Attribute attribute: attributes) { try { getAttributesManagerImpl().changedAttributeHook(sess, ues, new Attribute(attribute)); } catch (WrongAttributeValueException ex) { throw new InternalErrorException(ex); } catch (WrongReferenceAttributeValueException ex) { throw new InternalErrorException(ex); } } }</code><technical_language>unnecessary redundant, User obtained UserExtSource</technical_language>

Target:
public void removeAllAttributes(PerunSession sess, UserExtSource ues) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException { List<Attribute> attributes = getAttributes(sess, ues); getAttributesManagerImpl().removeAllAttributes(sess, ues); getPerunBl().getAuditer().log(sess, "All attributes removed for {}", ues); for(Attribute attribute : attributes) attribute.setValue(null); try { checkAttributesValue(sess, ues, attributes); this.checkAttributesDependencies(sess, ues, null, attributes); } catch(WrongAttributeAssignmentException ex) { throw new ConsistencyErrorException(ex); } for(Attribute attribute: attributes) { try { getAttributesManagerImpl().changedAttributeHook(sess, ues, new Attribute(attribute)); } catch (WrongAttributeValueException ex) { throw new InternalErrorException(ex); } catch (WrongReferenceAttributeValueException ex) { throw new InternalErrorException(ex); } } }
Source:
<code>protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { fInitializationSucceeded = false; fInitialized.countDown(); return false; } IStatus status1 = totalsModule.schedule(); IStatus status2 = eventTypesModule.schedule(); if (!(status1.isOK() && status2.isOK())) { cancelSubAnalyses(); fInitializationSucceeded = false; fInitialized.countDown(); return false; } if (!totalsModule.waitForInitialization() || !eventTypesModule.waitForInitialization()) { fInitializationSucceeded = false; fInitialized.countDown(); return false; } ITmfStateSystem totalsSS = totalsModule.getStateSystem(); ITmfStateSystem eventTypesSS = eventTypesModule.getStateSystem(); if (totalsSS == null || eventTypesSS == null) { fInitializationSucceeded = false; fInitialized.countDown(); <START> throw new IllegalArgumentException("TmfStatisticsModule : Sub-modules initialization succeeded but there is a null state system."); END> } fStatistics = new TmfStateStatistics(totalsSS, eventTypesSS); fInitializationSucceeded = true; fInitialized.countDown(); if (!(totalsModule.waitForCompletion(monitor) && eventTypesModule.waitForCompletion(monitor))) { return false; } return true; }</code><technical_language>IllegalStateException, IllegalArgument</technical_language>

Target:
protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { fInitializationSucceeded = false; fInitialized.countDown(); return false; } IStatus status1 = totalsModule.schedule(); IStatus status2 = eventTypesModule.schedule(); if (!(status1.isOK() && status2.isOK())) { cancelSubAnalyses(); fInitializationSucceeded = false; fInitialized.countDown(); return false; } if (!totalsModule.waitForInitialization() || !eventTypesModule.waitForInitialization()) { fInitializationSucceeded = false; fInitialized.countDown(); return false; } ITmfStateSystem totalsSS = totalsModule.getStateSystem(); ITmfStateSystem eventTypesSS = eventTypesModule.getStateSystem(); if (totalsSS == null || eventTypesSS == null) { fInitializationSucceeded = false; fInitialized.countDown(); throw new IllegalStateException("TmfStatisticsModule : Sub-modules initialization succeeded but there is a null state system."); } fStatistics = new TmfStateStatistics(totalsSS, eventTypesSS); fInitializationSucceeded = true; fInitialized.countDown(); if (!(totalsModule.waitForCompletion(monitor) && eventTypesModule.waitForCompletion(monitor))) { return false; } return true; }
Source:
<code>protected void clearStorage(boolean onShutdown) { if (onShutdown) { NodeEngine nodeEngine = mapServiceContext.getNodeEngine(); NativeMemoryConfig nativeMemoryConfig = nodeEngine.getConfig().getNativeMemoryConfig(); boolean shouldClear = (nativeMemoryConfig != null && nativeMemoryConfig.getAllocatorType() != POOLED); if (shouldClear) { storage.clear(true); } storage.destroy(true); } else { storage.clear(false); } <START> mutationObserver.onClear(); <END> }</code><technical_language>clearStorage method is called places: - DefaultRecordStore#destroyInternals. method calls RecordStoreMutationObserver#onClear called twice. if change invocation in destroyInternals, invocations of observer - DefaultRecordStore#clearPartition. This in turn is called from: - DefaultRecordStore#destroy, invocation of observer, called - MapServiceContextImpl#clearMapsHavingLesserBackupCountThan MapServiceContextImpl#clearPartitionData is ok observer invocation in this path - PartitionContainer#clear is called MapServiceContextImpl#reset resetting map service MapServiceContext#shutdown is called shutting map service. This path ok. I problems facing invoking observer in cases: - DefaultRecordStore#destroyInternals -> clearStorage - DefaultRecordStore#destroy -> DefaultRecordStore#clearPartition -> clearStorage This need fixed. OTOH, if onClear is idempotent releases resources, leave called twice. This impact non-idempotent observers</technical_language>

Target:
protected void clearStorage(boolean onShutdown) { if (onShutdown) { NodeEngine nodeEngine = mapServiceContext.getNodeEngine(); NativeMemoryConfig nativeMemoryConfig = nodeEngine.getConfig().getNativeMemoryConfig(); boolean shouldClear = (nativeMemoryConfig != null && nativeMemoryConfig.getAllocatorType() != POOLED); if (shouldClear) { storage.clear(true); mutationObserver.onClear(); } storage.destroy(true); mutationObserver.onDestroy(true); } else { storage.clear(false); mutationObserver.onClear(); } }
Source:
<code>public Object execute(ExecutionEvent aEvent) throws ExecutionException { final GerritTableView reviewTableView = GerritTableView .getActiveView(); final TableViewer viewer = reviewTableView.getTableViewer(); final ISelection tableSelection = viewer.getSelection(); final Job job = new Job(COMMAND_MESSAGE) { @Override protected IStatus run(IProgressMonitor monitor) { <START> if (tableSelection.isEmpty()) { <END> GerritUi.Ftracer.traceInfo("Selected table selection is EMPTY " ); } else { if (tableSelection instanceof IStructuredSelection ) { Object obj = ((IStructuredSelection) tableSelection).getFirstElement(); if (obj instanceof GerritTask) { item = (GerritTask) obj; try { reviewTableView.setStarred(item.getTaskId(), !item.getStarred(), monitor); item.toggleStarred(GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item.getAttribute(GerritTask.IS_STARRED)))); } catch (CoreException e) { UIUtils.showErrorDialog(e.getMessage(), e.getStatus().getException().getMessage()); } Display.getDefault().asyncExec(new Runnable() { public void run() { viewer.update(item, null); } }); } } } return Status.OK_STATUS; }}; job.setUser(false); job.schedule(); return null; }</code><technical_language>handler is executed for empty selection</technical_language>

Target:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { final GerritTableView reviewTableView = GerritTableView.getActiveView(); final TableViewer viewer = reviewTableView.getTableViewer(); final ISelection tableSelection = viewer.getSelection(); if (tableSelection.isEmpty()) { GerritUi.Ftracer.traceInfo("Selected table selection is EMPTY "); return null; } final Job job = new Job(COMMAND_MESSAGE) { @Override protected IStatus run(IProgressMonitor monitor) { if (tableSelection instanceof IStructuredSelection) { Object obj = ((IStructuredSelection) tableSelection) .getFirstElement(); if (obj instanceof GerritTask) { item = (GerritTask) obj; try { reviewTableView.setStarred(item.getTaskId(), !item.getStarred(), monitor); item.setAttribute( GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item .getAttribute(GerritTask.IS_STARRED)))); } catch (CoreException e) { UIUtils.showErrorDialog(e.getMessage(), e .getStatus().getException().getMessage()); } Display.getDefault().asyncExec(new Runnable() { public void run() { viewer.update(item, null); } }); } } return Status.OK_STATUS; } }; job.setUser(false); job.schedule(); return null; }
Source:
<code>public static void addDisposableListChangeListener( final IListChangeListener listener, final IObservableList observable, Control control) { <START> Assert.isLegal(listener != null); <END> Assert.isLegal(observable != null); Assert.isLegal(control != null); if (control.isDisposed()) { return; } observable.addListChangeListener(listener); control.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { observable.removeListChangeListener(listener); } }); }</code><technical_language>Assert.isNotNull</technical_language>

Target:
public static void addDisposableListChangeListener( final IListChangeListener listener, final IObservableList observable, Control control) { Assert.isNotNull(listener); Assert.isNotNull(observable); Assert.isNotNull(control); if (control.isDisposed()) { return; } observable.addListChangeListener(listener); control.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { observable.removeListChangeListener(listener); } }); }
Source:
<code>public WPDeleteSitePreference(Context context, AttributeSet attrs) { super(context, attrs); mButtonTextColor = ContextCompat.getColor(context, R.color.black); <START> TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.WPIconWidgetPreference); <END> for (int i = 0; i < array.getIndexCount(); ++i) { int index = array.getIndex(i); if (index == R.styleable.WPDeleteSitePreference_buttonText) { mButtonText = array.getString(index); } else if (index == R.styleable.WPDeleteSitePreference_buttonTextColor) { mButtonTextColor = array.getColor(index, ContextCompat.getColor(context, R.color.black)); } else if (index == R.styleable.WPDeleteSitePreference_buttonTextAllCaps) { mButtonTextAllCaps = array.getBoolean(index, false); } } array.recycle(); }</code><technical_language>I this needs changed WPDeleteSitePreference</technical_language>

Target:
public WPDeleteSitePreference(Context context, AttributeSet attrs) { super(context, attrs); mButtonTextColor = ContextCompat.getColor(context, R.color.black); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.WPDeleteSitePreference); for (int i = 0; i < array.getIndexCount(); ++i) { int index = array.getIndex(i); if (index == R.styleable.WPDeleteSitePreference_buttonText) { mButtonText = array.getString(index); } else if (index == R.styleable.WPDeleteSitePreference_buttonTextColor) { mButtonTextColor = array.getColor(index, ContextCompat.getColor(context, R.color.black)); } else if (index == R.styleable.WPDeleteSitePreference_buttonTextAllCaps) { mButtonTextAllCaps = array.getBoolean(index, false); } } array.recycle(); }
Source:
<code>public static String createArrayFieldNameFromCountField(String countField){ <START> if(countField == null){ <END> return null; } if(!doesFieldNameMatchArrayCountPattern(countField)){ return countField; } return countField.substring(0, countField.length() - 1); }</code><technical_language>a single line is enough: if(doesFieldName...) return countField.substring(...) else countField</technical_language>

Target:
public static String createArrayFieldNameFromCountField(String countField){ if(doesFieldNameMatchArrayCountPattern(countField)){ return countField.substring(0, countField.length() - 1); } return countField; }
Source:
<code>public void forSuccessfulResponseByUrlPattern(final NetworkTrafficInterceptor trafficInterceptor, final String pattern) { changeImplicitWait(0, TimeUnit.SECONDS); try { wait.until( new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { HarEntry entry = trafficInterceptor.getMatchingEntryByUrlPatternFromHar(pattern); return entry != null && entry.getResponse().getStatus() < 400; } @Override public String toString() { <START> return "successful response matching pattern: " + pattern; <END> } } ); } finally { restoreDeaultImplicitWait(); } }</code><technical_language>This method called error. enhance error message</technical_language>

Target:
public void forSuccessfulResponseByUrlPattern(final NetworkTrafficInterceptor trafficInterceptor, final String pattern) { changeImplicitWait(0, TimeUnit.SECONDS); try { wait.until( new ExpectedCondition<Boolean>() { private HarEntry entry; @Override public Boolean apply(WebDriver webDriver) { entry = trafficInterceptor.getEntryByUrlPattern(pattern); return entry != null && entry.getResponse().getStatus() < 400; } @Override public String toString() { return entry == null ? String.format("sent request matching pattern: %s", pattern) : String.format("successful response (pattern: %s)", pattern); } } ); } finally { restoreDeaultImplicitWait(); } }
Source:
<code>protected boolean checkWireTransferTabState(DisbursementVoucherDocument dvDocument) { boolean tabStatesOK = true; PaymentSourceWireTransfer dvWireTransfer = dvDocument.getWireTransfer(); if ((StringUtils.equals(KFSConstants.PaymentSourceConstants.PAYMENT_METHOD_CHECK, dvDocument.getDisbVchrPaymentMethodCode()) || StringUtils.equals( KFSConstants.PaymentSourceConstants.PAYMENT_METHOD_DRAFT, dvDocument.getDisbVchrPaymentMethodCode())) && hasWireTransferValues(dvWireTransfer)) { String questionText = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString( <START> KFSKeyConstants.QUESTION_CLEAR_UNNEEDED_TAB); <END> boolean clearTab = super.askOrAnalyzeYesNoQuestion( KFSConstants.DisbursementVoucherDocumentConstants.CLEAR_WIRE_TRANSFER_TAB_QUESTION_ID, questionText); if (clearTab) { clearWireTransferValues(dvWireTransfer); } else { super.event.setActionForwardName(KFSConstants.MAPPING_BASIC); tabStatesOK = false; } } return tabStatesOK; }</code><technical_language>cu-kfs code QUESTION_CLEAR_UNNEEDED_WIRE_TAB instead of QUESTION_CLEAR_UNNEEDED_TAB. please confirm if code needs former</technical_language>

Target:
protected boolean checkWireTransferTabState(DisbursementVoucherDocument dvDocument) { boolean tabStatesOK = true; PaymentSourceWireTransfer dvWireTransfer = dvDocument.getWireTransfer(); if ((StringUtils.equals(KFSConstants.PaymentSourceConstants.PAYMENT_METHOD_CHECK, dvDocument.getDisbVchrPaymentMethodCode()) || StringUtils.equals( KFSConstants.PaymentSourceConstants.PAYMENT_METHOD_DRAFT, dvDocument.getDisbVchrPaymentMethodCode())) && hasWireTransferValues(dvWireTransfer)) { String questionText = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString( CUKFSKeyConstants.QUESTION_CLEAR_UNNEEDED_WIRE_TAB); boolean clearTab = super.askOrAnalyzeYesNoQuestion( KFSConstants.DisbursementVoucherDocumentConstants.CLEAR_WIRE_TRANSFER_TAB_QUESTION_ID, questionText); if (clearTab) { clearWireTransferValues(dvWireTransfer); } else { super.event.setActionForwardName(KFSConstants.MAPPING_BASIC); tabStatesOK = false; } } return tabStatesOK; }
Source:
<code>public void testPaginationWatch() throws Exception { final String testId = UUID.randomUUID().toString(); final String basePath = "/testPaginationWatch-" + testId; createChildren(basePath, 10, 0); long minZkId = -1; final int pageSize = 3; int pageCount = 0; MyWatcher myWatcher = new MyWatcher(); while (true) { final List<PathWithStat> page = zk.getChildrenPaginated(basePath, myWatcher, pageSize, minZkId); if(page.isEmpty()) { break; } if(pageCount < 3) { String childPath = basePath + "/" + "before-pagination-" + pageCount; zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } for (PathWithStat pathWithStat : page) { final String nodePath = pathWithStat.getPath(); LOG.info("Read: " + nodePath); final Stat nodeStat = pathWithStat.getStat(); Assert.assertTrue(nodeStat.getCzxid() > minZkId); minZkId = nodeStat.getCzxid(); } pageCount += 1; } { String childPath = basePath + "/" + "after-pagination"; zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } while (true) { if(!myWatcher.watchFired) { LOG.info("Watch did not fire yet"); Thread.sleep(1000); } else { LOG.info("Watch fired"); break; } } <START> Thread.sleep(1000); <END> Assert.assertTrue(myWatcher.watchFired); }</code><technical_language>of logic instead of timed sleeping</technical_language>

Target:
public void testPaginationWatch() throws Exception { final String testId = UUID.randomUUID().toString(); final String basePath = "/testPaginationWatch-" + testId; createChildren(basePath, 10, 0); long minCzxId = -1; final int pageSize = 3; FireOnlyOnceWatcher fireOnlyOnceWatcher = new FireOnlyOnceWatcher(); RemoteIterator<PathWithStat> it = zk.getChildrenIterator(basePath, fireOnlyOnceWatcher, pageSize, minCzxId); int childrenIndex = 0; while (it.hasNext()) { ++childrenIndex; PathWithStat pathWithStat = it.next(); final String nodePath = pathWithStat.getPath(); LOG.info("Read: " + nodePath); final Stat nodeStat = pathWithStat.getStat(); Assert.assertTrue(nodeStat.getCzxid() > minCzxId); minCzxId = nodeStat.getCzxid(); if(childrenIndex < 6) { String childPath = basePath + "/" + "before-pagination-" + childrenIndex; zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if(childrenIndex % pageSize == 0) { zk.setData(basePath + "/" + pathWithStat.getPath(), new byte[3], -1); } synchronized (fireOnlyOnceWatcher) { Assert.assertEquals("Watch should not have fired yet", 0, fireOnlyOnceWatcher.watchFiredCount); } } { String childPath = basePath + "/" + "after-pagination"; zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } while (true) { synchronized (fireOnlyOnceWatcher) { if (fireOnlyOnceWatcher.watchFiredCount > 0) { Assert.assertEquals("Watch should have fired once", 1, fireOnlyOnceWatcher.watchFiredCount); break; } fireOnlyOnceWatcher.wait(1000); } } synchronized (fireOnlyOnceWatcher) { fireOnlyOnceWatcher.wait(1000); Assert.assertEquals("Watch should have fired once", 1, fireOnlyOnceWatcher.watchFiredCount); } }
Source:
<code>default <U> Seq<U> traverse(BiFunction<K, V, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); <START> return foldLeft(Stream.empty(), (acc, entry) -> acc.append(mapper.apply(entry._1, entry._2))); <END> }</code><technical_language>foldLeft is lazy, please implement this: java default <U> Seq<U> traverse(BiFunction<K, V, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return iterator().<U> map(entry -> mapper.apply(entry._1, entry._2)).toStream(); }</technical_language>

Target:
default <U> Seq<U> traverse(BiFunction<K, V, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return foldLeft(Vector.empty(), (acc, entry) -> acc.append(mapper.apply(entry._1, entry._2))); }
Source:
<code>public void connect(Action1<? super Subscription> connection) { boolean shouldSubscribe = false; synchronized (guard) { if (subscription != null) { connection.call(guardedSubscription); return; } else { shouldSubscribe = true; final Subject<? super T, ? extends R> subject = subjectFactory.call(); subscription = new Subscriber<T>() { @Override public void onCompleted() { subject.onCompleted(); } @Override public void onError(Throwable e) { subject.onError(e); } @Override public void onNext(T args) { subject.onNext(args); } }; guardedSubscription = Subscriptions.create(new Action0() { @Override public void call() { Subscription s; synchronized (guard) { <START> s = subscription; <END> subscription = null; guardedSubscription = null; connectedSubject.set(null); } if (s != null) { s.unsubscribe(); } } }); for(Subscriber<? super R> s : waitingForConnect) { subject.unsafeSubscribe(s); } waitingForConnect.clear(); connectedSubject.set(subject); } } if (shouldSubscribe) { connection.call(guardedSubscription); Subscriber<T> sub; synchronized (guard) { sub = subscription; } if (sub != null) source.subscribe(sub); } }</code><technical_language>check if guardedSubscription == this avoid unsubscribing a newer connection, i.e.: java Subscription s1 = src.connect(); Subscription s2 = src.connect(); s1.unsubscribe(); Subscription s3 = src.connect(); s2.unsubscribe(); // src connected</technical_language>

Target:
public void connect(Action1<? super Subscription> connection) { synchronized (guard) { if (subscription != null) { connection.call(guardedSubscription); return; } else { final Subject<? super T, ? extends R> subject = subjectFactory.call(); subscription = new Subscriber<T>() { @Override public void onCompleted() { subject.onCompleted(); } @Override public void onError(Throwable e) { subject.onError(e); } @Override public void onNext(T args) { subject.onNext(args); } }; final AtomicReference<Subscription> gs = new AtomicReference<Subscription>(); gs.set(Subscriptions.create(new Action0() { @Override public void call() { Subscription s; synchronized (guard) { if ( guardedSubscription == gs.get()) { s = subscription; subscription = null; guardedSubscription = null; connectedSubject.set(null); } else return; } if (s != null) { s.unsubscribe(); } } })); guardedSubscription = gs.get(); for(Subscriber<? super R> s : waitingForConnect) { subject.unsafeSubscribe(s); } waitingForConnect.clear(); connectedSubject.set(subject); } } connection.call(guardedSubscription); Subscriber<T> sub; synchronized (guard) { sub = subscription; } if (sub != null) source.subscribe(sub); }
Source:
<code>public static Set<Symbol> globalSymbols(FileInput fileInput, String packageName, PythonFile pythonFile) { SymbolTableBuilder symbolTableBuilder = new SymbolTableBuilder(packageName, pythonFile); String fullyQualifiedModuleName = SymbolUtils.fullyQualifiedModuleName(packageName, pythonFile.fileName()); fileInput.accept(symbolTableBuilder); Set<Symbol> globalSymbols = new HashSet<>(); for (Symbol globalVariable : fileInput.globalVariables()) { if (globalVariable.kind() == Symbol.Kind.CLASS) { String fullyQualifiedVariableName = globalVariable.fullyQualifiedName(); if (fullyQualifiedVariableName != null && fullyQualifiedVariableName.startsWith(fullyQualifiedModuleName)) { globalSymbols.add(((ClassSymbolImpl) globalVariable).copyWithoutUsages()); } else { <START> globalSymbols.add(((ClassSymbolImpl) globalVariable).copyWithPrefix(fullyQualifiedModuleName)); <END> } } else if (globalVariable.kind() == Symbol.Kind.FUNCTION) { globalSymbols.add(new FunctionSymbolImpl(fullyQualifiedModuleName, globalVariable.name(), ((FunctionSymbol) globalVariable))); } else { globalSymbols.add(new SymbolImpl(globalVariable.name(), fullyQualifiedModuleName + "." + globalVariable.name())); } } return globalSymbols; }</code><technical_language>I this approach. avoid adding "imported" symbols instead</technical_language>

Target:
public static Set<Symbol> globalSymbols(FileInput fileInput, String packageName, PythonFile pythonFile) { SymbolTableBuilder symbolTableBuilder = new SymbolTableBuilder(packageName, pythonFile); String fullyQualifiedModuleName = SymbolUtils.fullyQualifiedModuleName(packageName, pythonFile.fileName()); fileInput.accept(symbolTableBuilder); Set<Symbol> globalSymbols = new HashSet<>(); for (Symbol globalVariable : fileInput.globalVariables()) { String fullyQualifiedVariableName = globalVariable.fullyQualifiedName(); if (((fullyQualifiedVariableName != null) && !fullyQualifiedVariableName.startsWith(fullyQualifiedModuleName)) || globalVariable.usages().stream().anyMatch(u -> u.kind().equals(Usage.Kind.IMPORT))) { continue; } if (globalVariable.kind() == Symbol.Kind.CLASS) { globalSymbols.add(((ClassSymbolImpl) globalVariable).copyWithoutUsages()); } else if (globalVariable.kind() == Symbol.Kind.FUNCTION) { globalSymbols.add(new FunctionSymbolImpl(globalVariable.name(), ((FunctionSymbol) globalVariable))); } else { globalSymbols.add(new SymbolImpl(globalVariable.name(), fullyQualifiedModuleName + "." + globalVariable.name())); } } return globalSymbols; }
Source:
<code>public static IBiomeBlockReplacerProvider provider() { return new IBiomeBlockReplacerProvider() { private final ResourceLocation OCEAN_BLOCK = CubicChunks.location("ocean_block"); <START> private final ResourceLocation OCEAN_HEIGHT = CubicChunks.location("ocean_height"); <END> @Override public IBiomeBlockReplacer create(ICubicWorld world, CubicBiomeType biome, BiomeBlockReplacerConfig conf) { IBlockState oceanBlock = Block.getBlockFromName(conf.getString(OCEAN_BLOCK)).getDefaultState(); int oceanHeight = conf.getInt(OCEAN_HEIGHT); return new OceanWaterReplacer(oceanBlock, oceanHeight); } @Override public Set<ConfigOptionInfo> getPossibleConfigOptions() { return Sets.newHashSet( new ConfigOptionInfo(OCEAN_BLOCK, Blocks.WATER.getRegistryName().toString()), new ConfigOptionInfo(OCEAN_HEIGHT, 63) ); } }; }</code><technical_language>oceanHeight</technical_language>

Target:
public static IBiomeBlockReplacerProvider provider() { return new IBiomeBlockReplacerProvider() { private final ResourceLocation OCEAN_BLOCK = CubicChunks.location("ocean_block"); private final ResourceLocation OCEAN_LEVEL = CubicChunks.location("ocean_level"); @Override public IBiomeBlockReplacer create(ICubicWorld world, CubicBiome biome, BiomeBlockReplacerConfig conf) { IBlockState oceanBlock = Block.getBlockFromName(conf.getString(OCEAN_BLOCK)).getDefaultState(); int oceanHeight = conf.getInt(OCEAN_LEVEL); return new OceanWaterReplacer(oceanBlock, oceanHeight); } @Override public Set<ConfigOptionInfo> getPossibleConfigOptions() { return Sets.newHashSet( new ConfigOptionInfo(OCEAN_BLOCK, Blocks.WATER.getRegistryName().toString()), new ConfigOptionInfo(OCEAN_LEVEL, 63) ); } }; }
Source:
<code>public static void main(String[] args) throws Exception { if(args.length < 1) { usage(); return; } try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) { String chartTitle = modelReader.readLine(); String[] series = modelReader.readLine().split(","); List<String> listLanguages = new ArrayList<>(10); List<Double> listCountries = new ArrayList<>(10); List<Double> listSpeakers = new ArrayList<>(10); String ln; while((ln = modelReader.readLine()) != null) { String[] vals = ln.split(","); listCountries.add(Double.valueOf(vals[0])); listSpeakers.add(Double.valueOf(vals[1])); listLanguages.add(vals[2]); } String[] categories = listLanguages.toArray(new String[listLanguages.size()]); Double[] values1 = listCountries.toArray(new Double[listCountries.size()]); Double[] values2 = listSpeakers.toArray(new Double[listSpeakers.size()]); try (XWPFDocument doc = new XWPFDocument()) { <START> XWPFChart chart = doc.createChart(5000000,5000000); <END> setBarData(chart, chartTitle, series, categories, values1, values2); try (OutputStream out = new FileOutputStream("bar-chart-demo-output.docx")) { doc.write(out); } } catch(Exception e) { e.printStackTrace(); } } System.out.println("Done"); }</code><technical_language>Please XDDFChart.DEFAULT_WIDTH XDDFChart.DEFAULT_HEIGHT instead of magic numbers</technical_language>

Target:
public static void main(String[] args) throws Exception { if(args.length < 1) { usage(); return; } try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) { String chartTitle = modelReader.readLine(); String[] series = modelReader.readLine().split(","); List<String> listLanguages = new ArrayList<>(10); List<Double> listCountries = new ArrayList<>(10); List<Double> listSpeakers = new ArrayList<>(10); String ln; while((ln = modelReader.readLine()) != null) { String[] vals = ln.split(","); listCountries.add(Double.valueOf(vals[0])); listSpeakers.add(Double.valueOf(vals[1])); listLanguages.add(vals[2]); } String[] categories = listLanguages.toArray(new String[listLanguages.size()]); Double[] values1 = listCountries.toArray(new Double[listCountries.size()]); Double[] values2 = listSpeakers.toArray(new Double[listSpeakers.size()]); try (XWPFDocument doc = new XWPFDocument()) { XWPFChart chart = doc.createChart(XDDFChart.DEFAULT_WIDTH, XDDFChart.DEFAULT_HEIGHT); setBarData(chart, chartTitle, series, categories, values1, values2); try (OutputStream out = new FileOutputStream("bar-chart-demo-output.docx")) { doc.write(out); } } catch(Exception e) { e.printStackTrace(); } } System.out.println("Done"); }
Source:
<code>protected void updateValidityChecks(ActionsViewTable viewTable) { List<ScriptGeneratorAction> actions = scriptGeneratorModel.getActions(); TableItem[] items = viewTable.table().getItems(); int validityColumnIndex = viewTable.table().getColumnCount()-1; for (int i = 0; i < actions.size(); i++) { if (actions.get(i).isValid()) { <START> items[i].setBackground(clearColor); <END> items[i].setBackground(validityColumnIndex, validColor); } else { items[i].setBackground(invalidLightColor); items[i].setBackground(validityColumnIndex, invalidDarkColor); } } }</code><technical_language>Need bounds checks here</technical_language>

Target:
protected void updateValidityChecks(ActionsViewTable viewTable) { List<ScriptGeneratorAction> actions = scriptGeneratorModel.getActions(); TableItem[] items = viewTable.table().getItems(); int validityColumnIndex = viewTable.table().getColumnCount()-1; for (int i = 0; i < actions.size(); i++) { if(i < items.length) { if (!scriptGeneratorModel.languageSupported) { items[i].setBackground(lightValidityCheckErrorColor); items[i].setBackground(validityColumnIndex, darkValidityCheckErrorColor); } else if (actions.get(i).isValid()) { items[i].setBackground(clearColor); items[i].setBackground(validityColumnIndex, validColor); } else { items[i].setBackground(invalidLightColor); items[i].setBackground(validityColumnIndex, invalidDarkColor); } } else { LOG.warn("ScriptGeneratorViewModel - ActionsTable and UI Table mismatch"); } } }
Source:
<code>public void addSpiceUsbControllers(Guid vmId, int numberOfControllers) { VmBase vmBase = getVmBase(vmId); if (vmBase.getBiosType().getChipsetType() == ChipsetType.Q35) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, createSingleUsbControllerSpecParams(Q35_MODEL), true, false); <START> } else { <END> for (int index = 0; index < numberOfControllers; index++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, getSpiceUsbControllerSpecParams(EHCI_MODEL, 1, index), true, false); for (int companionIndex = 1; companionIndex <= COMPANION_USB_CONTROLLERS; companionIndex++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, getSpiceUsbControllerSpecParams(UHCI_MODEL, companionIndex, index), true, false); } } } }</code><technical_language>// For EHCI controller need create companion UHCI controllers</technical_language>

Target:
public void addSpiceUsbControllers(Guid vmId, int numberOfControllers) { VmBase vmBase = getVmBase(vmId); if (vmBase.getBiosType().getChipsetType() == ChipsetType.Q35) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, createSingleUsbControllerSpecParams(XHCI_MODEL), true, false); } else { for (int index = 0; index < numberOfControllers; index++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, createSpiceUsbControllerSpecParams(EHCI_MODEL, 1, index), true, false); for (int companionIndex = 1; companionIndex <= COMPANION_USB_CONTROLLERS; companionIndex++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, createSpiceUsbControllerSpecParams(UHCI_MODEL, companionIndex, index), true, false); } } } }
Source:
<code>public void fillMsqMaxSelectableChoices(int qnNumber, String value) { WebElement inputBox = getMsqMaxSelectableChoicesBox(qnNumber); String id = inputBox.getAttribute("id"); <START> fillTextBox(browser.driver.findElement(By.id(id)), value); <END> }</code><technical_language>i replace browser.driver.findElement(By.id(id)) inputBox</technical_language>

Target:
public void fillMsqMaxSelectableChoices(int qnNumber, String value) { WebElement inputBox = getMsqMaxSelectableChoicesBox(qnNumber); fillTextBox(inputBox, value); executeScript("$(arguments[0]).change();", inputBox); }
Source:
<code>public static Comparator<TurboIssue> getSortComparator(IModel model, String key, boolean inverted, boolean metadataRefresh) { Comparator<TurboIssue> comparator = (a, b) -> 0; boolean isLabelGroup = false; switch (key) { case "comments": comparator = (a, b) -> a.getCommentCount() - b.getCommentCount(); break; case "repo": comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId()); break; case "updated": case "date": comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt()); break; <START> case "nonselfupdate": <END> if (metadataRefresh) { comparator = (a, b) -> b.getMetadata().getNonSelfUpdatedAt().compareTo(a.getMetadata().getNonSelfUpdatedAt()); } else { comparator = (a, b) -> b.getUpdatedAt().compareTo(a.getUpdatedAt()); } break; case "id": comparator = (a, b) -> a.getId() - b.getId(); break; default: isLabelGroup = true; break; } if (isLabelGroup) { return getLabelGroupComparator(model, key, inverted); } else { if (!inverted) { return comparator; } else { final Comparator<TurboIssue> finalComparator = comparator; return (a, b) -> -finalComparator.compare(a, b); } } }</code><technical_language>camel case? Easier read way</technical_language>

Target:
public static Comparator<TurboIssue> getSortComparator(IModel model, String key, boolean inverted, boolean metadataRefresh) { Comparator<TurboIssue> comparator = (a, b) -> 0; boolean isLabelGroup = false; switch (key) { case "comments": comparator = (a, b) -> a.getCommentCount() - b.getCommentCount(); break; case "repo": comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId()); break; case "updated": case "date": comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt()); break; case "nonSelfUpdate": if (metadataRefresh) { comparator = (a, b) -> a.getMetadata().getNonSelfUpdatedAt().compareTo(b.getMetadata().getNonSelfUpdatedAt()); } else { comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt()); } break; case "id": comparator = (a, b) -> a.getId() - b.getId(); break; default: isLabelGroup = true; break; } if (isLabelGroup) { return getLabelGroupComparator(model, key, inverted); } else { if (!inverted) { return comparator; } else { final Comparator<TurboIssue> finalComparator = comparator; return (a, b) -> -finalComparator.compare(a, b); } } }
Source:
<code>public void testCreate() throws Exception { String testUserName = "test-user"; UserDto user = new UserDto(); user.setEnabled(true); user.setUsername(testUserName); user.setPassword("test-password"); user.setSecurityTokenKey("some-security-token"); userService.save(new EncodedPasswordUser(user, passwordEncoder)); User foundEntity = userService.findByUsername(testUserName); assertThat(foundEntity).as("Unable to locate user " + testUserName + ". Save operation failed!").isNotNull(); <START> logger.debug("Found stored user\n\t{}\n", foundEntity); <END> assertThat(foundEntity.getUsername()).isEqualTo(testUserName); assertThat(foundEntity.getPassword()) .as("Expected a hashed password, received plain-text!") .isNotEqualTo("test-password"); assertThat(foundEntity.getPassword()).as("User contains empty password!").isNotNull(); assertThat(foundEntity.isEnabled()).isTrue(); assertThat(foundEntity.getSecurityTokenKey()).isEqualTo("some-security-token"); }</code><technical_language>Please, remove tabs break lines, leave this: "Found stored user: {}"</technical_language>

Target:
public void testCreate() throws Exception { String testUserName = "test-user"; UserDto user = new UserDto(); user.setEnabled(true); user.setUsername(testUserName); user.setPassword("test-password"); user.setSecurityTokenKey("some-security-token"); userService.save(new EncodedPasswordUser(user, passwordEncoder)); User foundEntity = userService.findByUsername(testUserName); assertThat(foundEntity).as("Unable to locate user " + testUserName + ". Save operation failed!").isNotNull(); logger.debug("Found stored user: {}", foundEntity); assertThat(foundEntity.getUsername()).isEqualTo(testUserName); assertThat(foundEntity.getPassword()) .as("Expected a hashed password, received plain-text!") .isNotEqualTo("test-password"); assertThat(foundEntity.getPassword()).as("User contains empty password!").isNotNull(); assertThat(foundEntity.isEnabled()).isTrue(); assertThat(foundEntity.getSecurityTokenKey()).isEqualTo("some-security-token"); }
Source:
<code>public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf msgBuf = (ByteBuf) msg; <START> if (msgBuf.getByte(msgBuf.readerIndex()) == 0x1) { <END> ctx.fireChannelRead(msgBuf); return; } msgBuf.readByte(); ByteBufInputStream msgInputStream = new ByteBufInputStream(msgBuf); try { Request request = Request.parseFrom(msgInputStream); Header header = request.getHeader(); if (log.isDebugEnabled()) { log.debug("Request pi from {}", header.getType(), ctx.channel().remoteAddress()); } AbstractServer handler = handlerMap.get(header.getType()); if (handler == null) { log.warn("Received unregistered message {}, dropping", header.getType()); } else { try { handler.handleRequest(request, ctx, this); } catch(Throwable t) { log.error("channelRead: Handling failed due to {}:{}", header.getType(),t.getClass().getSimpleName(), t.getMessage(), t); } } } catch (Exception e) { log.error("Exception during read!", e); } finally { msgInputStream.close(); msgBuf.release(); } }</code><technical_language>static constants (i.e. 0x1 0x2)</technical_language>

Target:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf msgBuf = (ByteBuf) msg; byte msgMark = msgBuf.getByte(msgBuf.readerIndex()); if (msgMark == API.LEGACY_CORFU_MSG_MARK) { ctx.fireChannelRead(msgBuf); return; } else if(msgMark != API.PROTO_CORFU_MSG_MARK) { throw new IllegalStateException("Received incorrectly marked message."); } msgBuf.readByte(); ByteBufInputStream msgInputStream = new ByteBufInputStream(msgBuf); try { Request request = Request.parseFrom(msgInputStream); Header header = request.getHeader(); if (log.isDebugEnabled()) { log.debug("channelRead: Request from {}", header.getType(), ctx.channel().remoteAddress()); } AbstractServer handler = handlerMap.get(header.getType()); if (handler == null) { log.warn("channelRead: Received unregistered request {}, dropping", header.getType()); } else { if(requestIsValid(request, ctx)) { if(log.isTraceEnabled()) { log.trace("channelRead: Request routed to {}: {}", handler.getClass().getSimpleName(), request); } try { handler.handleRequest(request, ctx, this); } catch(Throwable t) { log.error("channelRead: Handling failed due to {}:{}", header.getType(), t.getClass().getSimpleName(), t.getMessage(), t); } } } } catch (Exception e) { log.error("channelRead: Exception during read!", e); } finally { msgInputStream.close(); msgBuf.release(); } }
Source:
<code>public void Search() { if (getEntity() != null) { AsyncDataProvider.GetVmsRunningOnOrMigratingToVds(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { @SuppressWarnings("unchecked") <START> ArrayList<VM> list = (ArrayList<VM>) returnValue; <END> HostVmListModel model = (HostVmListModel) target; model.setItems(list); } }), getEntity().getId()); } else { setItems(new ArrayList<VM>()); } }</code><technical_language>is a chance returnValue is null? if yes, converter a perfect place handle it..</technical_language>

Target:
public void Search() { if (getEntity() != null) { AsyncDataProvider.GetVmsRunningOnOrMigratingToVds(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { @SuppressWarnings("unchecked") final ArrayList<VM> list = (ArrayList<VM>) returnValue; final HostVmListModel model = (HostVmListModel) target; model.setItems(list); } }), getEntity().getId()); } else { setItems(new ArrayList<VM>()); } }