auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void writeInstalled() { record.setStatus(ApplicationRecord.STATUS_INSTALLED); <START> record.setUniqueId(getUniqueId()); <END> record.setDisplayName(getDisplayName()); record.setResourcesStatus(areResourcesValidated()); record.setPreMultipleAppsProfile(checkFromOldProfile()); try { CommCareApplication._().getGlobalStorage(ApplicationRecord.class).write(record); } catch (StorageFullException e) { throw new RuntimeException(e); } }</code><technical_language>explicitly set this currently upgrade, is a circumstance this need get called install process? Is this default set? dangerous configured profile, fetching transfering property own. sense call "record.initProfileProperties(getprofile())" do is clear is a one-time transfer? pattern is like: foo.setBar(getBar()) getBar() { if(foo.getBar() == something){ return soemthing } return foo.Bar(); } model depends _and_ sets of a property, in mind happen once</technical_language>

Target:
public void writeInstalled() { record.setStatus(ApplicationRecord.STATUS_INSTALLED); record.setResourcesStatus(areMMResourcesValidated()); record.setPropertiesFromProfile(getCommCarePlatform().getCurrentProfile()); try { CommCareApplication._().getGlobalStorage(ApplicationRecord.class).write(record); } catch (StorageFullException e) { throw new RuntimeException(e); } }
Source:
<code>public boolean isValidBackupDir(File keyspaceDir, File columnFamilyDir, File backupDir) { if (!backupDir.isDirectory() && !backupDir.exists()) return false; String keyspaceName = keyspaceDir.getName(); if (FILTER_KEYSPACE.contains(keyspaceName)) { logger.debug(keyspaceName + " is not consider a valid keyspace backup directory, will be bypass."); return false; } String dirName = columnFamilyDir.getName(); <START> String columnFamilyName = dirName.split("-")[0]; <END> if (FILTER_COLUMN_FAMILY.containsKey(keyspaceName) && FILTER_COLUMN_FAMILY.get(keyspaceName).contains(columnFamilyName)) { logger.debug(dirName + " is not consider a valid CF backup directory, will be bypass."); return false; } return true; }</code><technical_language>This assumes directory for CF is a hyphen. code is compatible, delimiter a configurable property</technical_language>

Target:
public boolean isValidBackupDir(File keyspaceDir, File columnFamilyDir, File backupDir) { if (!backupDir.isDirectory() && !backupDir.exists()) return false; String keyspaceName = keyspaceDir.getName(); if (FILTER_KEYSPACE.contains(keyspaceName)) { logger.debug(keyspaceName + " is not consider a valid keyspace backup directory, will be bypass."); return false; } String columnFamilyName = columnFamilyDir.getName(); if (FILTER_COLUMN_FAMILY.containsKey(keyspaceName) && FILTER_COLUMN_FAMILY.get(keyspaceName).contains(columnFamilyName)) { logger.debug(columnFamilyName + " is not consider a valid CF backup directory, will be bypass."); return false; } return true; }
Source:
<code>public void onAppendColumnEvent() { AppendColumnEvent event = new AppendColumnEvent(COLUMN_GROUP); scenarioSimulationEventHandler.onEvent(event); verify(scenarioSimulationEventHandler, times(1)).commonExecution(eq(scenarioSimulationContextLocal), isA(AppendColumnCommand.class)); <START> verify(scenarioGridPanelMock).setFocus(true); <END> }</code><technical_language>@jomarko If is move "context.getScenarioGridPanel().setFocus(true);" commonExecution, move this "verify(scenarioGridPanelMock).setFocus(true);" "commonExecution" Test</technical_language>

Target:
public void onAppendColumnEvent() { AppendColumnEvent event = new AppendColumnEvent(COLUMN_GROUP); scenarioSimulationEventHandler.onEvent(event); verify(scenarioSimulationEventHandler).commonExecution(eq(scenarioSimulationContextLocal), isA(AppendColumnCommand.class), eq(true)); }
Source:
<code>void queueViewPortChange( @NotNull String path, @Nullable Editor editor, @Nullable LineRange range, @Nullable TextSelection selection) { QueuedViewPortChange requestedViewportChange = new QueuedViewPortChange(editor, range, selection); QueuedViewPortChange previouslyQueuedRequest = queuedViewPortChanges.put(path, requestedViewportChange); <START> if (previouslyQueuedRequest != null) { <END> if (log.isTraceEnabled()) { log.trace( "Dropping previously queued viewport change request for " + path + "; old request: " + previouslyQueuedRequest + ", new request: " + requestedViewportChange); } } }</code><technical_language>remain if remove toString method</technical_language>

Target:
void queueViewPortChange( @NotNull String path, @Nullable Editor editor, @Nullable LineRange range, @Nullable TextSelection selection) { QueuedViewPortChange requestedViewportChange = new QueuedViewPortChange(editor, range, selection); queuedViewPortChanges.put(path, requestedViewportChange); }
Source:
<code>public Laplace(List params) { <START> if (params.size() == 0) { <END> fixedMean = false; fixedDiversity = false; } else if (params.size() == 1) { fixedMean = false; fixedDiversity = true; setDiversity(params.get(0)); } else if (params.size() == 2) { fixedMean = true; setMean(params.get(0)); fixedDiversity = true; setDiversity(params.get(1)); } else { throw new IllegalArgumentException( "Laplace CPD expects at most 2 parameters, not " + params.size()); } }</code><technical_language>implementation modified</technical_language>

Target:
public Laplace(List params) { if (params.size() == 0) { expectMeanAsArg = true; expectDiversityAsArg = true; } else if (params.size() == 1) { expectMeanAsArg = false; expectDiversityAsArg = true; initParams(params); expectMeanAsArg = true; expectDiversityAsArg = false; } else if (params.size() == 2) { expectMeanAsArg = true; expectDiversityAsArg = true; initParams(params); expectMeanAsArg = false; expectDiversityAsArg = false; } else { throw new IllegalArgumentException( "Laplace CPD expects at most 2 parameters, not " + params.size()); } }
Source:
<code>public static MaxAttemptsBuilder builder() { <START> return new MaxAttemptsBuilder(DEFAULT_THREAD_SLEEP); <END> }</code><technical_language>suggestion return builder(DEFAULT_THREAD_SLEEP);</technical_language>

Target:
public static MaxAttemptsBuilder builder() { return builder(DEFAULT_THREAD_SLEEP); }
Source:
<code>private static FileMetrics metrics(String fileName) { File baseDir = new File("src/test/resources/metrics/"); File file = new File(baseDir, fileName); String fileContent; try { fileContent = Files.toString(file, StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException(e); } <START> PyFile pyFile = new org.sonar.python.frontend.PythonParser().parse(fileContent); <END> return new FileMetrics(TestPythonVisitorRunner.createContext(file), true, pyFile); }</code><technical_language>7 lines duplicated in 3 tests in python-squid, factorize them</technical_language>

Target:
private static FileMetrics metrics(String fileName) { File baseDir = new File("src/test/resources/metrics/"); File file = new File(baseDir, fileName); return new FileMetrics(TestPythonVisitorRunner.createContext(file), true, PythonParser.parse(file)); }
Source:
<code>@Test public void testListSavedSearches() { Service service = connect(); SavedSearchCollectionArgs ascArgs = new SavedSearchCollectionArgs(); <START> ascArgs.setSortDir(SortDir.ASC); <END> SavedSearchCollection savedSearchesAsc = service.getSavedSearches(ascArgs); List<String> savedSearchNamesAsc = new ArrayList<String>(savedSearchesAsc.keySet()); SavedSearchCollectionArgs descArgs = new SavedSearchCollectionArgs(); descArgs.setSortDir(SortDir.DESC); SavedSearchCollection savedSearchesDesc = service.getSavedSearches(descArgs); List<String> savedSearchNamesDesc = new ArrayList<String>(savedSearchesDesc.keySet()); List<String> savedSearchNamesDescReversed = savedSearchNamesDesc; Collections.reverse(savedSearchNamesDescReversed); assertEquals(savedSearchNamesAsc, savedSearchNamesDescReversed); }</code><technical_language>abbreviate. Call SortDirection</technical_language>

Target:
@Test public void testListSavedSearches() { Service service = connect(); SavedSearchCollectionArgs ascArgs = new SavedSearchCollectionArgs(); ascArgs.setSortDirection(CollectionArgs.SortDirection.ASC); SavedSearchCollection savedSearchesAsc = service.getSavedSearches(ascArgs); List<String> savedSearchNamesAsc = new ArrayList<String>(savedSearchesAsc.keySet()); SavedSearchCollectionArgs descArgs = new SavedSearchCollectionArgs(); descArgs.setSortDirection(CollectionArgs.SortDirection.DESC); SavedSearchCollection savedSearchesDesc = service.getSavedSearches(descArgs); List<String> savedSearchNamesDesc = new ArrayList<String>(savedSearchesDesc.keySet()); List<String> savedSearchNamesDescReversed = savedSearchNamesDesc; Collections.reverse(savedSearchNamesDescReversed); assertEquals(savedSearchNamesAsc, savedSearchNamesDescReversed); }
Source:
<code>public boolean calculateIsFailure() { <START> int randomValue = random.nextInt(100) + 1; <END> return randomValue <= errorPct; }</code><technical_language>drop + 1 here, < instead of <=</technical_language>

Target:
public boolean calculateIsFailure() { int randomValue = random.nextInt(100); return randomValue < errorPercent; }
Source:
<code>public static TitleMessage[] fromTitle(Title title) { <START> TextMessage titleMessage = title.getTitle() != null ? asTextMessage(BaseComponent.toLegacyText(title.getTitle())) : asTextMessage(null); <END> TextMessage subTitleMessage = title.getSubtitle() != null ? asTextMessage(BaseComponent.toLegacyText(title.getSubtitle())) : asTextMessage(null); return new TitleMessage[]{ new TitleMessage(Action.TITLE, titleMessage), new TitleMessage(Action.SUBTITLE, subTitleMessage), new TitleMessage(Action.TIMES, title.getFadeIn(), title.getStay(), title.getFadeOut()) }; }</code><technical_language>API allow for title null, this check is useless</technical_language>

Target:
public static TitleMessage[] fromTitle(Title title) { TextMessage titleMessage = asTextMessage(BaseComponent.toLegacyText(title.getTitle())); TextMessage subTitleMessage = title.getSubtitle() != null ? asTextMessage(BaseComponent.toLegacyText(title.getSubtitle())) : asTextMessage(null); return new TitleMessage[]{ new TitleMessage(Action.TITLE, titleMessage), new TitleMessage(Action.SUBTITLE, subTitleMessage), new TitleMessage(Action.TIMES, title.getFadeIn(), title.getStay(), title.getFadeOut()) }; }
Source:
<code>public void markCanBeCompleted(Long id) { completedOperationIds.offer(id); <START> if (this.isFlushing.get() && completedOperationIds.size() == pendingOperationsWithSize.size()) { <END> synchronized (this) { notify(); } } }</code><technical_language>sorry! explain a bit isFlushing true "ompletedOperationIds.size() == pendingOperationsWithSize.size()", notify thread waiting "this"</technical_language>

Target:
public void markCanBeCompleted(Long id) { completedOperationIds.offer(id); int inflightOperationCount = pendingOperationCount.decrementAndGet(); if (this.isFlushing.get() && inflightOperationCount <= 0) { int count = 0; synchronized (pendingOperationsWithSize) { cleanupFinishedOperations(); count = pendingOperationsWithSize.size(); } if (count == 0) { synchronized (this) { notifyAll(); } } } }
Source:
<code>public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { <START> runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null, null); <END> }</code><technical_language>call runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false);</technical_language>

Target:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false); }
Source:
<code>public FileBasedConfig openSystemConfig(Config parent, FS fs) { if (systemConfig.get() == null) { systemConfig.compareAndSet(null, createSystemConfig(parent, fs)); } <START> return systemConfig.get(); <END> }</code><technical_language>need call get twice. FileBasedConfig result = systemConfig.get(); if (config == null) { systemConfig.compareAndSet(...); result = systemConfig.get(); } return result;</technical_language>

Target:
public FileBasedConfig openSystemConfig(Config parent, FS fs) { FileBasedConfig c = systemConfig.get(); if (c == null) { systemConfig.compareAndSet(null, createSystemConfig(parent, fs)); c = systemConfig.get(); } return c; }
Source:
<code><START> private EventTypeStatistics validateStatisticsUpdate( <END> final EventTypeStatistics existing, final EventTypeStatistics newStatistics) throws InvalidEventTypeException { if (existing != null && newStatistics == null) { return existing; } if (!Objects.equals(existing, newStatistics)) { throw new InvalidEventTypeException("default statistics must not be changed"); } return newStatistics; }</code><technical_language>I this method return something. simply check if (newStatistics is != null && !Objects.equals(existing, newStatistics)) throw exception in this case. calling method existing, validation is successful</technical_language>

Target:
private void validateStatisticsUpdate( final EventTypeStatistics existing, final EventTypeStatistics newStatistics) throws InvalidEventTypeException { if (!Objects.equals(existing, newStatistics)) { throw new InvalidEventTypeException("default statistics must not be changed"); } }
Source:
<code>public int hashCode() { final int prime = 31; <START> int result = super.hashCode(); <END> result = prime * result + ((fDefinition == null) ? 0 : fDefinition.hashCode()); return result; }</code><technical_language>Needs consider new custom fields</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((fDefinition == null) ? 0 : fDefinition.hashCode()); result = prime * result + ((customEventTimestamp == null) ? 0 : customEventTimestamp.hashCode()); result = prime * result + ((customEventContent == null) ? 0 : customEventContent.hashCode()); result = prime * result + ((customEventType == null) ? 0 : customEventType.hashCode()); return result; }
Source:
<code><START> public CompletionStage<KairosQuery> queryMetrics(final MetricsQuery query) { <END> try { final HttpRequest request = HttpRequest.POST(createUri(METRICS_QUERY_PATH)) .withEntity(ContentTypes.APPLICATION_JSON, _mapper.writeValueAsString(query)); return fireRequest(request, MetricsQueryResponse.class) .thenApply(response -> new KairosQuery.Builder().setRequest(query).setResponse(response).build()); } catch (final JsonProcessingException e) { throw new RuntimeException(e); } }</code><technical_language>naming KairosQuery (the result) MetricsQuery (the request) needs clarified</technical_language>

Target:
public CompletionStage<MetricsQueryResponse> queryMetrics(final MetricsQuery query) { try { final HttpRequest request = HttpRequest.POST(createUri(METRICS_QUERY_PATH).toString()) .withEntity(ContentTypes.APPLICATION_JSON, _mapper.writeValueAsString(query)); return fireRequest(request, MetricsQueryResponse.class); } catch (final JsonProcessingException e) { throw new RuntimeException(e); } }
Source:
<code>private void doOreoLaunch(Context context, View v) { final LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE); assert launcherApps != null; if (!launcherApps.hasShortcutHostPermission()) { <START> return; <END> } LauncherApps.ShortcutQuery query = new LauncherApps.ShortcutQuery(); query.setPackage(shortcutPojo.packageName); query.setShortcutIds(Collections.singletonList(shortcutPojo.getOreoId())); query.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED); List<UserHandle> userHandles = launcherApps.getProfiles(); for (UserHandle userHandle : userHandles) { List<ShortcutInfo> shortcuts = launcherApps.getShortcuts(query, userHandle); if (shortcuts != null && shortcuts.size() > 0 && shortcuts.get(0).isEnabled()) { launcherApps.startShortcut(shortcuts.get(0), v.getClipBounds(), null); return; } } }</code><technical_language>pop a toast here? bug reports "the shortcut launch"</technical_language>

Target:
private void doOreoLaunch(Context context, View v) { final LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE); assert launcherApps != null; if (!launcherApps.hasShortcutHostPermission()) { Toast.makeText(context, context.getString(R.string.shortcuts_no_host_permission), Toast.LENGTH_LONG).show(); return; } LauncherApps.ShortcutQuery query = new LauncherApps.ShortcutQuery(); query.setPackage(shortcutPojo.packageName); query.setShortcutIds(Collections.singletonList(shortcutPojo.getOreoId())); query.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED); List<UserHandle> userHandles = launcherApps.getProfiles(); for (UserHandle userHandle : userHandles) { List<ShortcutInfo> shortcuts = launcherApps.getShortcuts(query, userHandle); if (shortcuts != null && shortcuts.size() > 0 && shortcuts.get(0).isEnabled()) { launcherApps.startShortcut(shortcuts.get(0), v.getClipBounds(), null); return; } } Toast.makeText(context, R.string.application_not_found, Toast.LENGTH_LONG).show(); }
Source:
<code>public static void restoreIndex(final File file, final String alias, String index, final boolean clear) throws DotDataException { if(LicenseUtil.getLevel() >= LicenseLevel.STANDARD.level) { if(UtilMethods.isSet(alias)) { String indexName=APILocator.getESIndexAPI() .getAliasToIndexMap(APILocator.getSiteSearchAPI().listIndices()) .get(alias); if(UtilMethods.isSet(indexName)) index=indexName; } else if(!UtilMethods.isSet(index)) { index=APILocator.getIndiciesAPI().loadIndicies().site_search; } } if(UtilMethods.isSet(index)) { final String indexToRestore=index; new Thread() { public void run() { try { if(clear) APILocator.getESIndexAPI().clearIndex(indexToRestore); APILocator.getESIndexAPI().restoreIndex(file, indexToRestore); Logger.info(this, "finished restoring index "+indexToRestore); } catch(Exception ex) { Logger.error(ESIndexResource.class, "Error restoring "+indexToRestore,ex); }finally { try { <START> HibernateUtil.closeSession(); <END> } catch (DotHibernateException e) { Logger.warn(this, e.getMessage(), e); } } } }.start(); } }</code><technical_language>removed this HibernateUtil.closeSession(); too</technical_language>

Target:
public static void restoreIndex(final File file, final String alias, String index, final boolean clear) throws DotDataException { if(LicenseUtil.getLevel() >= LicenseLevel.STANDARD.level) { if(UtilMethods.isSet(alias)) { String indexName=APILocator.getESIndexAPI() .getAliasToIndexMap(APILocator.getSiteSearchAPI().listIndices()) .get(alias); if(UtilMethods.isSet(indexName)) index=indexName; } else if(!UtilMethods.isSet(index)) { index=APILocator.getIndiciesAPI().loadIndicies().site_search; } } if(UtilMethods.isSet(index)) { final String indexToRestore=index; new Thread() { @CloseDBIfOpened public void run() { try { if(clear) APILocator.getESIndexAPI().clearIndex(indexToRestore); APILocator.getESIndexAPI().restoreIndex(file, indexToRestore); Logger.info(this, "finished restoring index "+indexToRestore); } catch(Exception ex) { Logger.error(ESIndexResource.class, "Error restoring "+indexToRestore,ex); } } }.start(); } }
Source:
<code>public String getQualifiedName() { String name = getName(); if (getParent() == null) { return name == null ? "" : name; } if(name == null && this instanceof HaxeAnonymousType) { HaxeTypedefDeclaration typedefDecl = (HaxeTypedefDeclaration)(getParent().getParent()); if(typedefDecl != null) { <START> name = typedefDecl.getName(); <END> } } final String fileName = FileUtil.getNameWithoutExtension(getContainingFile().getName()); String packageName = HaxeResolveUtil.getPackageName(getContainingFile()); if (name != null && !packageName.isEmpty() && isAncillaryClass(name, fileName)) { packageName = HaxeResolveUtil.joinQName(packageName, fileName); } return HaxeResolveUtil.joinQName(packageName, name); }</code><technical_language>need check if extend for more</technical_language>

Target:
public String getQualifiedName() { String name = getName(); if (getParent() == null) { return name == null ? "" : name; } if(name == null && this instanceof HaxeAnonymousType) { HaxeTypedefDeclaration typedefDecl = (HaxeTypedefDeclaration)(getParent().getParent()); if(typedefDecl != null) { name = typedefDecl.getName(); } } final String fileName = FileUtil.getNameWithoutExtension(getContainingFile().getName()); String packageName = HaxeResolveUtil.getPackageName(getContainingFile()); if (name != null && isAncillaryClass(packageName, name, fileName)) { packageName = HaxeResolveUtil.joinQName(packageName, fileName); } return HaxeResolveUtil.joinQName(packageName, name); }
Source:
<code>private static void mutateRandomly(Connection conn, String tableName, int maxOrgId) { try { Statement stmt = conn.createStatement(); String sqlStr = "UPSERT INTO " + tableName + " VALUES(?, ?, ?, ?)"; PreparedStatement stmt = conn.prepareStatement(sqlStr); for (int i = 0; i < 10000; i++) { <START> stmt.setString(1, getRandomOrgId(maxOrgId); <END> stmt.setInt(2, i); stmt.setInt(3, i + 1); stmt.setInt(4, i + 2); stmt.executeUpdate(); } conn.commit(); } catch (Exception e) { LOG.error("Client side exception:" + e); } }</code><technical_language>missing closing parenthesis</technical_language>

Target:
private static void mutateRandomly(Connection conn, String tableName, int maxOrgId) { try { String sqlStr = "UPSERT INTO " + tableName + " VALUES(?, ?, ?, ?)"; PreparedStatement stmt = conn.prepareStatement(sqlStr); for (int i = 0; i < 10000; i++) { stmt.setString(1, getRandomOrgId(maxOrgId)); stmt.setInt(2, i); stmt.setInt(3, i + 1); stmt.setInt(4, i + 2); stmt.executeUpdate(); } conn.commit(); } catch (Exception e) { LOGGER.error("Client side exception:" + e); } }
Source:
<code>private BinaryContent getBinaryContentFromZip(String filePath) throws CatalogTransformerException { BinaryContent binaryContent; InputStream fileInputStream; File zipFile = new File(filePath); try { fileInputStream = new ZipInputStream(new FileInputStream(zipFile)); binaryContent = new BinaryContentImpl(fileInputStream); } catch (FileNotFoundException e) { throw new CatalogTransformerException("Unable to get ZIP file from ZipInputStream.", e); } jarSigner.signJar( zipFile, <START> System.getProperty(SystemBaseUrl.EXTERNAL_HOST), <END> AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword")), AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStore")), AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword"))); return binaryContent; }</code><technical_language>Missed this one</technical_language>

Target:
private BinaryContent getBinaryContentFromZip(String filePath) throws CatalogTransformerException { BinaryContent binaryContent; InputStream fileInputStream; File zipFile = new File(filePath); try { fileInputStream = new ZipInputStream(new FileInputStream(zipFile)); binaryContent = new BinaryContentImpl(fileInputStream); } catch (FileNotFoundException e) { throw new CatalogTransformerException("Unable to get ZIP file from ZipInputStream.", e); } jarSigner.signJar( zipFile, AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty(SystemBaseUrl.EXTERNAL_HOST)), AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword")), AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStore")), AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword"))); return binaryContent; }
Source:
<code>private void generateNewPassword(U userAccount) { assertNotNew(userAccount); if (!userAccount.getUserAccountData().isPasswordGenerationPossible()) { throw Exceptions.createHandled() .withNLSKey("UserAccountConroller.cannotGeneratePasswordForOwnUser") .handle(); } <START> userAccount.getUserAccountData().getLogin().forceGenerationOfPassword(null); <END> userAccount.getMapper().update(userAccount); auditLog.neutral("AuditLog.passwordGenerated") .causedByCurrentUser() .forUser(userAccount.getUniqueName(), userAccount.getUserAccountData().getLogin().getUsername()) .forTenant(String.valueOf(userAccount.getTenant().getId()), userAccount.getTenant().getValue().getTenantData().getName()) .log(); }</code><technical_language>unneccessary</technical_language>

Target:
private void generateNewPassword(U userAccount) { assertNotNew(userAccount); if (!userAccount.getUserAccountData().isPasswordGenerationPossible()) { throw Exceptions.createHandled() .withNLSKey("UserAccountConroller.cannotGeneratePasswordForOwnUser") .handle(); } userAccount.getUserAccountData().getLogin().forceGenerationOfPassword(); userAccount.getMapper().update(userAccount); auditLog.neutral("AuditLog.passwordGenerated") .causedByCurrentUser() .forUser(userAccount.getUniqueName(), userAccount.getUserAccountData().getLogin().getUsername()) .forTenant(String.valueOf(userAccount.getTenant().getId()), userAccount.getTenant().getValue().getTenantData().getName()) .log(); }
Source:
<code>protected List<String> getTimeZoneOptionsAsHtml(ZoneId existingTimeZone) { List<ZoneId> options = TimeHelper.getTimeZoneValues(); ArrayList<String> result = new ArrayList<>(); for (ZoneId timeZoneOption : options) { result.add("<option value=\"" + timeZoneOption.toString() + "\"" <START> + (existingTimeZone.equals(timeZoneOption) ? " selected" : "") + ">" + "(" + timeZoneOption.toString() <END> + ") " + TimeHelper.getCitiesForTimeZone(timeZoneOption) + "</option>"); } return result; }</code><technical_language>reason for toString instead of getId lines? I prefer getId more explicit</technical_language>

Target:
protected List<String> getTimeZoneOptionsAsHtml(ZoneId existingTimeZone) { List<ZoneId> options = TimeHelper.getTimeZoneValues(); ArrayList<String> result = new ArrayList<>(); for (ZoneId timeZoneOption : options) { result.add("<option value=\"" + timeZoneOption.getId() + "\"" + (existingTimeZone.equals(timeZoneOption) ? " selected" : "") + ">" + "(" + timeZoneOption.getId() + ") " + TimeHelper.getCitiesForTimeZone(timeZoneOption) + "</option>"); } return result; }
Source:
<code>private static Exception classifyException(Exception e) { if (e instanceof TApplicationException) { <START> return new PrestoException(THRIFT_GENERIC_REMOTE_SERVER_ERROR, "Exception raised by a remote thrift server", e); <END> } return e; }</code><technical_language>Capitalize Thrift (or remove word)</technical_language>

Target:
private static Exception classifyException(Exception e) { if (e instanceof TApplicationException) { return new PrestoException(THRIFT_SERVICE_GENERIC_REMOTE_ERROR, "Exception raised by a remote thrift server", e); } return e; }
Source:
<code>public void testNotLinkedToExternalNetworkNegative() { Network externalNetwork = new Network(); externalNetwork.setName(EXTERNAL_NETWORK_NAME); when(network.getId()).thenReturn(DEFAULT_GUID); when(networkDao.getAllExternalNetworksLinkedToPhysicalNetwork(eq(DEFAULT_GUID))).thenReturn(Collections.singletonList( externalNetwork)); assertThat(validator.notLinkedToExternalNetwork(), <START> failsWith(EngineMessage.ACTION_TYPE_FAILED_CANNOT_REMOVE_PHYSICAL_NETWORK_LINKED_TO_EXTERNAL_NETWORK)); <END> }</code><technical_language>extend check replacements, too? , ReplacementUtils.replaceWith(NetworkValidator.NETWORK_LIST_REPLACEMENT, Collections.singletonList(EXTERNAL_NETWORK_NAME))</technical_language>

Target:
public void testNotLinkedToExternalNetworkNegative() { Network externalNetwork = new Network(); externalNetwork.setName(EXTERNAL_NETWORK_NAME); List<Network> externalNetworkList = Collections.singletonList(externalNetwork); String linkedExternalNetworkNames = externalNetworkList.stream() .map(Network::getName) .collect(joining(", ")); when(network.getId()).thenReturn(DEFAULT_GUID); when(networkDao.getAllExternalNetworksLinkedToPhysicalNetwork(eq(DEFAULT_GUID))).thenReturn(externalNetworkList); assertThat(validator.notLinkedToExternalNetwork(), failsWith(EngineMessage.ACTION_TYPE_FAILED_CANNOT_REMOVE_PHYSICAL_NETWORK_LINKED_TO_EXTERNAL_NETWORK, ReplacementUtils.createSetVariableString(NetworkValidator.NETWORK_LIST_REPLACEMENT, linkedExternalNetworkNames))); }
Source:
<code>public static void setupProducts() { removeProducts(); final AttributeDefinition colorAttributeDefinition = AttributeDefinitionBuilder <START> .of(COLOR, LocalizedStrings.ofEnglishLocale(COLOR), new TextType()).build(); <END> final AttributeDefinition sizeAttributeDefinition = AttributeDefinitionBuilder .of(SIZE, LocalizedStrings.ofEnglishLocale(SIZE), new TextType()).build(); final ProductTypeDraft productTypeDraft = ProductTypeDraft.of(TEST_CLASS_NAME, "", asList(colorAttributeDefinition, sizeAttributeDefinition)); final ProductTypeCreateCommand productTypeCreateCommand = ProductTypeCreateCommand.of(productTypeDraft); productType = execute(productTypeCreateCommand); testProduct1 = createTestProduct(productType, "Schuh", "shoe", "red", "M"); testProduct2 = createTestProduct(productType, "Hemd", "shirt", "blue", "XL"); final SearchDsl<ProductProjection> search = ProductProjectionSearch.of(STAGED).withSort(SORT_CREATED_AT_DESC); execute(search, res -> { final List<String> ids = toIds(res.getResults()); return ids.contains(testProduct1.getId()) && ids.contains(testProduct2.getId()); }); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }</code><technical_language>provide static of methods instead of new calls constructor private? Please apply singleton pattern</technical_language>

Target:
public static void setupProducts() { removeProducts(); final AttributeDefinition colorAttributeDefinition = AttributeDefinitionBuilder .of(COLOR, LocalizedStrings.ofEnglishLocale(COLOR), TextType.of()).build(); final AttributeDefinition sizeAttributeDefinition = AttributeDefinitionBuilder .of(SIZE, LocalizedStrings.ofEnglishLocale(SIZE), TextType.of()).build(); final ProductTypeDraft productTypeDraft = ProductTypeDraft.of(TEST_CLASS_NAME, "", asList(colorAttributeDefinition, sizeAttributeDefinition)); final ProductTypeCreateCommand productTypeCreateCommand = ProductTypeCreateCommand.of(productTypeDraft); productType = execute(productTypeCreateCommand); testProduct1 = createTestProduct(productType, "Schuh", "shoe", "red", "M"); testProduct2 = createTestProduct(productType, "Hemd", "shirt", "blue", "XL"); final SearchDsl<ProductProjection> search = ProductProjectionSearch.of(STAGED).withSort(SORT_CREATED_AT_DESC); execute(search, res -> { final List<String> ids = toIds(res.getResults()); return ids.contains(testProduct1.getId()) && ids.contains(testProduct2.getId()); }); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }
Source:
<code>public void testFields() { <START> assertTrue(postModel.toString().equals("<Post id: 0 title: Test Post posted_at_millis: 100 user_id: 1 updated_at: 0>")); <END> assertTrue(userModel.toString().equals("<User id: 0 handle: handle created_at_millis: 0 num_posts: 0 some_date: 0 some_datetime: 0 bio: bio some_binary: null some_float: 0.0 some_decimal: 0.0 some_boolean: true>")); try { postModel.getField("fake_field"); fail("Non-existent field should have thrown exception on get"); } catch (IllegalStateException e) { } try { postModel.setField("fake_field", null); fail("Non-existent field should have thrown exception on set"); } catch (IllegalStateException e) { } assertFalse(postModel.hasField("fake_field")); assertTrue(postModel.hasField("title")); try { postModel.setField("title", "New Title"); assertEquals(postModel.getField("title"), "New Title"); } catch (IllegalStateException e) { e.printStackTrace(); fail("Field not found when it should have been"); } try { postModel.setField("title", 3); fail("Should have had class cast exception assigning int to string field"); } catch (ClassCastException e) { } }</code><technical_language>for regression testing purposes, a test verifies ID is real saved? re-fetch model save(userModel); is called a real ID</technical_language>

Target:
public void testFields() { try { postModel.getField("fake_field"); fail("Non-existent field should have thrown exception on get"); } catch (IllegalStateException e) { } try { postModel.setField("fake_field", null); fail("Non-existent field should have thrown exception on set"); } catch (IllegalStateException e) { } assertFalse(postModel.hasField("fake_field")); assertTrue(postModel.hasField("title")); try { postModel.setField("title", "New Title"); assertEquals(postModel.getField("title"), "New Title"); } catch (IllegalStateException e) { e.printStackTrace(); fail("Field not found when it should have been"); } try { postModel.setField("title", 3); fail("Should have had class cast exception assigning int to string field"); } catch (ClassCastException e) { } }
Source:
<code>public void PyramidTest() { ITmfStateSystemBuilder fixture = createFixture(); int parentQuark = fixture.getQuarkAbsoluteAndAdd(PROCESS_PATH, THREAD_PATH, CALLSTACK_PATH); int quark = fixture.getQuarkRelativeAndAdd(parentQuark, QUARK_0); TmfStateValue statev = TmfStateValue.newValueLong(0); fixture.modifyAttribute(0, TmfStateValue.nullValue(), quark); fixture.modifyAttribute(10, statev, quark); fixture.modifyAttribute(20, TmfStateValue.nullValue(), quark); quark = fixture.getQuarkRelativeAndAdd(parentQuark, QUARK_1); statev = TmfStateValue.newValueLong(1); fixture.modifyAttribute(0, TmfStateValue.nullValue(), quark); fixture.modifyAttribute(5, statev, quark); fixture.modifyAttribute(25, TmfStateValue.nullValue(), quark); quark = fixture.getQuarkRelativeAndAdd(parentQuark, QUARK_2); statev = TmfStateValue.newValueLong(2); fixture.modifyAttribute(0, statev, quark); fixture.modifyAttribute(30, TmfStateValue.nullValue(), quark); fixture.closeHistory(1002); CGAnalysis cga = new CGAnalysis(); <START> testPyramidStore(fixture, cga); <END> }</code><technical_language>Actually, instead of testPyramidStore methods separate methods, extract building of callstacks state systems. This way, able re-use test cases build calltree, flamegraph, etc. buildPyramidCallStack(fixture) put code in testPyramidStore</technical_language>

Target:
public void PyramidTest() { ITmfStateSystemBuilder fixture = createFixture(); buildPyramidCallStack(fixture); CGAnalysis cga = new CGAnalysis(); assertTrue(cga.iterateOverStateSystem(fixture, tp, pp, csp, new NullProgressMonitor())); ISegmentStore<@NonNull ISegment> segmentStore = cga.getSegmentStore(); assertNotNull(segmentStore); Object[] segments = segmentStore.toArray(); CalledFunction f1 = (CalledFunction) segments[0]; assertEquals("Number of segments Found", 1, segments.length, ERROR); assertEquals("Callees number", 0, f1.getChildren().size(), ERROR); assertEquals("Function's self time", 10, f1.getSelfTime(), ERROR); assertEquals("Compare the function's self time and total time", f1.getLength(), f1.getSelfTime(), ERROR); assertEquals("Function's depth", 0, f1.getDepth(), ERROR); }
Source:
<code><START> private static File getFileFromZip(File file) { <END> File fileFromZip = null; String pathString = file.getPath(); String zipFile = pathString.substring(pathString.indexOf(":") + 1, pathString.indexOf("!")); String filePathInsideZip = pathString.split("!")[1].substring(1); byte[] buffer = new byte[1024]; try { File outputDir = Files.createTempDirectory("robolectric_assets").toFile(); ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String currentFilename = ze.getName(); if (!currentFilename.equals(filePathInsideZip)) { ze = zis.getNextEntry(); continue; } fileFromZip = new File(outputDir + File.separator + currentFilename); new File(fileFromZip.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(fileFromZip); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); break; } zis.closeEntry(); zis.close(); } catch (IOException e) { e.printStackTrace(); } return fileFromZip; }</code><technical_language>logic involved - consider adding some docs</technical_language>

Target:
private static File getFileFromZip(File file) { File fileFromZip = null; String pathString = file.getPath(); String zipFile = pathString.substring(pathString.indexOf(":") + 1, pathString.indexOf("!")); String filePathInsideZip = pathString.split("!")[1].substring(1); byte[] buffer = new byte[1024]; try { File outputDir = Files.createTempDirectory("robolectric_assets").toFile(); ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String currentFilename = ze.getName(); if (!currentFilename.equals(filePathInsideZip)) { ze = zis.getNextEntry(); continue; } fileFromZip = new File(outputDir + File.separator + currentFilename); new File(fileFromZip.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(fileFromZip); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); break; } zis.closeEntry(); zis.close(); } catch (IOException e) { throw new RuntimeException(e); } return fileFromZip; }
Source:
<code>private void finalizeShutdown() { this.selectionManager.shutdown(); this.clientPinger.shutdown(); PAFuture.waitFor(this.monitoring.shutdown()); PAActiveObject.terminateActiveObject(false); try { Thread.sleep(2000); synchronized (nodeRM) { nodeRM.notifyAll(); shutedDown = true; } if (!PAResourceManagerProperties.RM_SHUTDOWN_KILL_RUNTIME.isSet() || <START> PAResourceManagerProperties.RM_SHUTDOWN_KILL_RUNTIME.getValueAsBoolean()) <END> this.nodeRM.getProActiveRuntime().killRT(true); } catch (Exception e) { logger.debug("", e); } }</code><technical_language>getValueAsBoolean() is true if is set is true. throw exception</technical_language>

Target:
private void finalizeShutdown() { this.selectionManager.shutdown(); this.clientPinger.shutdown(); PAFuture.waitFor(this.monitoring.shutdown()); PAActiveObject.terminateActiveObject(false); try { Thread.sleep(2000); synchronized (nodeRM) { nodeRM.notifyAll(); shutedDown = true; } if (PAResourceManagerProperties.RM_SHUTDOWN_KILL_RUNTIME.getValueAsBoolean()) this.nodeRM.getProActiveRuntime().killRT(true); } catch (Exception e) { logger.debug("", e); } }
Source:
<code>public ProcessStatus check() { boolean success = false; Transact inputTransact = inputDock.pullTransact(); if (inputTransact != null) { queue.offer(inputTransact); success = true; } Transact outputTransact = queue.peek(); if (outputTransact != null) { if (outputDock.pushTransact(outputTransact)) { queue.remove(); success = true; <START> } <END> } return success ? ProcessStatus.SUCCESS : ProcessStatus.NOTHING_TO_DO; }</code><technical_language>java if (outputDock.pushTransact(outputTransact)) { queue.remove(); return ProcessStatus.SUCCESS; } else { return ProcessStatus.CHECK_AGAIN; }</technical_language>

Target:
public BlockStatus check() { Transact inputTransact = inputDock.pullTransact(); if (inputTransact != null) { queue.offer(inputTransact); System.out.println(Simulator.getTime() + " queue added " + inputTransact.getNumber()); return BlockStatus.SUCCESS; } Transact outputTransact = queue.peek(); if (outputTransact != null) { if (!outputDock.hasTransact()) { queue.remove(); System.out.println(Simulator.getTime() + " queue removed " + outputTransact.getNumber()); outputDock.pushTransact(outputTransact); return BlockStatus.SUCCESS; } } return BlockStatus.NOTHING_TO_DO; }
Source:
<code>public Page<DiscussionComment> call() throws Exception { final List<String> requestedFields; <START> { <END> if (environment.getConfig().isDiscussionProfilePicturesEnabled()) { requestedFields = Collections.singletonList( DiscussionRequestFields.PROFILE_IMAGE.getQueryParamValue()); } else { requestedFields = Collections.EMPTY_LIST; } } return environment.getDiscussionAPI().getCommentsList(responseId, PAGE_SIZE, page, requestedFields); }</code><technical_language>need this extra block here</technical_language>

Target:
public Page<DiscussionComment> call() throws Exception { return environment.getDiscussionAPI().getCommentsList(responseId, PAGE_SIZE, page, DiscussionRequestFields.getRequestedFieldsList(environment.getConfig())); }
Source:
<code>public void onSupportActionModeStarted(ActionMode mode) { <START> if (mSelectionModeActive == true && selectedTextView != null) { <END> mSelectionModeActive = false; mActionMode = mode; Menu menu = mode.getMenu(); mode.getMenuInflater().inflate(R.menu.details_context, menu); menu.findItem(R.id.menu_copy).setVisible(false); menu.findItem(R.id.menu_cache_share_field).setOnMenuItemClickListener(new TextMenuItemClickListener()); menu.findItem(R.id.menu_translate_to_sys_lang).setOnMenuItemClickListener(new TextMenuItemClickListener()); menu.findItem(R.id.menu_translate_to_english).setOnMenuItemClickListener(new TextMenuItemClickListener()); buildDetailsContextMenu(mode, menu, res.getString(R.string.cache_description), false); selectedTextView.setWindowFocusWait(true); } super.onSupportActionModeStarted(mode); }</code><technical_language>Please compare true. if (mSelectionModeActive && selectedTextView != null) is enough</technical_language>

Target:
public void onSupportActionModeStarted(ActionMode mode) { if (selectionModeActive && selectedTextView != null) { selectionModeActive = false; mActionMode = mode; Menu menu = mode.getMenu(); mode.getMenuInflater().inflate(R.menu.details_context, menu); menu.findItem(R.id.menu_copy).setVisible(false); menu.findItem(R.id.menu_cache_share_field).setOnMenuItemClickListener(new TextMenuItemClickListener()); menu.findItem(R.id.menu_translate_to_sys_lang).setOnMenuItemClickListener(new TextMenuItemClickListener()); menu.findItem(R.id.menu_translate_to_english).setOnMenuItemClickListener(new TextMenuItemClickListener()); buildDetailsContextMenu(mode, menu, res.getString(R.string.cache_description), false); selectedTextView.setWindowFocusWait(true); } super.onSupportActionModeStarted(mode); }
Source:
<code>public void reapEntries(final Date reapingDate) { sqlDao.inTransaction(new Transaction<Void, QueueSqlDao<T>>() { @Override public Void inTransaction(final QueueSqlDao<T> transactional, final TransactionStatus status) throws Exception { final Date now = clock.getUTCNow().toDate(); final List<T> entriesLeftBehind = sqlDao.getEntriesLeftBehind(config.getMaxReDispatchCount(), now, reapingDate, config.getTableName()); if (entriesLeftBehind.size() > 0) { final Iterable<T> entriesToMove = Iterables.transform(entriesLeftBehind, new Function<T, T>() { @Nullable @Override public T apply(@Nullable final T entry) { set(entry, "processingState", PersistentQueueEntryLifecycleState.REAPED); return entry; } }); moveEntriesToHistoryFromTransaction(transactional, entriesToMove); for (T entry : entriesLeftBehind) { set(entry, "creatingOwner", CreatorName.get()); set(entry, "createdDate", clock.getUTCNow()); set(entry, "processingState", PersistentQueueEntryLifecycleState.AVAILABLE); insertEntryFromTransaction(transactional, entry); } log.warn(String.format( "%s %s entries were reaped by %s",DB_QUEUE_LOG_ID ,entriesLeftBehind.size(), CreatorName.get())); } return null; } private void set(T entry, String fieldName, Object value) { Class clazz = entry.getClass(); Field field = null; try { <START> field = clazz.getDeclaredField(fieldName); <END> field.setAccessible(true); field.set(entry, value); } catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { } } }); }</code><technical_language>While convenient, this a massive performance impact unfortunately. code, T extends EventEntryModelDao. I fine change interface EventEntryModelDao expose setters (make add @Override annotations in BusEventModelDao). setters, need this anymore</technical_language>

Target:
public void reapEntries(final Date reapingDate) { sqlDao.inTransaction(new Transaction<Void, QueueSqlDao<T>>() { @Override public Void inTransaction(final QueueSqlDao<T> transactional, final TransactionStatus status) throws Exception { final DateTime now = clock.getUTCNow(); final List<T> entriesLeftBehind = sqlDao.getEntriesLeftBehind(config.getMaxReDispatchCount(), now.toDate(), reapingDate, config.getTableName()); if (entriesLeftBehind.size() > 0) { final Iterable<T> entriesToMove = Iterables.transform(entriesLeftBehind, new Function<T, T>() { @Nullable @Override public T apply(@Nullable final T entry) { entry.setProcessingState(PersistentQueueEntryLifecycleState.REAPED); return entry; } }); moveEntriesToHistoryFromTransaction(transactional, entriesToMove); for (T entry : entriesLeftBehind) { entry.setCreatedDate(now); entry.setProcessingState(PersistentQueueEntryLifecycleState.AVAILABLE); entry.setCreatingOwner(CreatorName.get()); insertEntryFromTransaction(transactional, entry); } log.warn(String.format( "{} entries were reaped by {}",DB_QUEUE_LOG_ID ,entriesLeftBehind.size(), CreatorName.get())); } return null; } }); }
Source:
<code>@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setSslContextFactory(createSslFactory()); ConnectorConfiguration conCfg = new ConnectorConfiguration(); conCfg.setSslEnabled(true); conCfg.setSslClientAuth(true); cfg.setConnectorConfiguration(conCfg); CacheConfiguration ccfg = new CacheConfiguration(TEST_CACHE_NAME); <START> cfg.setCacheConfiguration(ccfg); <END> return cfg; }</code><technical_language>merge creating cache configuration passing ignite configuration</technical_language>

Target:
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setSslContextFactory(createSslFactory()); cfg.setConnectorConfiguration(new ConnectorConfiguration() .setSslEnabled(true) .setSslClientAuth(true)); cfg.setCacheConfiguration(new CacheConfiguration(TEST_CACHE_NAME)); return cfg; }
Source:
<code>public void setShippingMethodTaxAmount() throws Exception { withShippingMethodForGermany(client(), shippingMethod -> { withCustomLineItemFilledCartWithTaxMode(client(), TaxMode.EXTERNAL_AMOUNT, cart -> { final Cart cartWithShippingMethod = client().executeBlocking(CartUpdateCommand.of(cart, SetShippingMethod.of(shippingMethod))); final ExternalTaxRateDraft taxRate = ExternalTaxRateDraftBuilder .ofAmount(1.0, "Test Tax", CountryCode.DE) .build(); final MonetaryAmount totalGross = MoneyImpl.ofCents(1000, EUR); final ExternalTaxAmountDraftDsl taxAmountDraft = ExternalTaxAmountDraftBuilder .of(totalGross, taxRate) .build(); final SetShippingMethodTaxAmount setShippingMethodTaxAmount = SetShippingMethodTaxAmount.of(taxAmountDraft); final Cart updatedCart = client().executeBlocking(CartUpdateCommand.of(cartWithShippingMethod, setShippingMethodTaxAmount)); <START> <END> return updatedCart; }); }); }</code><technical_language>assertion checking shipping method set, price all</technical_language>

Target:
public void setShippingMethodTaxAmount() throws Exception { withShippingMethodForGermany(client(), shippingMethod -> { withCustomLineItemFilledCartWithTaxMode(client(), TaxMode.EXTERNAL_AMOUNT, cart -> { final Cart cartWithShippingMethod = client().executeBlocking(CartUpdateCommand.of(cart, SetShippingMethod.of(shippingMethod))); assertThat(cartWithShippingMethod.getShippingInfo()).isNotNull(); assertThat(cartWithShippingMethod.getShippingInfo().getTaxedPrice()).isNull(); final ExternalTaxRateDraft taxRate = ExternalTaxRateDraftBuilder .ofAmount(1.0, "Test Tax", CountryCode.DE) .build(); final MonetaryAmount totalGross = MoneyImpl.ofCents(100000, EUR); final ExternalTaxAmountDraftDsl taxAmountDraft = ExternalTaxAmountDraftBuilder .of(totalGross, taxRate) .build(); final SetShippingMethodTaxAmount setShippingMethodTaxAmount = SetShippingMethodTaxAmount.of(taxAmountDraft); final Cart updatedCart = client().executeBlocking(CartUpdateCommand.of(cartWithShippingMethod, setShippingMethodTaxAmount)); final TaxedItemPrice taxedPrice = updatedCart.getShippingInfo().getTaxedPrice(); assertThat(taxedPrice.getTotalGross()).isEqualTo(totalGross); return updatedCart; }); }); }