auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static Map<String, Properties> getIntermediateStreamProperties(Config config) { Map<String, Properties> intermedidateStreamProperties = Collections.emptyMap(); ApplicationConfig appConfig = new ApplicationConfig(config); if (appConfig.getAppMode() == ApplicationConfig.ApplicationMode.BATCH) { StreamConfig streamConfig = new StreamConfig(config); intermedidateStreamProperties = JavaConverters.asJavaCollectionConverter(streamConfig.getStreamIds()) .asJavaCollection() .stream() .filter(streamConfig::getIsIntermediateStream) .collect(Collectors.toMap(Function.identity(), streamId -> { Properties properties = new Properties(); properties.putAll(streamConfig.getStreamProperties(streamId)); properties.putIfAbsent("retention.ms", String.valueOf(KafkaConfig.DEFAULT_RETENTION_MS_FOR_BATCH())); return properties; })); } return intermedidateStreamProperties; }

Target:
static Map<String, Properties> getIntermediateStreamProperties(Config config) { Map<String, Properties> intermedidateStreamProperties = Collections.emptyMap(); ApplicationConfig appConfig = new ApplicationConfig(config); if (appConfig.getAppMode() == ApplicationConfig.ApplicationMode.BATCH) { StreamConfig streamConfig = new StreamConfig(config); intermedidateStreamProperties = JavaConverters.asJavaCollectionConverter(streamConfig.getStreamIds()) .asJavaCollection() .stream() .filter(streamConfig::getIsIntermediateStream) .collect(Collectors.toMap(Function.identity(), streamId -> { Properties properties = new Properties(); properties.putAll(streamConfig.getStreamProperties(streamId)); properties.putIfAbsent(TopicConfig.RETENTION_MS_CONFIG, String.valueOf(KafkaConfig.DEFAULT_RETENTION_MS_FOR_BATCH())); return properties; })); } return intermedidateStreamProperties; }
Source:
public void testCallsiteCopy2() { try { new TmfCallsite(null); fail("null copy"); } catch (final IllegalArgumentException e) { } }

Target:
public void testCallsiteCopy2() { new TmfCallsite(null); }
Source:
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) { worker.execute(); }

Target:
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) { String queryParam = "startId"; Long startId = 1L; if (parameters.containsKey(queryParam)) { startId = Long.valueOf(parameters.get(queryParam).asList().get(0)); } worker.execute(startId); }
Source:
public void init() throws APIManagerIntegrationTestException, APIManagementException, IOException { setupUserData(); apiStore = new APIStoreRestClient(storeURL); apiStore.login(SUPER_USER, SUPER_USER_LOGIN_PW); apiPublisher = new APIPublisherRestClient(publisherURL); apiPublisher.login(SUPER_USER, SUPER_USER_LOGIN_PW); apiPublisherAdmin = new APIPublisherRestClient(publisherURL); apiPublisherAdmin.login(ADMIN_LOGIN_USERNAME, ADMIN_LOGIN_PW); String swaggerFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "swaggerFiles" + File.separator + "APIScopeTest1.json"; File swaggerFile = new File(swaggerFilePath); String swaggerContent = readFromFile(swaggerFile.getAbsolutePath()); JSONObject swaggerJson = new JSONObject(swaggerContent); try { apiPublisher.developSampleAPI(swaggerJson, SUPER_USER, backendEndPoint, true, apiVisibility); } catch (Exception ex) { log.error("API publication failed", ex); } }

Target:
public void init() throws Exception { setupUserData(); apiStore = new APIStoreRestClient(storeURL); apiStore.login(SUPER_USER, SUPER_USER_LOGIN_PW); apiPublisher = new APIPublisherRestClient(publisherURL); apiPublisher.login(SUPER_USER, SUPER_USER_LOGIN_PW); apiPublisherAdmin = new APIPublisherRestClient(publisherURL); apiPublisherAdmin.login(ADMIN_LOGIN_USERNAME, ADMIN_LOGIN_PW); String swaggerFilePath = resourceLocation + "swaggerFiles" + File.separator + "APIScopeTest1.json"; File swaggerFile = new File(swaggerFilePath); String swaggerContent = readFromFile(swaggerFile.getAbsolutePath()); JSONObject swaggerJson = new JSONObject(swaggerContent); try { apiPublisher.developSampleAPI(swaggerJson, SUPER_USER, backendEndPoint, true, apiVisibility); } catch (Exception ex) { log.error("API publication failed", ex); } }
Source:
public void onCreate(Bundle savedInstanceState) { String currentTheme = ThemeHelper.getSelectedTheme(this); if(currentTheme.equals("light_theme")) { this.setTheme(R.style.FilePickerThemeLight); } else { this.setTheme(R.style.FilePickerThemeDark); } super.onCreate(savedInstanceState); }

Target:
public void onCreate(Bundle savedInstanceState) { if(ThemeHelper.isLightThemeSelected(this)) { this.setTheme(R.style.FilePickerThemeLight); } else { this.setTheme(R.style.FilePickerThemeDark); } super.onCreate(savedInstanceState); }
Source:
public FbStatus(final int code) { this(new Condition<Integer>() { @Override public boolean fits(final Integer status) { return code == status; } }); }

Target:
public FbStatus(final int code) { this(new Condition<Integer>() { @Override public boolean fits(final Integer status) { return code == status.intValue(); } }); }
Source:
public void testAddAccount() throws Exception { accountDao.addAccount(testAccount); }

Target:
public void testAddAccount() throws Exception { accountDao.addAccount(testAccount); verify(mockConnection).prepareStatement(anyString()); accountDao.addAccount(testAccount); verify(mockConnection).prepareStatement(anyString()); }
Source:
public void reloadComponents() { componentTables.clear(); for (ComponentTableProvider provider : extensionStorage.getComponentTableProviders()) { ComponentTable<?> table = provider.provide(sceneMC); componentTables.add(table); table.setProperties(this); } componentSelectDialog.getComponentClasses().clear(); for (UserAddableComponentProvider provider : extensionStorage.getUserAddableComponentProviders()) { componentSelectDialog.getComponentClasses().add(provider.provide()); } this.rebuildPropertiesTable(); }

Target:
public void reloadComponents() { reloadComponentTables(); componentSelectDialog.reloadComponents(); rebuildPropertiesTable(); }
Source:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongAttributeAssignmentException, InternalErrorException, WrongReferenceAttributeValueException { try { if (attribute.valueAsString().equals("true")) { Attribute requiredAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GroupsManager.GROUPMEMBERSQUERY_ATTRNAME); if (requiredAttribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, requiredAttribute, group, null, group, null, requiredAttribute.toString() + " must be set in order to enable synchronization."); } requiredAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GroupsManager.GROUPEXTSOURCE_ATTRNAME); if (requiredAttribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, requiredAttribute, group, null, group, null, requiredAttribute.toString() + " must be set in order to enable synchronization."); } } } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException(e); } }

Target:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongAttributeAssignmentException, InternalErrorException, WrongReferenceAttributeValueException { if (attribute.getValue() == null) return; try { if (attribute.valueAsString().equals("true")) { Attribute requiredAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GroupsManager.GROUPMEMBERSQUERY_ATTRNAME); if (requiredAttribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, requiredAttribute, group, null, group, null, requiredAttribute.toString() + " must be set in order to enable synchronization."); } requiredAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GroupsManager.GROUPEXTSOURCE_ATTRNAME); if (requiredAttribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, requiredAttribute, group, null, group, null, requiredAttribute.toString() + " must be set in order to enable synchronization."); } } } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException(e); } }
Source:
protected void doPostProcessingForSuccesfulSend() throws InvalidParametersException, EntityDoesNotExistException { FeedbackSessionAttributes feedbackObject = FeedbackSessionsLogic.inst() .getFeedbackSession(feedbackSessionName, courseId); feedbackObject.setPublishedEmailEnabled(false); FeedbackSessionsLogic.inst().updateFeedbackSession(feedbackObject); }

Target:
protected void doPostProcessingForSuccesfulSend() throws InvalidParametersException, EntityDoesNotExistException { FeedbackSessionAttributes feedbackSession = FeedbackSessionsLogic.inst() .getFeedbackSession(feedbackSessionName, courseId); feedbackSession.setSentPublishedEmail(false); FeedbackSessionsLogic.inst().updateFeedbackSession(feedbackSession); }
Source:
private boolean internalValidateAndSetQuota() { if (isInternalExecution()) { return true; } if (getStoragePool() == null) { throw new InvalidQuotaParametersException("Command: " + this.getClass().getName() + ". Storage pool is not available for quota calculation. "); } QuotaConsumptionParametersWrapper quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper(this, getReturnValue().getCanDoActionMessages()); quotaConsumptionParametersWrapper.setParameters(getQuotaConsumptionParameters()); if (quotaConsumptionParametersWrapper.getParameters() == null) { throw new InvalidQuotaParametersException("Command: " + this.getClass().getName() + ". No Quota parameters available."); } boolean result = true; setQuotaWasChanged(result); return result; }

Target:
private boolean internalValidateAndSetQuota() { if (isInternalExecution()) { return true; } if (getStoragePool() == null) { throw new InvalidQuotaParametersException("Command: " + this.getClass().getName() + ". Storage pool is not available for quota calculation. "); } QuotaConsumptionParametersWrapper quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper(this, getReturnValue().getCanDoActionMessages()); quotaConsumptionParametersWrapper.setParameters(getQuotaConsumptionParameters()); if (quotaConsumptionParametersWrapper.getParameters() == null) { throw new InvalidQuotaParametersException("Command: " + this.getClass().getName() + ". No Quota parameters available."); } boolean result = true; setQuotaChanged(result); return result; }
Source:
public void ensurePath(String path, boolean excludingLast) throws KeeperException { reporter.time(tag, "ensurePath", (ZooKeeperCallable<Void>) () -> { client.ensurePath(path, excludingLast); return null; }); }

Target:
public void ensurePath(String path, boolean excludingLast) throws KeeperException { reporter.time(tag, "ensurePath", () -> { client.ensurePath(path, excludingLast); return null; }); }
Source:
protected void executeCommand() { StoragePoolIsoMap map = loadStoragePoolIsoMap(); changeDomainStatusWithCompensation(map, StorageDomainStatus.Unknown, StorageDomainStatus.Locked, getCompensationContext()); if (shouldPerformOvfUpdate()) { ActionReturnValue returnValue = runInternalAction(ActionType.UpdateOvfStoreForStorageDomain, createUpdateOvfStoreParams(), getContext().clone().withoutCompensationContext()); if (!returnValue.getSucceeded()) { return; } } if (noAsyncOperations()) { executeDeactivateCommand(); } setSucceeded(true); }

Target:
protected void executeCommand() { StoragePoolIsoMap map = loadStoragePoolIsoMap(); changeDomainStatusWithCompensation(map, StorageDomainStatus.Unknown, StorageDomainStatus.Locked, getCompensationContext()); if (shouldPerformOvfUpdate()) { ActionReturnValue returnValue = runInternalAction(ActionType.UpdateOvfStoreForStorageDomain, createUpdateOvfStoreParams(), cloneContext().withoutCompensationContext()); if (!returnValue.getSucceeded()) { return; } } if (noAsyncOperations()) { executeDeactivateCommand(); } setSucceeded(true); }
Source:
public boolean isProjectComplete(Project project) { boolean projectsXmlExists = (new File(ConfigCore.getKitodoConfigDirectory() + "kitodo_projects.xml")).exists(); boolean digitalCollectionsXmlExists = (new File( ConfigCore.getKitodoConfigDirectory() + "kitodo_digitalCollections.xml")).exists(); return project.getTitle() != null && project.template != null && project.getFileFormatDmsExport() != null && project.getFileFormatInternal() != null && digitalCollectionsXmlExists && projectsXmlExists; }

Target:
public boolean isProjectComplete(Project project) { boolean projectsXmlExists = (new File(ConfigCore.getKitodoConfigDirectory() + FileNames.PROJECT_CONFIGURATION_FILE)).exists(); boolean digitalCollectionsXmlExists = (new File( ConfigCore.getKitodoConfigDirectory() + FileNames.DIGITAL_COLLECTIONS_FILE)).exists(); return project.getTitle() != null && project.template != null && project.getFileFormatDmsExport() != null && project.getFileFormatInternal() != null && digitalCollectionsXmlExists && projectsXmlExists; }
Source:
public String changeSessionId() { String oldId = delegate.getId(); String id = delegate.changeSessionId(); Map<String, Object> oldState = map.readAllMap(); map.delete(); map = redisson.getMap(keyPrefix + id, map.getCodec()); map.putAll(oldState); RBatch batch = redisson.createBatch(BatchOptions.defaults()); batch.getBucket(getExpiredKey(oldId)).remainTimeToLiveAsync(); batch.getBucket(getExpiredKey(oldId)).deleteAsync(); BatchResult<?> res = batch.execute(); List<?> list = res.getResponses(); Long remainTTL = (Long) list.get(0); redisson.getBucket(getExpiredKey(id)).set("", remainTTL, TimeUnit.MILLISECONDS); return id; }

Target:
public String changeSessionId() { String oldId = delegate.getId(); String id = delegate.changeSessionId(); RBatch batch = redisson.createBatch(BatchOptions.defaults()); batch.getBucket(getExpiredKey(oldId)).remainTimeToLiveAsync(); batch.getBucket(getExpiredKey(oldId)).deleteAsync(); batch.getMap(map.getName()).readAllMapAsync(); batch.getMap(map.getName()).deleteAsync(); BatchResult<?> res = batch.execute(); List<?> list = res.getResponses(); Long remainTTL = (Long) list.get(0); Map<String, Object> oldState = (Map<String, Object>) list.get(2); RBatch batchNew = redisson.createBatch(BatchOptions.defaults()); batchNew.getMap(keyPrefix + id, map.getCodec()).putAllAsync(oldState); batchNew.getBucket(getExpiredKey(id)).setAsync("", remainTTL, TimeUnit.MILLISECONDS); batchNew.execute(); return id; }
Source:
public void teardownTest() throws Exception { List<CompletableFuture<Void>> futures = members.stream().map(Atomix::stop).collect(Collectors.toList()); try { CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).get(30, TimeUnit.SECONDS); } catch (Exception e) { } protocol.close(); }

Target:
public void teardownTest() throws Exception { List<CompletableFuture<Void>> futures = members.stream().map(Atomix::stop).collect(Collectors.toList()); try { CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).get(30, TimeUnit.SECONDS); } catch (Exception e) { } finally { protocol.close(); } }
Source:
public void testCreateUpdateAndDeleteSecurityGroup() { for (String region : api.getConfiguredRegions()) { SecurityGroupApi sgApi = null; Rule rule = null; SecurityGroup securityGroup = null; try { sgApi = api.getSecurityGroupApi(region).get(); securityGroup = sgApi.create( SecurityGroup.createOptions().name("jclouds-test").description("jclouds test security group") .build()); assertNotNull(securityGroup); rule = sgApi.create( Rule.createOptions(RuleDirection.EGRESS, securityGroup.getId()) .ethertype(RuleEthertype.IPV6) .portRangeMax(90) .portRangeMin(80) .protocol(RuleProtocol.TCP) .build()); assertNotNull(rule); securityGroup = sgApi.getSecurityGroup(securityGroup.getId()); assertEquals(securityGroup.getName(), "jclouds-test"); assertEquals(securityGroup.getDescription(), "jclouds test security group"); assertEquals(securityGroup.getRules().size(), 3); Rule newSecGroupRule = null; for (Rule sgr : securityGroup.getRules()) { if (sgr.getId().equals(rule.getId())) { newSecGroupRule = sgr; break; } } assertNotNull(newSecGroupRule, "Did not find the new rule in the group."); assertEquals(rule, newSecGroupRule); assertEquals(rule.getEthertype(), RuleEthertype.IPV6); assertEquals(rule.getProtocol(), RuleProtocol.TCP); assertEquals(rule.getPortRangeMax().intValue(), 90); assertEquals(rule.getPortRangeMin().intValue(), 80); assertEquals(rule.getDirection(), RuleDirection.EGRESS); } finally { try { assertTrue(sgApi.deleteRule(rule.getId())); } finally { assertTrue(sgApi.deleteSecurityGroup(securityGroup.getId())); } } } }

Target:
public void testCreateUpdateAndDeleteSecurityGroup() { for (String region : api.getConfiguredRegions()) { SecurityGroupApi sgApi = null; Rule rule = null; SecurityGroup securityGroup = null; try { sgApi = api.getSecurityGroupApi(region).get(); securityGroup = sgApi.create( SecurityGroup.createBuilder().name("jclouds-test").description("jclouds test security group") .build()); assertNotNull(securityGroup); rule = sgApi.create( Rule.createBuilder(RuleDirection.EGRESS, securityGroup.getId()) .ethertype(RuleEthertype.IPV6) .portRangeMax(90) .portRangeMin(80) .protocol(RuleProtocol.TCP) .build()); assertNotNull(rule); securityGroup = sgApi.getSecurityGroup(securityGroup.getId()); assertEquals(securityGroup.getName(), "jclouds-test"); assertEquals(securityGroup.getDescription(), "jclouds test security group"); assertEquals(securityGroup.getRules().size(), 3); Rule newSecGroupRule = null; for (Rule sgr : securityGroup.getRules()) { if (sgr.getId().equals(rule.getId())) { newSecGroupRule = sgr; break; } } assertNotNull(newSecGroupRule, "Did not find the new rule in the group."); assertEquals(rule, newSecGroupRule); assertEquals(rule.getEthertype(), RuleEthertype.IPV6); assertEquals(rule.getProtocol(), RuleProtocol.TCP); assertEquals(rule.getPortRangeMax().intValue(), 90); assertEquals(rule.getPortRangeMin().intValue(), 80); assertEquals(rule.getDirection(), RuleDirection.EGRESS); } finally { try { assertTrue(sgApi.deleteRule(rule.getId())); } finally { assertTrue(sgApi.deleteSecurityGroup(securityGroup.getId())); } } } }
Source:
public void addGroup(Group group) throws CacheDatabaseException { String selectQuery = "SELECT * FROM " + TABLE_GROUPS + " WHERE " + KEY_GROUP_NODEID + " = ?"; Cursor cursor = mDatabase.rawQuery(selectQuery, new String[]{group.getId().getId()}); if (cursor.getCount() == 1) { cursor.close(); updateGroup(group); } else if (cursor.getCount() > 1) { deleteGroup(group); } if (cursor.getCount() > 1 || cursor.getCount() == 0) { try { ContentValues values = createContentValuesForGroup(group); mDatabase.insert(TABLE_GROUPS, null, values); for (User user : group.getUsers()) { addUser(user); } for (Message message : group.getLastMessages().values()) { addMessage(message, group.getId()); } cursor.close(); } catch (CacheDatabaseException | IOException exception) { Log.d(TAG, "Unable to add Group with id: " + group.getId().getId(), exception); throw new CacheDatabaseException(exception); } } }

Target:
public void addGroup(Group group) throws CacheDatabaseException { Objects.requireNonNull(group); String selectQuery = "SELECT * FROM " + TABLE_GROUPS + " WHERE " + KEY_GROUP_NODEID + " = ?"; Cursor cursor = mDatabase.rawQuery(selectQuery, new String[]{group.getId().getId()}); if (cursor.getCount() >= 1) { cursor.close(); updateGroup(group); } else if (cursor.getCount() > 1) { deleteGroup(group); } if (cursor.getCount() > 1 || cursor.getCount() == 0) { try { ContentValues values = createContentValuesForGroup(group); mDatabase.insert(TABLE_GROUPS, null, values); for (User user : group.getUsers()) { addUser(user); } for (Message message : group.getLastMessages().values()) { addMessage(message, group.getId()); } cursor.close(); } catch (CacheDatabaseException | IOException exception) { Log.d(TAG, "Unable to add Group with id: " + group.getId().getId(), exception); throw new CacheDatabaseException(exception); } } }
Source:
public FeatureState getFeatureState(final Feature feature) { try (Jedis jedis = jedisPool.getResource()) { final Map<String, String> map = jedis.hgetAll(keyPrefix + feature.name()); if (map == null || map.size() == 0) { return null; } final FeatureState featureState = new FeatureState(feature); featureState.setEnabled(Boolean.valueOf(map.get(ENABLED_FIELD))); featureState.setStrategyId(map.get(STRATEGY_FIELD)); final String strategyParameters = map.get(PARAMETERS_FIELD); if (strategyParameters != null) { for (final Map.Entry<String, String> entry : mapSerializer.deserialize(strategyParameters).entrySet()) { featureState.setParameter(entry.getKey(), entry.getValue()); } } return featureState; } }

Target:
public FeatureState getFeatureState(final Feature feature) { try (final Jedis jedis = jedisPool.getResource()) { final Map<String, String> redisMap = jedis.hgetAll(keyPrefix + feature.name()); if (redisMap == null || redisMap.size() == 0) { return null; } final FeatureState featureState = new FeatureState(feature); featureState.setEnabled(Boolean.valueOf(redisMap.get(ENABLED_FIELD))); featureState.setStrategyId(redisMap.get(STRATEGY_FIELD)); for (final Map.Entry<String, String> entry : redisMap.entrySet()) { final String key = entry.getKey(); if (key.startsWith(PARAMETER_PREFIX)) { featureState.setParameter(key.substring(PARAMETER_PREFIX_LENGTH), entry.getValue()); } } return featureState; } }
Source:
public void multiRefTestGetCRAIEntries() { final Slice slice1 = new Slice(ReferenceContext.MULTIPLE_REFERENCE_CONTEXT); final Slice slice2 = new Slice(ReferenceContext.MULTIPLE_REFERENCE_CONTEXT); final Container container = Container.initializeFromSlices(Arrays.asList(slice1, slice2)); final List<CRAIEntry> entries = container.getCRAIEntries(); Assert.assertNotNull(entries); Assert.assertEquals(entries.size(), 2); assertEntryForSlice(entries.get(0), slice1); assertEntryForSlice(entries.get(1), slice2); }

Target:
public void multiRefTestGetCRAIEntries() { final Slice multi = new Slice(ReferenceContext.MULTIPLE_REFERENCE_CONTEXT); final Container container = Container.initializeFromSlices(Arrays.asList(multi)); container.getCRAIEntries(); }
Source:
public NotifierTask(Context context, TaskContext taskContext, Uri uri, String notifyTitle, String notifyText) { mContext = context; mTaskContext = taskContext; mCR = mContext.getContentResolver(); mUri = uri; mNotifyTitle = notifyTitle; mNotifyText = notifyText; mSettings = Application.getPrefs(); }

Target:
public NotifierTask(Context context, TaskContext taskContext, Uri uri, String notifyTitle, String notifyText) { mContext = context; mTaskContext = taskContext; mCR = mContext.getContentResolver(); mUri = uri; mNotifyTitle = notifyTitle; mNotifyText = notifyText; }
Source:
public boolean optionExists(final String optionName) { if (this.cmd.hasOption(optionName)) { return true; } return false; }

Target:
public boolean optionExists(final String optionName) { return this.cmd.hasOption(optionName); }
Source:
public static File task(File projectDir, String dstName) throws IOException { File dstDir = new File(projectDir.getParent(), FileMetaDataExtractor.encodeSpecialCharsForFileSystem(dstName)); try { if (projectDir.renameTo(dstDir) && XstreamSerializer.renameProject(new File(dstDir, CODE_XML_FILE_NAME), dstName)) { return dstDir; } else { return null; } } catch (IOException e) { Log.e(TAG, "Cannot rename project directory " + projectDir.getAbsolutePath() + " to " + dstName, e); throw e; } }

Target:
public static File task(File projectDir, String dstName) throws IOException { File dstDir = new File(projectDir.getParent(), FileMetaDataExtractor.encodeSpecialCharsForFileSystem(dstName)); if (projectDir.renameTo(dstDir) && XstreamSerializer.renameProject(new File(dstDir, CODE_XML_FILE_NAME), dstName)) { return dstDir; } else { throw new IOException("Cannot rename project directory " + projectDir.getAbsolutePath() + " to " + dstName); } }
Source:
void populate(final int row, final PluginInfo plugin) { if (plugin.disabled() || plugin.indexUrl() == null) { table.setText(row, 1, plugin.name()); } else { HorizontalPanel p = new HorizontalPanel(); p.setStyleName(Gerrit.RESOURCES.css().pluginName()); p.add(new Anchor(plugin.name(), Gerrit.selfRedirect(plugin.indexUrl()), "_blank")); if (plugin.adminUrl() != null) { Anchor adminScreenAcnhcor = new Anchor(new ImageResourceRenderer().render(Gerrit.RESOURCES.gear()), Gerrit.selfRedirect(plugin.adminUrl())); adminScreenAcnhcor.setTitle(Util.C.pluginAdminToolTip()); p.add(adminScreenAcnhcor); } table.setWidget(row, 1, p); } table.setText(row, 2, plugin.version()); table.setText(row, 3, plugin.disabled() ? Util.C.pluginDisabled() : Util.C.pluginEnabled()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }

Target:
void populate(final int row, final PluginInfo plugin) { if (plugin.disabled() || plugin.indexUrl() == null) { table.setText(row, 1, plugin.name()); } else { table.setWidget(row, 1, new Anchor(plugin.name(), Gerrit.selfRedirect(plugin.indexUrl()), "_blank")); if (new ExtensionScreen(plugin.name() + "/admin").isFound()) { Anchor adminScreenAcnhcor = new Anchor(new ImageResourceRenderer().render(Gerrit.RESOURCES.gear()), Gerrit.selfRedirect("#/x/" + plugin.name() + "/admin")); adminScreenAcnhcor.setTitle(Util.C.pluginSettingsToolTip()); table.setWidget(row, 2, adminScreenAcnhcor); } } table.setText(row, 3, plugin.version()); table.setText(row, 4, plugin.disabled() ? Util.C.pluginDisabled() : Util.C.pluginEnabled()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 4, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }
Source:
private static String emptyDirectory(String path){ File f = new File(path); if(f.exists()) { for (File log : f.listFiles()) { log.delete(); } f.delete(); } return path; }

Target:
private static String emptyDirectory(String path){ File f = new File(path); if(f.exists()) { for (File log : f.listFiles()) { log.delete(); } } return path; }
Source:
public void setPosition(int position) { this.position = position; if(position > 0) { this.item.setPlayed(false); } }

Target:
public void setPosition(int position) { this.position = position; if(position > 0 && item.isNew()) { this.item.setPlayed(false); } }
Source:
protected List<TaskData> doProcess(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, BugzillaRestException { BufferedInputStream is = new BufferedInputStream(response.getResponseEntityAsStream()); InputStreamReader in = new InputStreamReader(is); isRestError(is, in); return parseFromJson(in); }

Target:
protected List<TaskData> doProcess(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, BugzillaRestException { BufferedInputStream is = new BufferedInputStream(response.getResponseEntityAsStream()); InputStreamReader in = new InputStreamReader(is); throwExeptionIfRestError(is, in); return parseFromJson(in); }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { StageConfigurer stageConfigurer = pipelineConfigurer.getStageConfigurer(); Schema inputSchema = stageConfigurer.getInputSchema(); Preconditions.checkArgument(inputSchema != null, "Input Schema must be a known constant."); }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { StageConfigurer stageConfigurer = pipelineConfigurer.getStageConfigurer(); Schema inputSchema = stageConfigurer.getInputSchema(); Preconditions.checkArgument(inputSchema != null, "Input Schema must be a known constant."); config.validate(inputSchema); pipelineConfigurer.getStageConfigurer().setOutputSchema(config.getOutputSchema(inputSchema)); }
Source:
public void setUp() { when(mockUserService.generatePassword()).thenReturn("topSecret"); MessageDestination anonMessageDestinationEntity = MessageDestination .createInstance(PublicKeyUtil.generateKeyPair().getPublic()); Set<Goal> goals = new HashSet<>(); deviceAnonEntity = DeviceAnonymized.createInstance(0, OperatingSystem.ANDROID, "Unknown", 5, Optional.of("Firebase-12345")); deviceAnonymizedRepository.save(deviceAnonEntity); userAnonEntity = UserAnonymized.createInstance(anonMessageDestinationEntity, goals); userAnonEntity.addDeviceAnonymized(deviceAnonEntity); UserAnonymizedDto userAnon = UserAnonymizedDto.createInstance(userAnonEntity); userAnonId = userAnon.getId(); when(mockUserAnonymizedService.getUserAnonymized(userAnonId)) .thenReturn(UserAnonymizedDto.createInstance(userAnonEntity)); when(mockMessageDestinationRepository.findById(anonMessageDestinationEntity.getId())) .thenReturn(Optional.of(anonMessageDestinationEntity)); }

Target:
public void setUp() { when(mockUserService.generatePassword()).thenReturn("topSecret"); MessageDestination anonMessageDestinationEntity = MessageDestination .createInstance(PublicKeyUtil.generateKeyPair().getPublic()); Set<Goal> goals = new HashSet<>(); deviceAnonEntity = DeviceAnonymized.createInstance(0, OperatingSystem.ANDROID, "Unknown", 5, Optional.of(FIREBASE_REGISTRATION_TOKEN)); deviceAnonymizedRepository.save(deviceAnonEntity); userAnonEntity = UserAnonymized.createInstance(anonMessageDestinationEntity, goals); userAnonEntity.addDeviceAnonymized(deviceAnonEntity); UserAnonymizedDto userAnon = UserAnonymizedDto.createInstance(userAnonEntity); userAnonId = userAnon.getId(); when(mockUserAnonymizedService.getUserAnonymized(userAnonId)) .thenReturn(UserAnonymizedDto.createInstance(userAnonEntity)); when(mockMessageDestinationRepository.findById(anonMessageDestinationEntity.getId())) .thenReturn(Optional.of(anonMessageDestinationEntity)); }
Source:
public M get() { if (message == null && messageBytes != null) { checkConverter(); try { return converter.fromBytes(messageBytes); } catch (Exception e) { throw new IllegalStateException("Converter failed to deserialize", e); } } return message; }

Target:
public M get() { if (message == null && messageBytes != null) { checkConverter(); try { return converter.fromBytes(messageBytes); } catch (DecodeException e) { throw new IllegalStateException("Converter failed to deserialize", e); } } return message; }
Source:
public MockitoSessionBuilder initMocks(Object testClassInstance) { if (testClassInstance == null) { testClassInstance = new Object(); } testInstances = singletonList(testClassInstance); return this; }

Target:
public MockitoSessionBuilder initMocks(Object testClassInstance) { if (testClassInstance != null) { this.testClassInstances.add(testClassInstance); } return this; }
Source:
public void updateComment(String pipelineName, int pipelineCounter, String comment, Username username, HttpLocalizedOperationResult result) { if (securityService.hasOperatePermissionForPipeline(username.getUsername(), pipelineName)) { pipelineDao.updateComment(pipelineName, pipelineCounter, comment); } else { result.unauthorized(LocalizedMessage.cannotViewPipeline(pipelineName), HealthStateType.general(HealthStateScope.forPipeline(pipelineName))); } }

Target:
public void updateComment(String pipelineName, int pipelineCounter, String comment, Username username, HttpLocalizedOperationResult result) { if (securityService.hasOperatePermissionForPipeline(username.getUsername(), pipelineName)) { pipelineDao.updateComment(pipelineName, pipelineCounter, comment); } else { result.unauthorized(LocalizedMessage.cannotOperatePipeline(pipelineName), HealthStateType.general(HealthStateScope.forPipeline(pipelineName))); } }
Source:
public Map<String, String> getAllValues( Locator locator ) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext( CassandraModel.CF_METRICS_STATE_NAME ); Session session = DatastaxIO.getSession(); try { Select.Where select = select() .all() .from( CassandraModel.CF_METRICS_METADATA_NAME ) .where( eq( KEY, locator.toString() )); List<Row> results = session.execute( select ).all(); Map<String, String> values = new HashMap<String, String>(); for ( Row row : results ) { if ( LOG.isDebugEnabled() ) { LOG.debug( "Read metrics_metadata: " + row.getString( KEY ) + row.getString( COLUMN1 ) + serDes.deserialize( row.getBytes( VALUE ) ) ); } values.put( row.getString( COLUMN1 ), serDes.deserialize( row.getBytes( VALUE ) ) ); } return values; } finally { ctx.stop(); } }

Target:
public Map<String, String> getAllValues( Locator locator ) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext( CassandraModel.CF_METRICS_METADATA_NAME ); Session session = DatastaxIO.getSession(); try { Select.Where select = select() .all() .from( CassandraModel.CF_METRICS_METADATA_NAME ) .where( eq( KEY, locator.toString() )); List<Row> results = session.execute( select ).all(); Map<String, String> values = new HashMap<String, String>(); for ( Row row : results ) { if ( LOG.isTraceEnabled() ) { LOG.trace( "Read metrics_metadata: " + row.getString( KEY ) + row.getString( COLUMN1 ) + serDes.deserialize( row.getBytes( VALUE ) ) ); } values.put( row.getString( COLUMN1 ), serDes.deserialize( row.getBytes( VALUE ) ) ); } return values; } finally { ctx.stop(); } }
Source:
public String getErrorPage() { return null; }

Target:
public String getErrorPage() { return "public/404"; }
Source:
public void handle(LoginRequest loginRequest) throws Exception { Preconditions.checkState( thisState == State.USERNAME, "Not expecting USERNAME" ); this.loginRequest = loginRequest; if ( getName().length() == 0 ) { disconnect( bungee.getTranslation( "name_empty" ) ); return; } if ( getName().length() > 16 ) { disconnect( bungee.getTranslation( "name_too_long" ) ); return; } if ( !Util.testUsername( getName() ) ) { disconnect( bungee.getTranslation( "name_invalid" ) ); return; } int limit = BungeeCord.getInstance().config.getPlayerLimit(); if ( limit > 0 && bungee.getOnlineCount() > limit ) { disconnect( bungee.getTranslation( "proxy_full" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getUniqueId() ) != null ) { disconnect( bungee.getTranslation( "already_connected_proxy" ) ); return; } Callback<PreLoginEvent> callback = new Callback<PreLoginEvent>() { @Override public void done(PreLoginEvent result, Throwable error) { if ( result.isCancelled() ) { disconnect( result.getCancelReasonComponents() ); return; } if ( ch.isClosed() ) { return; } if ( onlineMode ) { unsafe().sendPacket( request = EncryptionUtil.encryptRequest() ); } else { finish(); } thisState = State.ENCRYPT; } }; bungee.getPluginManager().callEvent( new PreLoginEvent( InitialHandler.this, callback ) ); }

Target:
public void handle(LoginRequest loginRequest) throws Exception { Preconditions.checkState( thisState == State.USERNAME, "Not expecting USERNAME" ); this.loginRequest = loginRequest; if ( getName().length() == 0 ) { disconnect( bungee.getTranslation( "name_empty" ) ); return; } if ( getName().length() > 16 ) { disconnect( bungee.getTranslation( "name_too_long" ) ); return; } boolean validName; if ( isOnlineMode() || BungeeCord.getInstance().config.isStrictOfflineNameValidate() ) { validName = Util.testUsername( getName() ); } else { validName = !getName().contains( "." ); } if ( !validName ) { disconnect( bungee.getTranslation( "name_invalid" ) ); return; } int limit = BungeeCord.getInstance().config.getPlayerLimit(); if ( limit > 0 && bungee.getOnlineCount() > limit ) { disconnect( bungee.getTranslation( "proxy_full" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getUniqueId() ) != null ) { disconnect( bungee.getTranslation( "already_connected_proxy" ) ); return; } Callback<PreLoginEvent> callback = new Callback<PreLoginEvent>() { @Override public void done(PreLoginEvent result, Throwable error) { if ( result.isCancelled() ) { disconnect( result.getCancelReasonComponents() ); return; } if ( ch.isClosed() ) { return; } if ( onlineMode ) { unsafe().sendPacket( request = EncryptionUtil.encryptRequest() ); } else { finish(); } thisState = State.ENCRYPT; } }; bungee.getPluginManager().callEvent( new PreLoginEvent( InitialHandler.this, callback ) ); }
Source:
public BanCommitResult ban(final ProjectControl projectControl, final List<ObjectId> commitsToBan, final String reason) throws PermissionDeniedException, IOException, InterruptedException, MergeException, ConcurrentRefUpdateException { if (!projectControl.isOwner()) { throw new PermissionDeniedException( "No project owner: not permitted to ban commits"); } final BanCommitResult result = new BanCommitResult(); NoteMap banCommitNotes = NoteMap.newEmptyMap(); final Repository repo = repoManager.openRepository(projectControl.getProject().getNameKey()); final RevWalk revWalk = new RevWalk(repo); final ObjectInserter inserter = repo.newObjectInserter(); try { for (final ObjectId commitToBan : commitsToBan) { try { revWalk.parseCommit(commitToBan); } catch (MissingObjectException e) { } catch (IncorrectObjectTypeException e) { result.notACommit(commitToBan, e.getMessage()); continue; } banCommitNotes.set(commitToBan, createNoteContent(reason, inserter)); } NotesBranchUtil notesBranchUtil = notesBranchUtilFactory.create(repo); NoteMap newlyCreated = notesBranchUtil.commitNewNotes(banCommitNotes, REF_REJECT_COMMITS, createPersonIdent(), buildCommitMessage(commitsToBan, reason)); for (Note n : banCommitNotes) { if (newlyCreated.contains(n)) { result.commitBanned(n); } else { result.commitAlreadyBanned(n); } } return result; } finally { revWalk.release(); inserter.release(); } }

Target:
public BanCommitResult ban(final ProjectControl projectControl, final List<ObjectId> commitsToBan, final String reason) throws PermissionDeniedException, IOException, InterruptedException, MergeException, ConcurrentRefUpdateException { if (!projectControl.isOwner()) { throw new PermissionDeniedException( "No project owner: not permitted to ban commits"); } final BanCommitResult result = new BanCommitResult(); NoteMap banCommitNotes = NoteMap.newEmptyMap(); final Repository repo = repoManager.openRepository(projectControl.getProject().getNameKey()); try { final RevWalk revWalk = new RevWalk(repo); final ObjectInserter inserter = repo.newObjectInserter(); try { for (final ObjectId commitToBan : commitsToBan) { try { revWalk.parseCommit(commitToBan); } catch (MissingObjectException e) { } catch (IncorrectObjectTypeException e) { result.notACommit(commitToBan, e.getMessage()); continue; } banCommitNotes.set(commitToBan, createNoteContent(reason, inserter)); } inserter.flush(); NotesBranchUtil notesBranchUtil = notesBranchUtilFactory.create(repo); NoteMap newlyCreated = notesBranchUtil.commitNewNotes(banCommitNotes, REF_REJECT_COMMITS, createPersonIdent(), buildCommitMessage(commitsToBan, reason)); for (Note n : banCommitNotes) { if (newlyCreated.contains(n)) { result.commitBanned(n); } else { result.commitAlreadyBanned(n); } } return result; } finally { revWalk.release(); inserter.release(); } } finally { repo.close(); } }
Source:
public void voidCondition_shouldVoidConditionSuccessfully(){ Condition condition = new Condition(); int patientId = 2; condition.setCondition(new CodedOrFreeText()); condition.setAdditionalDetail("voiding a condition"); condition.setVerificationStatus(ConditionVerificationStatus.PROVISIONAL); condition.setClinicalStatus(ConditionClinicalStatus.INACTIVE); condition.setUuid(UUID); condition.setPatient(patientService.getPatient(patientId)); expectedException = ExpectedException.none(); conditionService.voidCondition(condition, "Test Reason"); Condition voidedCondition = conditionService.getConditionByUuid(UUID); Assert.assertEquals(ConditionVerificationStatus.PROVISIONAL, voidedCondition.getVerificationStatus()); Assert.assertEquals(ConditionClinicalStatus.INACTIVE, voidedCondition.getClinicalStatus()); Assert.assertEquals(UUID, voidedCondition.getUuid()); }

Target:
public void voidCondition_shouldVoidConditionSuccessfully(){ Integer conditionId = 2; String voidReason = "Test Reason"; Condition nonVoidedCondition = conditionService.getCondition(conditionId); Assert.assertFalse(nonVoidedCondition.getVoided()); Assert.assertNull(nonVoidedCondition.getVoidReason()); Assert.assertNull(nonVoidedCondition.getDateVoided()); Assert.assertNull(nonVoidedCondition.getVoidedBy()); conditionService.voidCondition(nonVoidedCondition, voidReason); Condition voidedCondition = conditionService.getCondition(conditionId); Assert.assertEquals(ConditionVerificationStatus.CONFIRMED, voidedCondition.getVerificationStatus()); Assert.assertEquals(ConditionClinicalStatus.ACTIVE, voidedCondition.getClinicalStatus()); Assert.assertEquals("2cc6880e-2c46-11e4-9138-a6c5e4d20fb7", voidedCondition.getUuid()); Assert.assertTrue(voidedCondition.getVoided()); Assert.assertEquals(voidReason, voidedCondition.getVoidReason()); Assert.assertNotNull(voidedCondition.getDateVoided()); Assert.assertEquals(Context.getAuthenticatedUser(), voidedCondition.getVoidedBy()); }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Permission that = (Permission) o; return Objects.equals(resource, that.resource) && Objects.equals(operation, that.operation) && Objects.equals(authorizationAttribute.getDataType(), that.authorizationAttribute.getDataType()) && Objects.equals(authorizationAttribute.getValue(), that.authorizationAttribute.getDataType()); }

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Permission that = (Permission) o; return Objects.equals(resource, that.resource) && Objects.equals(operation, that.operation) && Objects.equals(authorizationAttribute.getDataType(), that.authorizationAttribute.getDataType()) && Objects.equals(authorizationAttribute.getValue(), that.authorizationAttribute.getValue()); }
Source:
private static Path unsymlinkAndLookForIndex(Path samPath) { try { final Path canonicalSamPath = samPath.toRealPath(); final Path canonicalIndexPath = lookForIndex(canonicalSamPath); if ( canonicalIndexPath != null) { System.err.println("The index file " + canonicalIndexPath.toAbsolutePath() + " was found by resolving the canonical path of a symlink: " + samPath.toAbsolutePath() + " -> " + samPath.toRealPath()); } return canonicalIndexPath; } catch (IOException e) { return null; } }

Target:
private static Path unsymlinkAndLookForIndex(Path samPath) { try { final Path canonicalSamPath = samPath.toRealPath(); final Path canonicalIndexPath = lookForIndex(canonicalSamPath); if ( canonicalIndexPath != null) { LOG.warn("The index file " + canonicalIndexPath.toAbsolutePath() + " was found by resolving the canonical path of a symlink: " + samPath.toAbsolutePath() + " -> " + samPath.toRealPath()); } return canonicalIndexPath; } catch (IOException e) { return null; } }
Source:
public void prepareDatabaseForScenario() { Logger LOGGER = LoggerFactory.getLogger(this.getClass()); LOGGER.info(this.getClass() + ": prepareDatabaseForScenario"); cleanRepoAbstractEntity(this.oslpDeviceRepo); cleanRepoAbstractEntity(this.deviceAuthorizationRepo); cleanRepoSerializable(this.deviceRepo); cleanRepoSerializable(this.deviceModelRepo); cleanRepoSerializable(this.manufacturerRepo); for(Organisation org : this.organizationRepo.findAll()) { String orgName = org.getOrganisationIdentification(); if (!orgName.equals("test-org") && !orgName.equals("FlexOvlProject") && !orgName.equals("GemeenteArnhem") && !orgName.equals("LianderNetManagement")) { this.organizationRepo.delete(org); } } insertDefaultData(); }

Target:
public void prepareDatabaseForScenario() { cleanRepoAbstractEntity(this.oslpDeviceRepo); cleanRepoAbstractEntity(this.deviceAuthorizationRepo); cleanRepoSerializable(this.smartMeterRepo); cleanRepoSerializable(this.deviceRepo); cleanRepoSerializable(this.deviceModelRepo); cleanRepoSerializable(this.manufacturerRepo); cleanRepoSerializable(this.ssldRepository); cleanRepoSerializable(this.organizationRepo); insertDefaultData(); }
Source:
static ServerHolder reservoirSampleServer(final List<ServerHolder> serverHolders) { if (serverHolders.isEmpty()) { return null; } ServerHolder sampledServer = null; long total = 0; for (ServerHolder serverHolder : serverHolders) { ImmutableDruidServer server = serverHolder.getServer(); long numSegments = server.getSegments().size(); long endIndex = total + numSegments; long randomIndex = ThreadLocalRandom.current().nextLong((endIndex == 0) ? 1 : endIndex); if (randomIndex >= total && randomIndex < endIndex) { sampledServer = serverHolder; } total += numSegments; } return sampledServer; }

Target:
static ServerHolder reservoirSampleServer(final List<ServerHolder> serverHolders) { if (serverHolders.isEmpty()) { return null; } else if (serverHolders.size() == 1) { return serverHolders.get(0); } ServerHolder sampledServer = null; long total = 0; for (ServerHolder serverHolder : serverHolders) { ImmutableDruidServer server = serverHolder.getServer(); long numSegments = server.getSegments().size(); long endIndex = total + numSegments; long upperBound = endIndex; if (endIndex == 0) { upperBound = 1; } long randomIndex = ThreadLocalRandom.current().nextLong(upperBound); if (randomIndex >= total && randomIndex < endIndex) { sampledServer = serverHolder; } total += numSegments; } return sampledServer; }
Source:
private InjectMenuActivity.MockMenuInflater createMenuInflater() { final InjectMenuActivity.MockMenuInflater menuInflater = Mockito.mock(InjectMenuActivity.MockMenuInflater.class); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { menuInflater.menuInflated = true; return null; } }).when(menuInflater).inflate(anyInt(), any(Menu.class)); return menuInflater; }

Target:
private InjectMenuActivity.MockMenuInflater createMenuInflater() { final InjectMenuActivity.MockMenuInflater menuInflater = mock(InjectMenuActivity.MockMenuInflater.class); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { menuInflater.menuInflated = true; return null; } }).when(menuInflater).inflate(anyInt(), any(Menu.class)); return menuInflater; }
Source:
private void populateAbandonAction() { final Button b = new Button(Util.C.buttonAbandonChangeBegin()); b.addClickListener(new ClickListener() { public void onClick(Widget sender) { b.setEnabled(false); new AbandonChangeDialog(patchSet.getId(), new AsyncCallback<Object>() { public void onSuccess(Object result) { actionsPanel.remove(b); fireOnSuggestRefresh(); } public void onFailure(Throwable caught) { b.setEnabled(true); } }).center(); } }); actionsPanel.add(b); }

Target:
private void populateAbandonAction() { final Button b = new Button(Util.C.buttonAbandonChangeBegin()); b.addClickListener(new ClickListener() { public void onClick(Widget sender) { new AbandonChangeDialog(patchSet.getId(), new AsyncCallback<Object>() { public void onSuccess(Object result) { actionsPanel.remove(b); fireOnSuggestRefresh(); } public void onFailure(Throwable caught) { } }).center(); } }); actionsPanel.add(b); }