auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public QuotaTariffVO updateQuotaTariffPlan(QuotaTariffUpdateCmd cmd) { final int quotaType = cmd.getUsageType(); final BigDecimal quotaCost = new BigDecimal(cmd.getValue()); final Date effectiveDate = _quotaService.computeAdjustedTime(cmd.getStartDate()); final Date now = _quotaService.computeAdjustedTime(new Date()); if (effectiveDate.compareTo(now) < 0) { throw new InvalidParameterValueException("Incorrect effective date for tariff " + effectiveDate + " is less than now " + now); } QuotaTypes quotaConstant = QuotaTypes.listQuotaTypes().get(quotaType); if (quotaConstant == null) { throw new InvalidParameterValueException("Quota type does not exists " + quotaType); } final short opendb = TransactionLegacy.currentTxn().getDatabaseId(); TransactionLegacy.open(TransactionLegacy.USAGE_DB).close(); QuotaTariffVO result = null; try { result = new QuotaTariffVO(); result.setUsageType(quotaType); result.setUsageName(quotaConstant.getQuotaName()); result.setUsageUnit(quotaConstant.getQuotaUnit()); result.setUsageDiscriminator(quotaConstant.getDiscriminator()); result.setCurrencyValue(quotaCost); result.setEffectiveOn(effectiveDate); result.setUpdatedOn(now); result.setUpdatedBy(cmd.getEntityOwnerId()); <START> s_logger.debug(String.format("Updating Quota Tariff Plan: New value=%s for resource type=%d effective on date=%s", quotaCost, quotaType, effectiveDate)); <END> _quotaTariffDao.addQuotaTariff(result); } catch (Exception pokemon) { s_logger.error("Error in update quota tariff plan: " + pokemon); } finally { TransactionLegacy.open(opendb).close(); } return result; }</code><technical_language>This debug statement wrapped in if (s_logger.isDebugEnabled) { } block</technical_language>

Target:
public QuotaTariffVO updateQuotaTariffPlan(QuotaTariffUpdateCmd cmd) { final int quotaType = cmd.getUsageType(); final BigDecimal quotaCost = new BigDecimal(cmd.getValue()); final Date effectiveDate = _quotaService.computeAdjustedTime(cmd.getStartDate()); final Date now = _quotaService.computeAdjustedTime(new Date()); if (effectiveDate.compareTo(now) < 0) { throw new InvalidParameterValueException("Incorrect effective date for tariff " + effectiveDate + " is less than now " + now); } QuotaTypes quotaConstant = QuotaTypes.listQuotaTypes().get(quotaType); if (quotaConstant == null) { throw new InvalidParameterValueException("Quota type does not exists " + quotaType); } QuotaTariffVO result = null; result = new QuotaTariffVO(quotaType); result.setUsageName(quotaConstant.getQuotaName()); result.setUsageUnit(quotaConstant.getQuotaUnit()); result.setUsageDiscriminator(quotaConstant.getDiscriminator()); result.setCurrencyValue(quotaCost); result.setEffectiveOn(effectiveDate); result.setUpdatedOn(now); result.setUpdatedBy(cmd.getEntityOwnerId()); if (s_logger.isDebugEnabled()) { s_logger.debug(String.format("Updating Quota Tariff Plan: New value=%s for resource type=%d effective on date=%s", quotaCost, quotaType, effectiveDate)); } _quotaTariffDao.addQuotaTariff(result); return result; }
Source:
<code>public int getBasicRailMetadata(EntityMinecart cart) { int meta = tileEntity.getBlockMetadata(); <START> if (cart != null && (isSwitched() || springingCarts.contains(cart.getPersistentID()))) { <END> if (meta == EnumTrackMeta.NORTH_SOUTH.ordinal()) { if (isMirrored()) { if (reversed) { meta = EnumTrackMeta.WEST_SOUTH_CORNER.ordinal(); } else { meta = EnumTrackMeta.WEST_NORTH_CORNER.ordinal(); } } else { if (reversed) { meta = EnumTrackMeta.EAST_NORTH_CORNER.ordinal(); } else { meta = EnumTrackMeta.EAST_SOUTH_CORNER.ordinal(); } } } else if (meta == EnumTrackMeta.EAST_WEST.ordinal()) { if (isMirrored()) { if (reversed) { meta = EnumTrackMeta.WEST_NORTH_CORNER.ordinal(); } else { meta = EnumTrackMeta.EAST_NORTH_CORNER.ordinal(); } } else { if (reversed) { meta = EnumTrackMeta.EAST_SOUTH_CORNER.ordinal(); } else { meta = EnumTrackMeta.WEST_SOUTH_CORNER.ordinal(); } } } } return meta; }</code><technical_language>this "derail" a cart "locked" direction if track switched? need add a check locked set isSwitched() is true. for Wye</technical_language>

Target:
public int getBasicRailMetadata(EntityMinecart cart) { int meta = tileEntity.getBlockMetadata(); if (cart != null && isSwitched(cart)) { if (meta == EnumTrackMeta.NORTH_SOUTH.ordinal()) { if (isMirrored()) { if (reversed) { meta = EnumTrackMeta.WEST_SOUTH_CORNER.ordinal(); } else { meta = EnumTrackMeta.WEST_NORTH_CORNER.ordinal(); } } else { if (reversed) { meta = EnumTrackMeta.EAST_NORTH_CORNER.ordinal(); } else { meta = EnumTrackMeta.EAST_SOUTH_CORNER.ordinal(); } } } else if (meta == EnumTrackMeta.EAST_WEST.ordinal()) { if (isMirrored()) { if (reversed) { meta = EnumTrackMeta.WEST_NORTH_CORNER.ordinal(); } else { meta = EnumTrackMeta.EAST_NORTH_CORNER.ordinal(); } } else { if (reversed) { meta = EnumTrackMeta.EAST_SOUTH_CORNER.ordinal(); } else { meta = EnumTrackMeta.WEST_SOUTH_CORNER.ordinal(); } } } } return meta; }
Source:
<code>public BeanIdentifier getIdentifier(int idx) { checkIsBuilt(); <START> return index[idx]; <END> }</code><technical_language>idx in theory (difference in deployments in a cluster) out of range of array. detect in naming scheme fail instead of letting ArrayIndexOutOfBounds escape</technical_language>

Target:
public BeanIdentifier getIdentifier(int idx) { checkIsBuilt(); if (idx < 0 || idx >= index.length) { throw SerializationLogger.LOG.unableToGetBeanIdentifier(idx, this); } return index[idx]; }
Source:
<code>public void propertyChange(PropertyChangeEvent event) { if(event.getSource() == serverChoice && event.getProperty() == FieldEditor.VALUE) { String changedLSLocation = CPPStreamConnectionProvider.getDefaultLSLocation((String) event.getNewValue()).getAbsolutePath(); <START> if(changedLSLocation != null) { <END> serverPath.setStringValue(changedLSLocation); } } }</code><technical_language>This null check is late: if getDefaultLSLocation() returns null, call getAbsolutePath() previous line throw a NullPointerException</technical_language>

Target:
public void propertyChange(PropertyChangeEvent event) { if(event.getSource() == serverChoice && event.getProperty() == FieldEditor.VALUE) { File changedLSLocation = CPPStreamConnectionProvider.getDefaultLSLocation((String) event.getNewValue()); if(changedLSLocation != null) { serverPath.setStringValue(changedLSLocation.getAbsolutePath()); } } }
Source:
<code>public void navigateForward() { try { driver.navigate().forward(); PageObjectLogging.log("navigateForward", "next page loaded", true); } catch (TimeoutException e) { PageObjectLogging.log("navigateForward", <START> "page loaded for more then 30 seconds after navigating back", true); <END> } }</code><technical_language>change message "after navigating forward"</technical_language>

Target:
public void navigateForward() { try { driver.navigate().forward(); PageObjectLogging.log("Navigate Forward", "next page loaded", true); } catch (TimeoutException e) { PageObjectLogging.log("Navigate Forward", "page loaded for more then 30 seconds after navigating forward", false); } }
Source:
<code><START> public String getResultName(@Nonnull Query query, @Nonnull ObjectName objectName, @Nullable String key, @Nonnull String attribute) { <END> String result; if (query.getResultAlias() == null) { result = escapeObjectName(objectName); if (attribute != null && !attribute.isEmpty()) { result += "." + attribute; } if (key != null && !key.isEmpty()) { result += "." + key; } } else { result = expressionLanguageEngine.resolveExpression(query.getResultAlias(), objectName); } return result; }</code><technical_language>change existing ResultNameStrategyImpl? adding another implementation JConsoleNameStrategyImpl? a compatibility risk if modify ResultNameStrategyImpl</technical_language>

Target:
public String getResultName(@Nonnull Query query, @Nonnull ObjectName objectName, @Nullable String key, @Nonnull String attribute) { String result; if (query.getResultAlias() == null) { if (key == null) { result = escapeObjectName(objectName) + "." + attribute; } else { result = escapeObjectName(objectName) + "." + attribute + "." + key; } } else { result = expressionLanguageEngine.resolveExpression(query.getResultAlias(), objectName); } return result; }
Source:
<code>protected void executeCommand() { <START> Provider hostProvider = getProvider(); <END> HostProviderProxy proxy = ((HostProviderProxy) ProviderProxyFactory.getInstance().create(hostProvider)); List<? extends Certificate> chain = proxy.getCertificateChain(); saveChainToTrustStore(chain); }</code><technical_language>This named hostProvider</technical_language>

Target:
protected void executeCommand() { Provider provider = getProvider(); ProviderProxy proxy = ProviderProxyFactory.getInstance().create(provider); List<? extends Certificate> chain = proxy.getCertificateChain(); saveChainToTrustStore(chain); }
Source:
<code>public static <START> synchronized IndexedUserContainer <END> getInstance() { return container; }</code><technical_language>obsolete now, accessing a class attribute is thread-safe</technical_language>

Target:
public static IndexedUserContainer getInstance() { return container; }
Source:
<code>private void removeCacheLoader(String storeType, Collection<CacheLoader> collection) { <START> Iterator<CacheLoader> clIt = collection.iterator(); <END> while (clIt.hasNext()) { CacheLoader w = clIt.next(); if (undelegate(w).getClass().getName().equals(storeType)) clIt.remove(); } }</code><technical_language>do removeIf. This implementation decided iterate</technical_language>

Target:
private void removeCacheLoader(String storeType, Collection<CacheLoader> collection) { collection.removeIf(cacheLoader -> undelegate(cacheLoader).getClass().getName().equals(storeType)); }
Source:
<code>public List<OskariLayer> findByIdList(final List<Integer> intList) { <START> final List<String> strList = ConversionHelper.getStringListFromIntegers(intList); <END> if(intList.size() < 1 && strList.size() < 1){ return new ArrayList<OskariLayer>(); } Map<String, Object> params = new HashMap<String, Object>(); params.put("strList", strList); params.put("intList", intList); List<Map<String,Object>> result = queryForList(getNameSpace() + ".findByIdList", params); final List<OskariLayer> layers = mapDataList(result); return OskariLayerWorker.reorderLayers(layers, strList); }</code><technical_language>This is needed params integers. remove method ConversionHelper</technical_language>

Target:
public List<OskariLayer> findByIdList(final List<Integer> intList) { if(intList.isEmpty()){ return new ArrayList<OskariLayer>(); } Map<String, Object> params = new HashMap<String, Object>(); params.put("intList", intList); params.put("parentIntList", intList); List<Map<String,Object>> result = queryForList(getNameSpace() + ".findByIdList", params); final List<OskariLayer> layers = mapDataList(result); List<OskariLayer> reLayers = new ArrayList<OskariLayer>(); for (Integer id : intList) { for (OskariLayer lay : layers) { if (lay.getId() == id) { reLayers.add(lay); break; } } } return reLayers; }
Source:
<code>public void onProcessComplete(int exitValue) { LOGGER.warn("Process is exited with exit value " + exitValue); if (exitValue != 0) { <START> state = State.EXITED; <END> synchronized (this) { notify(); } } }</code><technical_language>EXITED is unexpected termination? this TERMINATED</technical_language>

Target:
public void onProcessComplete(int exitValue) { LOGGER.warn("Process is exited with exit value " + exitValue); if (exitValue != 0) { transition(State.TERMINATED); synchronized (this) { notify(); } } else { transition(State.COMPLETED); } }
Source:
<code>public CompletableFuture<MessageSendingResult> send(Message message) { try { <START> final CompletableFuture<MessageSendingResult> resultFuture = new CompletableFuture<>(); <END> sendMessage(message, resultFuture); return resultFuture; } catch (Exception e) { throw new InternalProcessingException("Failed to send message", e); } }</code><technical_language>final</technical_language>

Target:
public CompletableFuture<MessageSendingResult> send(Message message) { try { CompletableFuture<MessageSendingResult> resultFuture = new CompletableFuture<>(); sendMessage(message, resultFuture); return resultFuture; } catch (Exception e) { throw new InternalProcessingException("Failed to send message", e); } }
Source:
<code>public void sendPushMessage(Variant variant, Collection<String> clientIdentifiers, UnifiedPushMessage pushMessage, NotificationSenderCallback senderCallback) { AdmService admService = ADM.newService(); PayloadBuilder builder = ADM.newPayload(); builder.dataField("alert", pushMessage.getMessage().getAlert()); builder.dataField("sound", pushMessage.getMessage().getSound()); <START> builder.dataField("badge", "" + pushMessage.getMessage().getBadge()); <END> int ttl = pushMessage.getConfig().getTimeToLive(); if (ttl != -1) { builder.expiresAfter(ttl); } builder.dataField("message","useless payload"); builder.consolidationKey("my other app"); Set<String> keys = pushMessage.getMessage().getUserData().keySet(); for (String key : keys) { builder.dataField(key, pushMessage.getMessage().getUserData().get(key)); } System.out.println(builder.build()); final AdmVariant admVariant = (AdmVariant) variant; for(String token : clientIdentifiers) { try { admService.sendMessageToDevice(token, admVariant.getClientId(), admVariant.getClientSecret(), builder.build()); senderCallback.onSuccess(); } catch (Exception e) { logger.severe("Error sending payload to ADM server", e); senderCallback.onError(e.getMessage()); } } }</code><technical_language>ADM apple</technical_language>

Target:
public void sendPushMessage(Variant variant, Collection<String> clientIdentifiers, UnifiedPushMessage pushMessage, NotificationSenderCallback senderCallback) { final AdmService admService = ADM.newService(); final PayloadBuilder builder = ADM.newPayload(); builder.dataField("alert", pushMessage.getMessage().getAlert()); int ttl = pushMessage.getConfig().getTimeToLive(); if (ttl != -1) { builder.expiresAfter(ttl); } builder.dataField("message","useless payload"); builder.consolidationKey(pushMessage.getMessage().getConsolidationKey()); Set<String> keys = pushMessage.getMessage().getUserData().keySet(); for (String key : keys) { builder.dataField(key, pushMessage.getMessage().getUserData().get(key)); } final AdmVariant admVariant = (AdmVariant) variant; for(String token : clientIdentifiers) { try { admService.sendMessageToDevice(token, admVariant.getClientId(), admVariant.getClientSecret(), builder.build()); senderCallback.onSuccess(); } catch (Exception e) { logger.severe("Error sending payload to ADM server", e); senderCallback.onError(e.getMessage()); } } }
Source:
<code>public CompletableFuture<Boolean> replaceIssueLabels(TurboIssue issue, List<String> newLabels) { boolean isLabelsChanged = updateIssueLabels(issue, newLabels); if (isLabelsChanged) { logger.info("Changing labels for " + issue + " on UI"); refreshUI(); } return updateIssueLabelsOnRepo(issue, newLabels); <START> } <END></code><technical_language>If follow suggested code, 1. isLabelsChanged(issue, newLabels) tested for correctness of boolean condition. e.g. new labels is a subset of originals 2. this method paths, needs test cases only. i.e. labels changed case labels unchanged case</technical_language>

Target:
public CompletableFuture<Boolean> replaceIssueLabels(TurboIssue issue, List<String> newLabels) { logger.info("Changing labels for " + issue + " on UI"); issue.setLabels(newLabels); refreshUI(); return updateIssueLabelsOnRepo(issue, newLabels); }
Source:
<code>public void start(BundleContext bc) throws Exception { this.processRuntimeReg = bc.registerService( new String[]{ ProcessRuntimeFactoryService.class.getName(), Service.class.getName()}, new ProcessRuntimeFactoryServiceImpl(), new Hashtable() ); this.processRuntimeReg2 = bc.registerService( new String[]{ ProcessMarshallerFactoryService.class.getName(), Service.class.getName()}, new ProcessMarshallerFactoryServiceImpl(), new Hashtable() ); RuntimeManagerFactory.Factory.reset(); <START> ProcessBuilderFactory.resetInitialization(); <END> }</code><technical_language>Is this change intentional - ProcessRuntimeFactory -> ProcessBuilderFactory? here, in master PR</technical_language>

Target:
public void start(BundleContext bc) throws Exception { this.processRuntimeReg = bc.registerService( new String[]{ ProcessRuntimeFactoryService.class.getName(), Service.class.getName()}, new ProcessRuntimeFactoryServiceImpl(), new Hashtable() ); this.processRuntimeReg2 = bc.registerService( new String[]{ ProcessMarshallerFactoryService.class.getName(), Service.class.getName()}, new ProcessMarshallerFactoryServiceImpl(), new Hashtable() ); RuntimeManagerFactory.Factory.reset(); ProcessRuntimeFactory.resetInitialization(); }
Source:
<code>public String toString() { return String.format("%s, storagePoolId = %s, storagePoolName = %s, masterDomainId = %s, masterVersion = %s, domainsList = [%s]", super.toString(), getStoragePoolId(), getStoragePoolName(), getMasterDomainId(), getMasterVersion(), <START> getPrintableDomainsList()); <END> }</code><technical_language>Update toString , add vdsSpmId</technical_language>

Target:
public String toString() { return String.format("%s, vdsSpmId = %i, storagePoolId = %s, " + "storagePoolName = %s, masterDomainId = %s, masterVersion = %s, " + "domainsList = [%s]", super.toString(), getVdsSpmId(), getStoragePoolId(), getStoragePoolName(), getMasterDomainId(), getMasterVersion(), getPrintableDomainsList()); }
Source:
<code>public void testPendingMutationsOnDDL() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(QueryServices.PENDING_MUTATIONS_DDL_THROW_ATTRIB, "true"); try (Connection conn = DriverManager.getConnection(getUrl(), props); <START> PhoenixConnection spy = spy((PhoenixConnection) conn)) { <END> MutationState mutationState = mock(MutationState.class); when(mutationState.getNumRows()).thenReturn(1); doReturn(mutationState).when(spy).getMutationState(); exceptionRule.expect(SQLException.class); exceptionRule.expectMessage( SQLExceptionCode.CANNOT_PERFORM_DDL_WITH_PENDING_MUTATIONS.getMessage()); spy.createStatement().execute("create table MUTATION_TEST1" + "( id1 UNSIGNED_INT not null primary key," + "appId1 VARCHAR)"); } }</code><technical_language>nit: variable name spy suffixed spy, pConnSpy etc</technical_language>

Target:
public void testPendingMutationsOnDDL() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(QueryServices.PENDING_MUTATIONS_DDL_THROW_ATTRIB, "true"); try (Connection conn = DriverManager.getConnection(getUrl(), props); PhoenixConnection pConnSpy = spy((PhoenixConnection) conn)) { MutationState mutationState = mock(MutationState.class); when(mutationState.getNumRows()).thenReturn(1); doReturn(mutationState).when(pConnSpy).getMutationState(); exceptionRule.expect(SQLException.class); exceptionRule.expectMessage( SQLExceptionCode.CANNOT_PERFORM_DDL_WITH_PENDING_MUTATIONS.getMessage()); pConnSpy.createStatement().execute("create table MUTATION_TEST1" + "( id1 UNSIGNED_INT not null primary key," + "appId1 VARCHAR)"); } }
Source:
<code>public static void prepareCommandForMonitoring(CommandBase<?> command, VdcActionType actionType, boolean runAsInternal) { <START> <END> ExecutionContext context = new ExecutionContext(); try { boolean isMonitored = shouldMonitorCommand(actionType, runAsInternal); context.setMonitored(isMonitored); if (isMonitored) { Job job = createJob(actionType, command); JobRepositoryFactory.getJobRepository().saveJob(job); context.setExecutionMethod(ExecutionMethod.AsJob); context.setJob(job); command.setExecutionContext(context); } } catch (Exception e) { log.errorFormat("Failed to prepare command of type {0} for monitoring due to error {1}", actionType.name(), ExceptionUtils.getMessage(e), e); } }</code><technical_language>I said, if u creating create commandBase, if u need other place other method, reason create unused object a force JVM remove them</technical_language>

Target:
public static void prepareCommandForMonitoring(CommandBase<?> command, VdcActionType actionType, boolean runAsInternal) { ExecutionContext context = command.getExecutionContext(); if (context == null) { context = new ExecutionContext(); } try { boolean isMonitored = shouldMonitorCommand(actionType, runAsInternal); context.setMonitored(isMonitored); if (isMonitored) { Job job = createJob(actionType, command); JobRepositoryFactory.getJobRepository().saveJob(job); context.setExecutionMethod(ExecutionMethod.AsJob); context.setJob(job); command.setExecutionContext(context); } } catch (Exception e) { log.errorFormat("Failed to prepare command of type {0} for monitoring due to error {1}", actionType.name(), ExceptionUtils.getMessage(e), e); } }
Source:
<code>public void clearMemory() { final Iterator<Map.Entry<String,Bitmap>> iterator = cache.entrySet().iterator(); while (iterator.hasNext()) { iterator.next(); <START> iterator.remove(); <END> } currentSize = 0; }</code><technical_language>want call recycle Bitmap here</technical_language>

Target:
public void clearMemory() { final Iterator<Map.Entry<String,Bitmap>> iterator = cache.entrySet().iterator(); while (iterator.hasNext()) { final Bitmap bitmap = iterator.next().getValue(); bitmap.recycle(); iterator.remove(); } currentSize = 0; }
Source:
<code>private NotifierInfo populateNotifierInfo (Map notificationSinkConfig) { NotifierInfo notifierInfo = new NotifierInfo(); Map notifierInfoConfig = (Map) notificationSinkConfig.get(TopologyLayoutConstants.JSON_KEY_CONFIG); notifierInfo.setNotifierName((String) notifierInfoConfig.get(TopologyLayoutConstants.JSON_KEY_NOTIFIER_NAME)); notifierInfo.setClassName((String) notifierInfoConfig.get(TopologyLayoutConstants.JSON_KEY_NOTIFIER_CLASSNAME)); notifierInfo.setJarFileName((String) notifierInfoConfig.get(TopologyLayoutConstants.JSON_KEY_NOTIFIER_JAR_FILENAME)); <START> String[] fieldNames = { <END> TopologyLayoutConstants.JSON_KEY_NOTIFIER_FROM, TopologyLayoutConstants.JSON_KEY_NOTIFIER_TO, TopologyLayoutConstants.JSON_KEY_NOTIFIER_SUBJECT, TopologyLayoutConstants.JSON_KEY_NOTIFIER_CONTENT_TYPE, TopologyLayoutConstants.JSON_KEY_NOTIFIER_BODY }; notifierInfo.setFieldValues(this.getFieldValues(notifierInfoConfig, fieldNames)); String[] propertyNames = { TopologyLayoutConstants.JSON_KEY_NOTIFIER_HOST, TopologyLayoutConstants.JSON_KEY_NOTIFIER_PORT, TopologyLayoutConstants.JSON_KEY_NOTIFIER_SSL, TopologyLayoutConstants.JSON_KEY_NOTIFIER_STARTTLS, TopologyLayoutConstants.JSON_KEY_NOTIFIER_PROTOCOL, TopologyLayoutConstants.JSON_KEY_NOTIFIER_USERNAME, TopologyLayoutConstants.JSON_KEY_NOTIFIER_PASSWORD, TopologyLayoutConstants.JSON_KEY_NOTIFIER_AUTH, TopologyLayoutConstants.JSON_KEY_NOTIFIER_DEBUG }; notifierInfo.setProperties(this.getProperties(notifierInfoConfig, propertyNames)); return notifierInfo; }</code><technical_language>hard code fields differ for notifier. convert field values fieldValues Map</technical_language>

Target:
private NotifierInfo populateNotifierInfo (Map notificationSinkConfig) { NotifierInfo notifierInfo = new NotifierInfo(); Map notifierInfoConfig = (Map) notificationSinkConfig.get(TopologyLayoutConstants.JSON_KEY_CONFIG); notifierInfo.setName((String) notifierInfoConfig.get(TopologyLayoutConstants.JSON_KEY_NOTIFIER_NAME)); notifierInfo.setClassName((String) notifierInfoConfig.get(TopologyLayoutConstants.JSON_KEY_NOTIFIER_CLASSNAME)); notifierInfo.setJarFileName((String) notifierInfoConfig.get(TopologyLayoutConstants.JSON_KEY_NOTIFIER_JAR_FILENAME)); Map properties = (Map) notifierInfoConfig.get(TopologyLayoutConstants.JSON_KEY_NOTIFIER_PROPERTIES); notifierInfo.setProperties(convertMapValuesToString(properties)); Map fieldValues = (Map) notifierInfoConfig.get(TopologyLayoutConstants.JSON_KEY_NOTIFIER_FIELD_VALUES); notifierInfo.setFieldValues(convertMapValuesToString(fieldValues)); return notifierInfo; }
Source:
<code>public void recount() { count = 0; for(char type : types) { <START> if (type != 0) count++; <END> } }</code><technical_language>Prefer braces if if single-line, I think</technical_language>

Target:
public void recount() { count = 0; for(char type : types) { if (type != 0) { count++; } } }
Source:
<code>public void testWhenAnyComplete() throws Exception { assertGetUncheckedListenable(future -> getFutureValue(MoreFutures.whenAnyComplete(ImmutableList.of(SettableFuture.create(), future, SettableFuture.create())))); <START> assertFailure(() -> MoreFutures.whenAnyComplete(null), e -> assertInstanceOf(e, NullPointerException.class)); <END> assertFailure(() -> MoreFutures.whenAnyComplete(ImmutableList.of()), e -> assertInstanceOf(e, IllegalArgumentException.class)); assertEquals(tryGetFutureValue(MoreFutures.whenAnyComplete(ImmutableList.of(SettableFuture.create(), SettableFuture.create())), 10, MILLISECONDS), Optional.empty()); }</code><technical_language>Static import</technical_language>

Target:
public void testWhenAnyComplete() throws Exception { assertGetUncheckedListenable(future -> getFutureValue(whenAnyComplete(ImmutableList.of(SettableFuture.create(), future, SettableFuture.create())))); assertFailure(() -> whenAnyComplete(null), e -> assertInstanceOf(e, NullPointerException.class)); assertFailure(() -> whenAnyComplete(ImmutableList.of()), e -> assertInstanceOf(e, IllegalArgumentException.class)); assertEquals( tryGetFutureValue(whenAnyComplete(ImmutableList.of(SettableFuture.create(), SettableFuture.create())), 10, MILLISECONDS), Optional.empty()); }
Source:
<code>protected void executeQueryCommand() { <START> GlusterVolumeEntity volumeCheck = glusterVolumeDao.getByName(getParameters().getClusterId(), <END> getGlusterVolumeName(getParameters().getVolumeId())); boolean nfs = volumeCheck.isNfsEnabled() && getParameters().isNfs(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeProfileInfo, new GlusterVolumeProfileInfoVDSParameters(getParameters().getClusterId(), getUpServerId(getParameters().getClusterId()), getGlusterVolumeName(getParameters().getVolumeId()), nfs)); GlusterVolumeProfileInfo profileInfo = (GlusterVolumeProfileInfo) returnValue.getReturnValue(); if (!nfs) { populateBrickNames(profileInfo); } getQueryReturnValue().setReturnValue(profileInfo); }</code><technical_language>missed this before, do: GlusterVolumeEntity volumeCheck = glusterVolumeDao.getById(getParameters().getVolumeId());</technical_language>

Target:
protected void executeQueryCommand() { GlusterVolumeEntity volumeCheck = glusterVolumeDao.getById(getParameters().getVolumeId()); boolean nfs = volumeCheck.isNfsEnabled() && getParameters().isNfs(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeProfileInfo, new GlusterVolumeProfileInfoVDSParameters(getParameters().getClusterId(), getUpServerId(getParameters().getClusterId()), getGlusterVolumeName(getParameters().getVolumeId()), nfs)); GlusterVolumeProfileInfo profileInfo = (GlusterVolumeProfileInfo) returnValue.getReturnValue(); if (!nfs) { populateBrickNames(profileInfo); } getQueryReturnValue().setReturnValue(profileInfo); }
Source:
<code>public Mono<Void> uploadFromFile(String uploadFilePath, FileRangeWriteType type) { AsynchronousFileChannel channel = channelSetup(uploadFilePath); return Flux.fromIterable(sliceFile(uploadFilePath)) .flatMap(chunk -> { return upload(FluxUtil.byteBufStreamFromFile(channel, chunk.start(), chunk.end() - chunk.start() + 1), chunk.end() - chunk.start() + 1, chunk.start(), type) <START> .timeout(Duration.ofSeconds(300)) <END> .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException); }) .then() .doOnTerminate(() -> channelCleanUp(channel)); }</code><technical_language>questions for timeout retry</technical_language>

Target:
public Mono<Void> uploadFromFile(String uploadFilePath, FileRangeWriteType type) { AsynchronousFileChannel channel = channelSetup(uploadFilePath); return Flux.fromIterable(sliceFile(uploadFilePath)) .flatMap(chunk -> { return upload(FluxUtil.byteBufStreamFromFile(channel, chunk.start(), chunk.end() - chunk.start() + 1), chunk.end() - chunk.start() + 1, chunk.start(), type) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException); }) .then() .doOnTerminate(() -> channelCleanUp(channel)); }
Source:
<code><START> public static synchronized void deleteDatabase(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { <END> StringBuffer dbName = new StringBuffer(dbNamePrefix); if (account != null) { final String accountSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(accountSuffix); } dbName.append(DB_NAME_SUFFIX); final String fullDBName = dbName.toString(); final DBOpenHelper helper = openHelpers.get(fullDBName); if (helper != null) { helper.close(); openHelpers.remove(fullDBName); } ctx.deleteDatabase(fullDBName); if (account != null && TextUtils.isEmpty(communityId)) { StringBuffer communityDBNamePrefix = new StringBuffer(dbNamePrefix); String accountSuffix = account.getUserLevelFilenameSuffix(); communityDBNamePrefix.append(accountSuffix); final String dbPath = ctx.getApplicationInfo().dataDir + "/databases"; final File dir = new File(dbPath); if (dir != null) { final SmartStoreFileFilter fileFilter = new SmartStoreFileFilter(communityDBNamePrefix.toString()); final File[] fileList = dir.listFiles(); if (fileList != null) { for (final File file : fileList) { if (file != null && fileFilter.accept(dir, file.getName())) { file.delete(); openHelpers.remove(file.getName()); } } } } } }</code><technical_language>happened defaultHelper? need defaultHelper for unauthenticated context. some tests SmartStore in unauthenticated context. For this context, supporting ability name DB though</technical_language>

Target:
public static synchronized void deleteDatabase(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { try { StringBuffer dbName = new StringBuffer(dbNamePrefix); if (account != null) { final String accountSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(accountSuffix); } dbName.append(DB_NAME_SUFFIX); final String fullDBName = dbName.toString(); final DBOpenHelper helper = openHelpers.get(fullDBName); if (helper != null) { helper.close(); openHelpers.remove(fullDBName); } ctx.deleteDatabase(fullDBName); if (account != null && TextUtils.isEmpty(communityId)) { StringBuffer communityDBNamePrefix = new StringBuffer(dbNamePrefix); String accountSuffix = account.getUserLevelFilenameSuffix(); communityDBNamePrefix.append(accountSuffix); final String dbPath = ctx.getApplicationInfo().dataDir + "/databases"; final File dir = new File(dbPath); if (dir != null) { final SmartStoreFileFilter fileFilter = new SmartStoreFileFilter(communityDBNamePrefix.toString()); final File[] fileList = dir.listFiles(); if (fileList != null) { for (final File file : fileList) { if (file != null && fileFilter.accept(dir, file.getName())) { file.delete(); openHelpers.remove(file.getName()); } } } } } } catch (Exception e) { Log.e("DBOpenHelper:deleteDatabase", "Exception occurred while attempting to delete database.", e); } }
Source:
<code>private void populateCube(Cube cube) { int cubeX = cube.getX(); int cubeY = cube.getY(); int cubeZ = cube.getZ(); cubeGen.getPopulationRequirement(cube).forEachPoint((x, y, z) -> { Cube popcube = getCube(x + cubeX, y + cubeY, z + cubeZ); if (!popcube.isPopulated()) { cubeGen.populate(popcube); popcube.setPopulated(true); } }); <START> if (CubicChunks.Config.BoolOptions.USE_VANILLA_CHUNK_WORLD_GENERATORS.getValue()) { <END> for (int y = 15; y >= 0; y--) { Cube popcube = getCube(cubeX, y + cubeY, cubeZ); if (!popcube.isPopulated()) { cubeGen.populate(popcube); popcube.setPopulated(true); } } GameRegistry.generateWorld(cubeX, cubeZ, world, chunkGenerator, this); } cube.setFullyPopulated(true); }</code><technical_language>want check if compatibility generator avoid twice. I right generate cubes offset 1 in x z direction (there is 8 blocks offset in population). compatibility generator do that</technical_language>

Target:
private void populateCube(Cube cube) { int cubeX = cube.getX(); int cubeY = cube.getY(); int cubeZ = cube.getZ(); cubeGen.getPopulationRequirement(cube).forEachPoint((x, y, z) -> { Cube popcube = getCube(x + cubeX, y + cubeY, z + cubeZ); if (!popcube.isPopulated()) { cubeGen.populate(popcube); popcube.setPopulated(true); } }); if (!(cubeGen instanceof VanillaCompatibilityGenerator) && CubicChunks.Config.BoolOptions.USE_VANILLA_CHUNK_WORLD_GENERATORS.getValue()) { for (int x = 0; x < 2; x++) { for (int z = 0; z < 2; z++) { for (int y = 15; y >= 0; y--) { Cube popcube = getCube(x + cubeX, y + cubeY, z + cubeZ); if (!popcube.isPopulated()) { cubeGen.populate(popcube); popcube.setPopulated(true); } } } } GameRegistry.generateWorld(cubeX, cubeZ, world, chunkGenerator, this); } cube.setFullyPopulated(true); }
Source:
<code>private IStatus validateMappings(ResourceMapping[] mappings) { for (ResourceMapping mapping : mappings) { if (mapping instanceof EMFResourceMapping && mapping.getModelObject() instanceof StorageTraversal) { final StorageTraversal traversal = (StorageTraversal)mapping.getModelObject(); <START> if (traversal.getDiagnostic().getSeverity() != Diagnostic.OK) { <END> return BasicDiagnostic.toIStatus(traversal.getDiagnostic()); } } else { return new Status(IStatus.ERROR, EMFCompareIDEUIPlugin.PLUGIN_ID, EMFCompareIDEUIMessages .getString("EMFResourceMappingMerger.mergeFailedInvalidMapping")); } } return Status.OK_STATUS; }</code><technical_language>i suggest change tests for getSeverity() >= Diagnostic.WARNING</technical_language>

Target:
private IStatus validateMappings(ResourceMapping[] mappings) { for (ResourceMapping mapping : mappings) { if (mapping instanceof EMFResourceMapping && mapping.getModelObject() instanceof StorageTraversal) { final StorageTraversal traversal = (StorageTraversal)mapping.getModelObject(); if (traversal.getDiagnostic().getSeverity() >= Diagnostic.WARNING) { return BasicDiagnostic.toIStatus(traversal.getDiagnostic()); } } else { return new Status(IStatus.ERROR, EMFCompareIDEUIPlugin.PLUGIN_ID, EMFCompareIDEUIMessages .getString("EMFResourceMappingMerger.mergeFailedInvalidMapping")); } } return Status.OK_STATUS; }
Source:
<code><START> private HashMap<ArchitectureType, HashMap<Version, Boolean>> getMap(ArchCapabilitiesVerb archCapabilitiesVerb) { <END> HashMap<ArchitectureType, HashMap<Version, Boolean>> supportMap = new HashMap<ArchitectureType, HashMap<Version, Boolean>>(); for (ArchitectureType arch : ArchitectureType.values()) { HashMap<Version, Boolean> archMap = new HashMap<Version, Boolean>(); for (Version version : Version.ALL) { boolean isSupported = isSupported(archCapabilitiesVerb, arch, version); archMap.put(version, isSupported); } supportMap.put(arch, archMap); } return supportMap; }</code><technical_language>declare a Hashmap simply a Map</technical_language>

Target:
private Map<ArchitectureType, Map<Version, Boolean>> getMap(ArchCapabilitiesVerb archCapabilitiesVerb) { if (verbMap.containsKey(archCapabilitiesVerb)) { return verbMap.get(archCapabilitiesVerb); } else { Map<ArchitectureType, Map<Version, Boolean>> supportMap = new HashMap<ArchitectureType, Map<Version, Boolean>>(); for (ArchitectureType arch : ArchitectureType.values()) { Map<Version, Boolean> archMap = new HashMap<Version, Boolean>(); for (Version version : Version.ALL) { boolean isSupported = isSupported(archCapabilitiesVerb, arch, version); archMap.put(version, isSupported); } supportMap.put(arch, archMap); } verbMap.put(archCapabilitiesVerb, supportMap); return supportMap; } }
Source:
<code>public Object call() throws Exception { ObjectReader or = block.templateReader.newReader(); try { for (;;) { Slice s; synchronized (this) { if (slices.isEmpty()) break; <START> s = slices.removeFirst(); <END> } doSlice(or, s); } for (Slice s = block.stealWork(); s != null; s = block.stealWork()) doSlice(or, s); } finally { or.release(); block.pm.endWorker(); } return null; }</code><technical_language>is a race dw = null selecting next. i.e. more work dw assigned yet. set dw in this synchronized loop too. doSlice refactored newDeltaWorker() a runWorker(). private void setWorker(ObjectReader or, Slice s) throws IOException { DeltaWindow w = new DeltaWindow(block.config, block.dc, or, block.pm, block.list, s.beginIndex, s.endIndex); synchronized (this) { dw = w; } } private void runWorker() throws IOException { DeltaWorker w; synchronized (this) { w = dw; } w.search(); synchronized (this) { dw = null; } }</technical_language>

Target:
public Object call() throws Exception { ObjectReader or = block.templateReader.newReader(); try { for (;;) { Slice s; synchronized (this) { if (slices.isEmpty()) break; s = slices.removeFirst(); } runWorker(or, s); } for (Slice s = block.stealWork(); s != null; s = block.stealWork()) runWorker(or, s); } finally { or.release(); block.pm.endWorker(); } return null; }
Source:
<code>static Status run(List<String> command, File workingDirectory, long timeout) throws ProcessException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(workingDirectory); TimeLimitProcess p; try { p = new TimeLimitProcess(processBuilder.start(), timeout, true); } catch (IOException e) { throw new ProcessException("Exception starting process", e); } int exitValue; try { exitValue = p.waitFor(); } catch (InterruptedException e) { throw new ProcessException("Exception running process", e); } List<String> standardOutputLines; try { standardOutputLines = StreamUtils.captureLinesFromStream(p.getInputStream()); } catch (IOException e) { throw new ProcessException("Exception getting process stream output", e); } List<String> errorOutputLines; try { errorOutputLines = StreamUtils.captureLinesFromStream(p.getErrorStream()); } catch (IOException e) { throw new ProcessException("Error getting process error output", e); } if (p.timed_out()) { for (String line : standardOutputLines) { System.out.println(line); } <START> assert !p.timed_out() : "Process timed out after " + p.timeout_msecs() + " msecs"; <END> } return new Status(command, exitValue, standardOutputLines, errorOutputLines); }</code><technical_language>confusing assert conditioned a predicate returns false. throw exception unconditionally</technical_language>

Target:
static Status run(List<String> command, File workingDirectory, long timeout) throws CommandException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(workingDirectory); TimeLimitProcess p; try { p = new TimeLimitProcess(processBuilder.start(), timeout, true); } catch (IOException e) { throw new CommandException("Exception starting process", e); } int exitValue = -1; try { exitValue = p.waitFor(); } catch (InterruptedException e) { } List<String> standardOutputLines; try { standardOutputLines = UtilMDE.streamLines(p.getInputStream()); } catch (IOException e) { throw new CommandException("Exception getting process standard output", e); } List<String> errorOutputLines; try { errorOutputLines = UtilMDE.streamLines(p.getErrorStream()); } catch (IOException e) { throw new CommandException("Exception getting process error output", e); } return new Status(command, exitValue, p.timed_out(), standardOutputLines, errorOutputLines); }
Source:
<code>public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(invoker, args); } String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { if ("toString".equals(methodName)) { return invoker.toString(); } else if ("$destroy".equals(methodName)) { invoker.destroy(); return null; } else if ("hashCode".equals(methodName)) { return invoker.hashCode(); } } else if (parameterTypes.length == 1 && "equals".equals(methodName)) { return invoker.equals(args[0]); } RpcInvocation rpcInvocation = new RpcInvocation(method, invoker.getInterface().getName(), args); String serviceKey = invoker.getUrl().getServiceKey(); if (serviceKey != null) { rpcInvocation.setTargetServiceUniqueName(serviceKey); <START> ConsumerModel consumerModel = ApplicationModel.getConsumerModel(serviceKey); <END> rpcInvocation.put("consumerModel", consumerModel); } return invoker.invoke(rpcInvocation).recreate(); }</code><technical_language>I put ConsumerModel in constructor,because change get performance</technical_language>

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(invoker, args); } String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { if ("toString".equals(methodName)) { return invoker.toString(); } else if ("$destroy".equals(methodName)) { invoker.destroy(); return null; } else if ("hashCode".equals(methodName)) { return invoker.hashCode(); } } else if (parameterTypes.length == 1 && "equals".equals(methodName)) { return invoker.equals(args[0]); } RpcInvocation rpcInvocation = new RpcInvocation(method, invoker.getInterface().getName(), args); String serviceKey = invoker.getUrl().getServiceKey(); rpcInvocation.setTargetServiceUniqueName(serviceKey); if (consumerModel != null) { rpcInvocation.put(Constants.CONSUMER_MODEL, consumerModel); rpcInvocation.put(Constants.METHOD_MODEL, consumerModel.getMethodModel(method)); } return invoker.invoke(rpcInvocation).recreate(); }
Source:
<code>public void testFilenameBatchedUnique() throws Exception { ExportToFileClient client = new ExportToFileClient(); Properties props = new Properties(); props.put("nonce", Long.toString(System.currentTimeMillis())); props.put("type", "csv"); props.put("outdir", m_dir); props.put("period", "1"); props.put("with-schema", "true"); props.put("batched", "true"); props.put("uniquenames", "true"); client.configure(props); final AdvertisedDataSource source = constructTestSource(false, 0); final ExportToFileClient.ExportToFileDecoder decoder = client.constructExportDecoder(source); long l = System.currentTimeMillis(); vtable.addRow(l, l, l, 0, l, l, (byte) 1, (short) 2, 3, 4, 5.5, 6, "xx", new BigDecimal(88), GEOG_POINT, GEOG); vtable.advanceRow(); byte[] rowBytes = ExportEncoder.encodeRow(vtable, "mytable", 0, 1L); ExportRow row = ExportRow.decodeRow(null, 0, 0L, rowBytes); decoder.onBlockStart(row); decoder.processRow(row); decoder.onBlockCompletion(row); boolean validName = true; final File dir = new File(m_dir); final File[] subdirs = dir.listFiles(); List<File> remainingFiles = new ArrayList<>(); if (subdirs != null) { for (File file : subdirs) { if (file.isDirectory()) { remainingFiles.addAll(Arrays.asList(file.listFiles())); } <START> else if (!file.getName().matches("\\d\\-mytable\\-\\(\\d\\).*\\.[a-z]{3,4}")) { <END> validName = false; break; } } for (File file : remainingFiles) { if (!file.getName().matches("\\d\\-mytable\\-\\(\\d\\).*\\.[a-z]{3,4}")) { validName = false; break; } } } assertTrue(validName); }</code><technical_language>Also, I need .* regex for extension</technical_language>

Target:
public void testFilenameBatchedUnique() throws Exception { ExportToFileClient client = new ExportToFileClient(); Properties props = new Properties(); props.put("nonce", Long.toString(System.currentTimeMillis())); props.put("type", "csv"); props.put("outdir", m_dir); props.put("period", "1"); props.put("with-schema", "true"); props.put("batched", "true"); props.put("uniquenames", "true"); client.configure(props); final AdvertisedDataSource source = constructTestSource(false, 0); final ExportToFileClient.ExportToFileDecoder decoder = client.constructExportDecoder(source); long l = System.currentTimeMillis(); vtable.addRow(l, l, l, 0, l, l, (byte) 1, (short) 2, 3, 4, 5.5, 6, "xx", new BigDecimal(88), GEOG_POINT, GEOG); vtable.advanceRow(); byte[] rowBytes = ExportEncoder.encodeRow(vtable, "mytable", 0, 1L); ExportRow row = ExportRow.decodeRow(null, 0, 0L, rowBytes); decoder.onBlockStart(row); decoder.processRow(row); decoder.onBlockCompletion(row); boolean validName = true; final File dir = new File(m_dir); final File[] subdirs = dir.listFiles(); List<File> allFiles = new ArrayList<>(); if (subdirs != null) { for (File file : subdirs) { if (file.isDirectory()) { allFiles.addAll(Arrays.asList(file.listFiles())); } else { allFiles.add(file); } } for (File file : allFiles) { if (!(file.getName().matches("\\d\\-mytable\\-\\(\\d\\)\\.[a-z]{3}")||file.getName().matches("\\d\\-mytable\\-\\(\\d\\)-schema\\.json"))) { validName = false; break; } } } assertTrue(validName); }
Source:
<code>private Object transform(ConfigKey<?> key, Object value) { if (value instanceof CharSequence) { String raw = value.toString(); if (raw.startsWith(EXTERNAL_CONFIG_PREFIX)) { <START> CampYamlParser parser = mgmt.getConfig().getConfig(CampYamlParser.YAML_PARSER_KEY); <END> if (parser == null) { LOG.debug("Not transforming external-config {}, as no camp-yaml parser available", key); return value; } return parser.parse(raw); } } return value; }</code><technical_language>startsWith("$brooklyn:)</technical_language>

Target:
private Object transform(ConfigKey<?> key, Object value) { if (value instanceof CharSequence) { String raw = value.toString(); if (raw.startsWith(BROOKLYN_YAML_PREFIX)) { CampYamlParser parser = mgmt.getConfig().getConfig(CampYamlParser.YAML_PARSER_KEY); if (parser == null) { LOG.debug("Not transforming external-config {}, as no camp-yaml parser available", key); return value; } return parser.parse(raw); } } return value; }
Source:
<code>public FilesWatcher() { <START> watchers = new ConcurrentHashMap<>(); <END> executorPollTime = getPollTimeOrDefault(); init(); }</code><technical_language>simply do this(getPollTimeOrDefault()); instead</technical_language>

Target:
public FilesWatcher() { executorPollTime = getPollTimeOrDefault(); init(); }
Source:
<code>static String getVarName(Path path) { return "Var_" + Hashing.sha256() <START> .hashString(MorePaths.pathWithUnixSeparators(path.getFileName()), Charsets.UTF_8) <END> .toString() .substring(0, 10); }</code><technical_language>MorePaths.pathWithUnixSeparators? getFileName include name of file separators</technical_language>

Target:
static String getVarName(Path path) { return "Var_" + Hashing.sha256().hashString(path.getFileName().toString(), Charsets.UTF_8); }
Source:
<code><START> public void testGetDiagram(){ <END> final CanvasHandler handler = mock(CanvasHandler.class); doNothing().when(presenter).refreshTreeView(); final Diagram expectedDiagram = mock(Diagram.class); doReturn(expectedDiagram).when(handler).getDiagram(); presenter.setHandler(handler); final Diagram actual = presenter.getDiagram(); assertEquals(expectedDiagram, actual); }</code><technical_language>I a format issue here: suggestion public void testGetDiagram() {</technical_language>

Target:
public void testGetDiagram() { final CanvasHandler handler = mock(CanvasHandler.class); final Diagram expectedDiagram = mock(Diagram.class); doNothing().when(presenter).refreshTreeView(); doReturn(expectedDiagram).when(handler).getDiagram(); presenter.setHandler(handler); final Diagram actual = presenter.getDiagram(); assertEquals(expectedDiagram, actual); }