auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static <T extends Throwable> String getFailureWithSuppliedMessage(Class<T> expectedType, Supplier<String> messageSupplier) { <START> return buildPrefix(nullSafeGet(messageSupplier) + getFailureMessage(expectedType)); <END> }</code><technical_language>closing parenthesis for buildPrefix() follow call nullSafeGet()</technical_language>

Target:
private static <T extends Throwable> String getFailureWithSuppliedMessage(Class<T> expectedType, Supplier<String> messageSupplier) { return buildPrefix(nullSafeGet(messageSupplier)) + getFailureMessage(expectedType); }
Source:
<code><START> private String getPath() { <END> return Paths.get(getPersistencePath(), mapName).toString() + File.separator; }</code><technical_language>Instead of converting Path a String, return Path object callers instead. deal file separators existing Path methods</technical_language>

Target:
private Path getPath() { return Paths.get(getPersistencePath(), mapName); }
Source:
<code>public void shouldReturnInternalServerError_ifGatewayErrors() throws IOException { String externalChargeId = "external-charge-id"; ApplePayAuthRequest applePayAuthRequest = ApplePayAuthRequestBuilder.anApplePayToken().build(); GatewayError gatewayError = mock(GatewayError.class); GatewayResponse gatewayResponse = responseBuilder() .withGatewayError(gatewayError) .withSessionIdentifier("234") .build(); when(gatewayError.getErrorType()).thenReturn(GATEWAY_ERROR); when(gatewayError.getMessage()).thenReturn("oops"); when(mockedApplePayDecrypter.performDecryptOperation(applePayAuthRequest)).thenReturn(validData); when(mockedApplePayAuthoriseService.doAuthorise(externalChargeId, validData)).thenReturn(gatewayResponse); Response authorisationResponse = applePayService.authorise(externalChargeId, applePayAuthRequest); verify(mockedApplePayAuthoriseService).doAuthorise(externalChargeId, validData); assertThat(authorisationResponse.getStatus(), is(500)); ErrorResponse response = (ErrorResponse)authorisationResponse.getEntity(); <START> MatcherAssert.assertThat(response.getMessages(), contains("oops")); <END> }</code><technical_language>Please static import assertThat</technical_language>

Target:
public void shouldReturnInternalServerError_ifGatewayErrors() throws IOException { String externalChargeId = "external-charge-id"; ApplePayAuthRequest applePayAuthRequest = ApplePayAuthRequestBuilder.anApplePayToken().build(); GatewayError gatewayError = mock(GatewayError.class); GatewayResponse gatewayResponse = responseBuilder() .withGatewayError(gatewayError) .withSessionIdentifier("234") .build(); when(gatewayError.getErrorType()).thenReturn(GATEWAY_ERROR); when(gatewayError.getMessage()).thenReturn("oops"); when(mockedApplePayDecrypter.performDecryptOperation(applePayAuthRequest)).thenReturn(validData); when(mockedApplePayAuthoriseService.doAuthorise(externalChargeId, validData)).thenReturn(gatewayResponse); Response authorisationResponse = applePayService.authorise(externalChargeId, applePayAuthRequest); verify(mockedApplePayAuthoriseService).doAuthorise(externalChargeId, validData); assertThat(authorisationResponse.getStatus(), is(500)); ErrorResponse response = (ErrorResponse)authorisationResponse.getEntity(); assertThat(response.getMessages(), contains("oops")); }
Source:
<code>protected Builder() { id("jdbc") .name("Jdbc BlobStore") <START> .identityName("Unused") <END> .defaultEndpoint("http://localhost/transient") .defaultIdentity("unused") .defaultCredential("unused") .version("1") .documentation(URI.create("<LINK_0>")) .view(BlobStoreContext.class) .defaultModules(ImmutableSet.<Class<? extends Module>>of(JdbcBlobStoreContextModule.class)); }</code><technical_language>add credentialName. unused? configured DB user pass</technical_language>

Target:
protected Builder() { id("jdbc") .name("Jdbc BlobStore") .identityName("Unused") .credentialName("unused") .defaultEndpoint("http://localhost/transient") .defaultIdentity("unused") .defaultCredential("unused") .version("1") .documentation(URI.create("<LINK_0>")) .view(BlobStoreContext.class) .defaultModules(ImmutableSet.<Class<? extends Module>>of(JdbcBlobStoreContextModule.class)); }
Source:
<code>void controlReplicationForPartitions(List<? extends PartitionId> ids, boolean enable) { lock.lock(); try { for (PartitionId id : ids) { if (replicatedPartitions.contains(id)) { if (enable) { <START> replicationDisabledPartitions.remove(id); <END> allDisabled = false; pauseCondition.signal(); } else { replicationDisabledPartitions.add(id); allDisabled = replicatedPartitions.size() == replicationDisabledPartitions.size(); } logger.info("Enable status of replication of from is {}. allDisabled for is {}", id, datacenterName, replicationDisabledPartitions.contains(id), getName(), allDisabled); } } } finally { lock.unlock(); } }</code><technical_language>if(replicationDisabledPartitions.remove(id)) { allDisabled = false; pauseCondition.signal(); }</technical_language>

Target:
void controlReplicationForPartitions(List<? extends PartitionId> ids, boolean enable) { lock.lock(); try { for (PartitionId id : ids) { if (allReplicatedPartitions.contains(id)) { if (enable) { if (replicationDisabledPartitions.remove(id)) { allDisabled = false; pauseCondition.signal(); } } else { replicationDisabledPartitions.add(id); allDisabled = allReplicatedPartitions.size() == replicationDisabledPartitions.size(); } logger.info("Enable status of replication of from is {}. allDisabled for is {}", id, datacenterName, replicationDisabledPartitions.contains(id), getName(), allDisabled); } } } finally { lock.unlock(); } }
Source:
<code>public SSDate resetTime() { this.setHours(0); this.setMinutes(0); this.setSeconds(0); <START> return this; <END> }</code><technical_language>dont a setter type function return "this"</technical_language>

Target:
public void resetTime() { this.setHours(0); this.setMinutes(0); this.setSeconds(0); }
Source:
<code><START> private boolean readFirstLine() throws IOException { <END> is0D0Amode = false; String line; do { line = readLine(); if (line == null) { return false; } } while (ignoreEmptyLines && line.isEmpty() || (commentMatcher != null && commentMatcher.isComment(line))); currentRow.append(line); return true; }</code><technical_language>is0D0Amode is false true, need this flag</technical_language>

Target:
private boolean readFirstLine() throws IOException { String line; do { line = readLine(); if (line == null) { return false; } } while (ignoreEmptyLines && line.isEmpty() || (commentMatcher != null && commentMatcher.isComment(line))); currentRow.append(line); return true; }
Source:
<code>public void addPartitions(String databaseName, String tableName, List<PartitionDescProto> partitions, boolean ifNotExists) throws UndefinedTableException, DuplicatePartitionException, <START> UndefinedPartitionMethodException { <END> try { final BlockingInterface stub = getStub(); final AddPartitionsProto.Builder builder = AddPartitionsProto.newBuilder(); final TableIdentifierProto.Builder identifier = TableIdentifierProto.newBuilder() .setDatabaseName(databaseName) .setTableName(tableName); builder.setTableIdentifier(identifier.build()); for (PartitionDescProto partition: partitions) { builder.addPartitionDesc(partition); } builder.setIfNotExists(ifNotExists); ReturnState state = stub.addPartitions(null, builder.build()); throwsIfThisError(state, UndefinedTableException.class); throwsIfThisError(state, UndefinedPartitionMethodException.class); throwsIfThisError(state, DuplicatePartitionException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }</code><technical_language>UndefinedDatabaseException handled. In addition, DuplicatePartitionException is missed CatalogServer.addPartitions(). great if add it</technical_language>

Target:
public void addPartitions(String databaseName, String tableName, List<PartitionDescProto> partitions, boolean ifNotExists) throws UndefinedDatabaseException, UndefinedTableException, DuplicatePartitionException, UndefinedPartitionMethodException { try { final BlockingInterface stub = getStub(); final AddPartitionsProto.Builder builder = AddPartitionsProto.newBuilder(); final TableIdentifierProto.Builder identifier = TableIdentifierProto.newBuilder() .setDatabaseName(databaseName) .setTableName(tableName); builder.setTableIdentifier(identifier.build()); for (PartitionDescProto partition: partitions) { builder.addPartitionDesc(partition); } builder.setIfNotExists(ifNotExists); ReturnState state = stub.addPartitions(null, builder.build()); throwsIfThisError(state, UndefinedTableException.class); throwsIfThisError(state, UndefinedPartitionMethodException.class); throwsIfThisError(state, DuplicatePartitionException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
<code>protected void firstListenerAdded() { if (!isDisposed() && listener == null) { listener = property.adaptListener(new ISimplePropertyListener<ListDiff<E>>() { @Override public void handleEvent(final SimplePropertyEvent<ListDiff<E>> event) { if (!isDisposed() && !updating) { getRealm().exec(new Runnable() { @Override public void run() { if (event.type == SimplePropertyEvent.CHANGE) { modCount++; notifyIfChanged(event.diff); } else if (event.type == SimplePropertyEvent.STALE && !stale) { stale = true; fireStale(); } } }); } } }); } getRealm().exec(new Runnable() { @Override public void run() { cachedList = new <START> ArrayList<E>(getList()); <END> stale = false; if (listener != null) listener.addTo(source); } }); }</code><technical_language><> work</technical_language>

Target:
protected void firstListenerAdded() { if (!isDisposed() && listener == null) { listener = property.adaptListener(new ISimplePropertyListener<ListDiff<E>>() { @Override public void handleEvent(final SimplePropertyEvent<ListDiff<E>> event) { if (!isDisposed() && !updating) { getRealm().exec(new Runnable() { @Override public void run() { if (event.type == SimplePropertyEvent.CHANGE) { modCount++; notifyIfChanged(event.diff); } else if (event.type == SimplePropertyEvent.STALE && !stale) { stale = true; fireStale(); } } }); } } }); } getRealm().exec(new Runnable() { @Override public void run() { cachedList = new ArrayList<>(getList()); stale = false; if (listener != null) listener.addTo(source); } }); }
Source:
<code>@Override public Object invoke(Object proxy, final Method method, final Object[] args) { if (methodWantsSynchronousInvocation(method)) { return invokeRequest(method, args, true); } else { if (httpExecutor == null || callbackExecutor == null) { <START> throw new NullPointerException("Asynchronous invocation requires calling setExecutors."); <END> } httpExecutor.execute(new CallbackRunnable(obtainCallback(args), callbackExecutor) { @Override public Object obtainResponse() { return invokeRequest(method, args, false); } }); return null; } }</code><technical_language>NPE is a strange choice. I want IllegalStateException, this object support this call. (In theory a method createNewThreadForEachCall avoid problem, omitting NPE)</technical_language>

Target:
@Override public Object invoke(Object proxy, final Method method, final Object[] args) { if (methodWantsSynchronousInvocation(method)) { return invokeRequest(method, args, true); } else { if (httpExecutor == null || callbackExecutor == null) { throw new IllegalStateException("Asynchronous invocation requires calling setExecutors."); } httpExecutor.execute(new CallbackRunnable(obtainCallback(args), callbackExecutor) { @Override public Object obtainResponse() { return invokeRequest(method, args, false); } }); return null; } }
Source:
<code>public void adjust(Mechanism mechanism) { if (mechanism.matches("inputs")) { List<ItemStack> ingredients = new ArrayList<>(); dList list = mechanism.getValue().asType(dList.class); <START> if (!mechanism.hasValue() || list.filter(dItem.class).isEmpty()) { <END> recipe.getRecipe().setIngredients(ingredients); return; } for (dItem item : list.filter(dItem.class)) { ingredients.add(item.getItemStack()); } if (ingredients.size() > 2) { dB.echoError("Trade recipe input was given " + list.size() + " items. Only using the first two items!"); ingredients = ingredients.subList(0, 2); } recipe.getRecipe().setIngredients(ingredients); } }</code><technical_language>call list.filter(dItem.class) repeatedly - call store result</technical_language>

Target:
public void adjust(Mechanism mechanism) { if (mechanism.matches("inputs")) { List<ItemStack> ingredients = new ArrayList<>(); List<dItem> list = mechanism.getValue().asType(dList.class).filter(dItem.class); if (!mechanism.hasValue() || list.isEmpty()) { recipe.getRecipe().setIngredients(ingredients); return; } for (dItem item : list) { ingredients.add(item.getItemStack()); } if (ingredients.size() > 2) { dB.echoError("Trade recipe input was given " + list.size() + " items. Only using the first two items!"); ingredients = ingredients.subList(0, 2); } recipe.getRecipe().setIngredients(ingredients); } }
Source:
<code>public void refreshAllUsers() { DbUserDAO dao = DbFacade.getInstance().getDbUserDao(); List<DbUser> dbUsers = dao.getAll(); List<DbGroup> dbGroups = DbFacade.getInstance().getDbGroupDao().getAll(); for (DbGroup group : dbGroups) { groupsMap.put(group.getExternalId(), group); } Map<Directory, List<DbUser>> index = new HashMap<>(); for (DbUser dbUser : dbUsers) { AuthenticationProfile profile = AuthenticationProfileRepository.getInstance().getProfile(dbUser.getDomain()); if (profile == null) { <START> log.warn(String.format("No profile was found for user %1$s. It is possible that the relevant domain for the user was removed for the user. Marking the user as inactive", <END> dbUser.getLoginName())); if (dbUser.isActive()) { dbUser.setActive(false); dao.update(dbUser); } continue; } Directory key = profile.getDirectory(); List<DbUser> value = index.get(key); if (value == null) { value = new ArrayList<DbUser>(); index.put(key, value); } value.add(dbUser); } List<DbUser> updates = new ArrayList<>(); for (Map.Entry<Directory, List<DbUser>> entry : index.entrySet()) { List<DbUser> refreshed = refreshUsers(entry.getValue(), entry.getKey()); updates.addAll(refreshed); } for (DbUser dbUser : updates) { dao.update(dbUser); } }</code><technical_language>please split string message more line line exceed 120 chars limit</technical_language>

Target:
public void refreshAllUsers() { DbUserDAO dao = DbFacade.getInstance().getDbUserDao(); List<DbUser> dbUsers = dao.getAll(); List<DbGroup> dbGroups = DbFacade.getInstance().getDbGroupDao().getAll(); for (DbGroup group : dbGroups) { groupsMap.put(group.getExternalId(), group); } Map<Directory, List<DbUser>> index = new HashMap<>(); for (DbUser dbUser : dbUsers) { AuthenticationProfile profile = AuthenticationProfileRepository.getInstance().getProfile(dbUser.getDomain()); if (profile == null) { log.warn(String.format("No profile was found for user %1$s. It is possible that the relevant " + "domain for the user was removed for the user. Marking the user as inactive", dbUser.getLoginName())); if (dbUser.isActive()) { dbUser.setActive(false); dao.update(dbUser); } continue; } Directory key = profile.getDirectory(); List<DbUser> value = index.get(key); if (value == null) { value = new ArrayList<DbUser>(); index.put(key, value); } value.add(dbUser); } List<DbUser> updates = new ArrayList<>(); for (Map.Entry<Directory, List<DbUser>> entry : index.entrySet()) { List<DbUser> refreshed = refreshUsers(entry.getValue(), entry.getKey()); updates.addAll(refreshed); } for (DbUser dbUser : updates) { dao.update(dbUser); } }
Source:
<code><START> public void getCashPointsByLocation_shouldReturnAllCashpointsForTheSpecifiedLocation() throws Exception { <END> List<CashPoint> cashPoint = service.getCashPointsByLocation(Context.getLocationService().getLocation(1),false); Assert.assertNotNull(cashPoint); Assert.assertEquals(1, cashPoint.size()); }</code><technical_language>This needs tests returning multiple cash points for a single location</technical_language>

Target:
public void getCashPointsByLocation_shouldReturnAllCashpointsForTheSpecifiedLocation() throws Exception { List<CashPoint> cashPoint = service.getCashPointsByLocation(Context.getLocationService().getLocation(0),false); Assert.assertNotNull(cashPoint); Assert.assertEquals(3, cashPoint.size()); Assert.assertEquals(0,(int)Iterators.get(cashPoint.iterator(),0).getId()); Assert.assertEquals(4,(int)Iterators.get(cashPoint.iterator(),1).getId()); Assert.assertEquals(5,(int)Iterators.get(cashPoint.iterator(),2).getId()); }
Source:
<code>public void testWhatsNewJsonParsing() throws IOException, ParseException { final Context context = RuntimeEnvironment.application; final String whatsNewJson = FileUtil.loadTextFileFromResources(context, R.raw.whats_new); final Type type = new TypeToken<List<WhatsNew>>() {}.getType(); final List<WhatsNew> list = new Gson().fromJson(whatsNewJson, type); assertThat(list).isNotEmpty(); List<WhatsNewModel> messages; <START> for(WhatsNew whatsNew : list) { <END> assertThat(new Version(whatsNew.getVersion())).isNotNull(); messages = whatsNew.getMessages(); assertThat(messages).isNotEmpty(); validateWhatsNewMessages(messages); messages = WhatsNewUtil.getWhatsNewMessages(whatsNew.getVersion(), list); assertThat(messages).isNotEmpty(); } messages = WhatsNewUtil.getWhatsNewMessages("0.0.00", list); assertThat(messages).isNull(); }</code><technical_language>Auto-format needed for this file</technical_language>

Target:
public void testWhatsNewJsonParsing() throws IOException, ParseException { final Context context = RuntimeEnvironment.application; final String whatsNewJson = FileUtil.loadTextFileFromResources(context, R.raw.whats_new); final Type type = new TypeToken<List<WhatsNewModel>>() { }.getType(); final List<WhatsNewModel> whatsNewModels = new Gson().fromJson(whatsNewJson, type); assertThat(whatsNewModels).isNotEmpty(); List<WhatsNewItemModel> whatsNewItems; for (WhatsNewModel whatsNewModel : whatsNewModels) { assertThat(new Version(whatsNewModel.getVersion())).isNotNull(); whatsNewItems = whatsNewModel.getWhatsNewItems(); assertThat(whatsNewItems).isNotEmpty(); validateWhatsNewItems(whatsNewItems); whatsNewItems = WhatsNewUtil.getWhatsNewItems(whatsNewModel.getVersion(), whatsNewModels); assertThat(whatsNewItems).isNotEmpty(); } whatsNewItems = WhatsNewUtil.getWhatsNewItems("0.0.00", whatsNewModels); assertThat(whatsNewItems).isNull(); }
Source:
<code>public void compute(Iterator<SplitRepeatMessage> msgIterator) { initVertex(); if (verbose) LOG.fine("Iteration " + getSuperstep() + " for key " + getVertexId()); <START> if(getVertexId().toString().equals("AGACCCATGCAGCGGGTCAGG") <END> || getVertexId().toString().equals("GGAGACCCATGCAGCGGGTCA")) System.out.println("stop"); if (getSuperstep() == 1) { restrictNeighbor(); } else if (getSuperstep() == 2) { if (msgIterator.hasNext()) voteToHalt(); else detectRepeatAndSplit(); } else if (getSuperstep() == 3) { responseToRepeat(msgIterator); voteToHalt(); } }</code><technical_language>this stuff here</technical_language>

Target:
public void compute(Iterator<SplitRepeatMessage> msgIterator) { initVertex(); if (verbose) LOG.fine("Iteration " + getSuperstep() + " for key " + getVertexId()); if (getSuperstep() == 1) { restrictNeighbor(); } else if (getSuperstep() == 2) { if (msgIterator.hasNext()) voteToHalt(); else detectRepeatAndSplit(); } else if (getSuperstep() == 3) { responseToRepeat(msgIterator); voteToHalt(); } }
Source:
<code>protected void createControls(Composite parent, int horizontalSpan) { if (horizontalSpan < 2) { horizontalSpan = 2; } Composite applicabilityComp = new Composite(parent, SWT.NONE); applicabilityComp.setLayout(new GridLayout(2, false)); applicabilityComp.setLayoutData(new GridData(SWT.BEGINNING, SWT.FILL, true, false)); if (toolkit != null) { toolkit.adapt(applicabilityComp); } setBranchViewButton = new Button(applicabilityComp, SWT.PUSH); setBranchViewButton.setToolTipText("Select a branch view to associate this version artifact with."); setBranchViewButton.setText("Select Branch View"); setBranchViewButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { <START> String baselineBranch = artifact.getSoleAttributeValue(AtsAttributeTypes.BaselineBranchUuid); <END> changeView(BranchId.valueOf(baselineBranch)); refresh(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); text = new Text(applicabilityComp, SWT.WRAP); text.setForeground(Displays.getSystemColor(SWT.COLOR_DARK_GRAY)); text.setText(getArtifactViewApplicabiltyText()); }</code><technical_language>handle case baseline branch set</technical_language>

Target:
protected void createControls(Composite parent, int horizontalSpan) { if (horizontalSpan < 2) { horizontalSpan = 2; } Composite applicabilityComp = new Composite(parent, SWT.NONE); applicabilityComp.setLayout(new GridLayout(2, false)); applicabilityComp.setLayoutData(new GridData(SWT.BEGINNING, SWT.FILL, true, false)); if (toolkit != null) { toolkit.adapt(applicabilityComp); } setBranchViewButton = new Button(applicabilityComp, SWT.PUSH); setBranchViewButton.setToolTipText("Select a branch view to associate this version artifact with."); setBranchViewButton.setText("Select Branch View"); setBranchViewButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { try { String baselineBranch = artifact.getSoleAttributeValue(AtsAttributeTypes.BaselineBranchUuid, ""); changeView(BranchId.valueOf(baselineBranch)); refresh(); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); text = new Text(applicabilityComp, SWT.WRAP); text.setForeground(Displays.getSystemColor(SWT.COLOR_DARK_GRAY)); text.setText(getArtifactViewApplicabiltyText()); }
Source:
<code>public boolean isDescendant(String potentialChildRelativePath) throws IOException { <START> if (potentialChildRelativePath.equals("") && cacheDescendant) { <END> return true; } if (new File(potentialChildRelativePath).isAbsolute()) { throw new IllegalArgumentException("Only a relative path is supported, the given path is absolute: " + potentialChildRelativePath); } File directChild = new File(f, potentialChildRelativePath); if (directChild.getParentFile().equals(f)) { if (!Util.isSymlink(directChild)) { return true; } } FilePath root = new FilePath(this.root); String relativePath = computeRelativePathToRoot(); try { boolean isDescendant = root.isDescendant(relativePath + potentialChildRelativePath); if (isDescendant && potentialChildRelativePath.equals("")) { cacheDescendant = true; } return isDescendant; } catch (InterruptedException e) { return false; } }</code><technical_language>suggestion if (potentialChildRelativePath.isEmpty() && cacheDescendant) {</technical_language>

Target:
public boolean isDescendant(String potentialChildRelativePath) throws IOException { if (potentialChildRelativePath.isEmpty() && cacheDescendant) { return true; } if (new File(potentialChildRelativePath).isAbsolute()) { throw new IllegalArgumentException("Only a relative path is supported, the given path is absolute: " + potentialChildRelativePath); } File directChild = new File(f, potentialChildRelativePath); if (directChild.getParentFile().equals(f)) { if (!Util.isSymlink(directChild)) { return true; } } FilePath root = new FilePath(this.root); String relativePath = computeRelativePathToRoot(); try { boolean isDescendant = root.isDescendant(relativePath + potentialChildRelativePath); if (isDescendant && potentialChildRelativePath.isEmpty()) { cacheDescendant = true; } return isDescendant; } catch (InterruptedException e) { return false; } }
Source:
<code>protected void setUp() throws Exception { super.setUp(); manager = TasksUiPlugin.getRepositoryManager(); manager.clearRepositories(TasksUiPlugin.getDefault().getRepositoriesFilePath()); repository = new TaskRepository(BugzillaCorePlugin.CONNECTOR_KIND, BugzillaFixture.current().getRepositoryUrl()); UserCredentials credentials = CommonTestUtil.getCredentials(PrivilegeLevel.USER); repository.setCredentials(AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), credentials.getPassword()), false); TasksUiPlugin.getRepositoryManager().addRepository(repository); TasksUiTestUtil.ensureTasksUiInitialization(); <START> wizard = new EditRepositoryWizard(repository, TasksUiPlugin.getConnectorUi(repository.getConnectorKind())); <END> }</code><technical_language>create connector connectorUI do in AbstractRepositorySettingsPageTest</technical_language>

Target:
protected void setUp() throws Exception { super.setUp(); manager = TasksUiPlugin.getRepositoryManager(); manager.clearRepositories(TasksUiPlugin.getDefault().getRepositoriesFilePath()); repository = new TaskRepository(BugzillaCorePlugin.CONNECTOR_KIND, BugzillaFixture.current().getRepositoryUrl()); UserCredentials credentials = CommonTestUtil.getCredentials(PrivilegeLevel.USER); repository.setCredentials(AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), credentials.getPassword()), false); TasksUiPlugin.getRepositoryManager().addRepository(repository); TasksUiTestUtil.ensureTasksUiInitialization(); BugzillaConnectorUi connectorUi = new BugzillaConnectorUi(); wizard = new EditRepositoryWizard(repository, connectorUi); }
Source:
<code><START> public String sendChat(String input) throws ChatScriptDeliveryException { <END> if (!initialized) { return init(null); } ChatScriptMessage g = new ChatScriptMessage(this.userName, this.botName, input); return doMessage(g.toCSFormat()); }</code><technical_language>need create exception, requires change default behavior. Please a standard for use-case</technical_language>

Target:
public String sendChat(String input) throws Exception { if (!initialized) { return init(null); } ChatScriptMessage g = new ChatScriptMessage(this.userName, this.botName, input); return doMessage(g.toCSFormat()); }
Source:
<code>private void buildDeployWithoutServerTemplate(final BuildExecutionContext context, final DeploymentMode mode) { showBuildMessage(); buildServiceCaller.call((RemoteCallback<BuildResults>) result -> { if (result.getErrorMessages().isEmpty()) { notificationEvent.fire(new NotificationEvent(CONSTANTS.BuildSuccessful(), NotificationEvent.NotificationType.SUCCESS)); notificationEvent.fire( new NotificationEvent( CONSTANTS.DeploymentSkippedDueToNoServerTemplateConfiguredForMode( preferedKieServerMode.name().toLowerCase()), NotificationEvent.NotificationType.WARNING) .setAutoHide(false) .setNavigation(CONSTANTS.ViewDeploymentDetails(), <START> SERVER_MANAGEMENT)); <END> } else { notificationEvent.fire(new NotificationEvent(CONSTANTS.BuildFailed(), NotificationEvent.NotificationType.ERROR)); } buildResultsEvent.fire(result); finish(); }, (ErrorCallback<Message>) (message, throwable) -> { buildDeployWithoutServerTemplate(context, DeploymentMode.FORCED); return false; }).buildAndDeploy(context.getModule(), mode); }</code><technical_language>suggestion in other PR, this call like: .setNavigation(CONSTANTS.ViewDeploymentDetails(), new DefaultPlaceRequest(SERVER_MANAGEMENT), projectController.canViewDeploymentDetails()));</technical_language>

Target:
private void buildDeployWithoutServerTemplate(final BuildExecutionContext context, final DeploymentMode mode) { showBuildMessage(); buildServiceCaller.call((RemoteCallback<BuildResults>) result -> { if (result.getErrorMessages().isEmpty()) { notificationEvent.fire(new NotificationEvent(CONSTANTS.BuildSuccessful(), NotificationEvent.NotificationType.SUCCESS)); notificationEvent.fire( new NotificationEvent( CONSTANTS.DeploymentSkippedDueToNoServerTemplateConfiguredForMode( preferedKieServerMode.name().toLowerCase()), NotificationEvent.NotificationType.WARNING) .setAutoHide(false) .setNavigation(CONSTANTS.ViewDeploymentDetails(), new DefaultPlaceRequest(SERVER_MANAGEMENT))); } else { notificationEvent.fire(new NotificationEvent(CONSTANTS.BuildFailed(), NotificationEvent.NotificationType.ERROR)); } buildResultsEvent.fire(result); finish(); }, (ErrorCallback<Message>) (message, throwable) -> { buildDeployWithoutServerTemplate(context, DeploymentMode.FORCED); return false; }).buildAndDeploy(context.getModule(), mode); }
Source:
<code>public String encrypt(String plainTextValue) throws CrypterException { <START> if (isEmpty(plainTextValue)) { <END> throw new CrypterException("Value to encrypt cannot be null or empty."); } if (associatedData == null) { throw new CrypterException("Associated data cannot be null."); } try { byte[] encryptedBytes = aead.encrypt(plainTextValue.getBytes(), associatedData); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (GeneralSecurityException e) { LOGGER.debug("Problem encrypting.", e); throw new CrypterException("Problem encrypting.", e); } }</code><technical_language>Do want encrypt blank, non-empty strings? encrypt(" ") valid input</technical_language>

Target:
public String encrypt(String plainTextValue) throws CrypterException { if (isBlank(plainTextValue)) { throw new CrypterException("Value to encrypt cannot be null or blank."); } if (associatedData == null) { throw new CrypterException("Associated data cannot be null."); } try { byte[] encryptedBytes = aead.encrypt(plainTextValue.getBytes(), associatedData); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (GeneralSecurityException e) { LOGGER.debug("Problem encrypting.", e); throw new CrypterException("Problem encrypting.", e); } }
Source:
<code>private Set<Method> getMethods(Class<?> controller) { <START> Set<Method> methods = new HashSet<>(); <END> for (Method method : new Mirror().on(controller).reflectAll().methods()) { if (!method.getDeclaringClass().equals(Object.class)) { methods.add(method); } } return methods; }</code><technical_language>sort this Set name asc length desc. generate methods greater args count, for overloaded methods</technical_language>

Target:
private List<Method> getMethods(Class<?> controller) { List<Method> methods = new ArrayList<>(); for (Method method : new Mirror().on(controller).reflectAll().methods()) { if (!method.getDeclaringClass().equals(Object.class)) { methods.add(method); } } sort(methods, new SortByArgumentsLengthDesc()); return methods; }
Source:
<code>public DatastreamRecordMetadata(String checkpoint, String topic, int partition) { _checkpoint = checkpoint; _topic = topic; _partition = partition; <START> _recordIndex = 0; <END> }</code><technical_language>nit: this brooklinEventIndex instead? a Record is a collection of events</technical_language>

Target:
public DatastreamRecordMetadata(String checkpoint, String topic, int partition) { _checkpoint = checkpoint; _topic = topic; _partition = partition; _eventIndex = 0; }
Source:
<code>public int outgoingCount() { int count; if ( read.hasTxStateWithChanges() && read.txState().nodeIsAddedInThisTx( getOwningNode() ) ) { count = 0; } else if ( isBuffered() ) { count = bufferedGroup.outgoingCount; } else { count = count( outgoingRawId() ); } return read.hasTxStateWithChanges() ? read.txState().getNodeState( getOwningNode() ) <START> .augmentDegree( Direction.OUTGOING, count, getType() ) : count; <END> }</code><technical_language>Is this correct if is a loop added in transaction well? suspecting Direction.OUTGOING is graphdb semantics include loops</technical_language>

Target:
public int outgoingCount() { int count; if ( isBuffered() ) { count = bufferedGroup.outgoingCount; } else { count = count( outgoingRawId() ); } return read.hasTxStateWithChanges() ? read.txState().getNodeState( getOwningNode() ) .augmentDegree( RelationshipDirection.OUTGOING, count, getType() ) : count; }
Source:
<code><START> protected void updatePodPath(String newPodPath, Map<String, IDeploymentResourceMapper> deploymentResourceMapperByProjectName, IService service) { <END> this.deploymentMapperByProjectName = deploymentResourceMapperByProjectName; newPodPath = getDeploymentDirectory(service, deploymentResourceMapperByProjectName); updatePodPath(newPodPath); }</code><technical_language>mmm newPodPath parameter is completely</technical_language>

Target:
protected void updatePodPath(String newPodPath, Map<String, IDeploymentResourceMapper> deploymentResourceMapperByProjectName, IService service) { this.deploymentMapperByProjectName = deploymentResourceMapperByProjectName; String inferredPodPath = getInferredDeploymentDirectory(service, deploymentResourceMapperByProjectName, newPodPath); firePropertyChange(PROPERTY_POD_PATH_EDITABLE, this.inferredPodPath == null, (this.inferredPodPath = inferredPodPath) == null); if(inferredPodPath != null) { newPodPath = inferredPodPath; } else if (newPodPath == null) { newPodPath = DEFAULT_DEPLOYMENT_DIR; } updatePodPath(newPodPath); }
Source:
<code>public static TenantManagementServiceClient getTenantManagementServiceClient() throws APIManagementException { AuthenticatorClient authenticatorClient = null; try { authenticatorClient = new AuthenticatorClient(keyManagerURL); URL url = new URL(keyManagerURL); <START> String sessionCookie = authenticatorClient.login("admin", "admin", "localhost"); <END> TenantManagementServiceClient tenantManagementServiceClient = new TenantManagementServiceClient(keyManagerURL, sessionCookie); return tenantManagementServiceClient; } catch (Exception e) { throw new APIManagementException("Unable to create new tenantManagementClient ", e); } }</code><technical_language>do need this localhost? This means longer property values coming Deployment Properties</technical_language>

Target:
public static TenantManagementServiceClient getTenantManagementServiceClient() throws APIManagementException { AuthenticatorClient authenticatorClient = null; try { authenticatorClient = new AuthenticatorClient(keyManagerURL); String sessionCookie = authenticatorClient.login("admin", "admin", "localhost"); TenantManagementServiceClient tenantManagementServiceClient = new TenantManagementServiceClient(keyManagerURL, sessionCookie); return tenantManagementServiceClient; } catch (Exception e) { throw new APIManagementException("Unable to create new tenantManagementClient ", e); } }
Source:
<code>public void setUp() throws Exception { brickPosition = 1; <START> Script script = BrickTestUtils.createProjectAndGetStartScript(projectName); <END> script.addBrick(new PlaySoundAndWaitBrick()); soundInfoList = ProjectManager.getInstance().getCurrentSprite().getSoundList(); soundFile = FileTestUtils.saveFileToProject(projectName, ProjectManager.getInstance().getCurrentProject() .getDefaultScene().getName(), "longsound.mp3", org.catrobat.catroid.test.R.raw.longtestsound , InstrumentationRegistry.getContext(), FileTestUtils.FileTypes.SOUND); SoundInfo soundInfo = new SoundInfo(); soundInfo.setSoundFileName(soundFile.getName()); soundInfo.setTitle(soundName); soundInfoList.add(soundInfo); baseActivityTestRule.launchActivity(null); ProjectManager.getInstance().getFileChecksumContainer() .addChecksum(soundInfo.getChecksum(), soundInfo.getAbsolutePath()); }</code><technical_language>please put this in a createProject method</technical_language>

Target:
public void setUp() throws Exception { String soundName = "testSound1"; String projectName = "testProject"; File soundFile; List<SoundInfo> soundInfoList; brickPosition = 1; Script script = BrickTestUtils.createProjectAndGetStartScript(projectName); script.addBrick(new PlaySoundAndWaitBrick()); soundInfoList = ProjectManager.getInstance().getCurrentSprite().getSoundList(); soundFile = FileTestUtils.saveFileToProject(projectName, ProjectManager.getInstance().getCurrentProject() .getDefaultScene().getName(), "longsound.mp3", org.catrobat.catroid.test.R.raw.longtestsound, InstrumentationRegistry.getContext(), FileTestUtils.FileTypes.SOUND); SoundInfo soundInfo = new SoundInfo(); soundInfo.setSoundFileName(soundFile.getName()); soundInfo.setTitle(soundName); soundInfoList.add(soundInfo); baseActivityTestRule.launchActivity(null); ProjectManager.getInstance().getFileChecksumContainer() .addChecksum(soundInfo.getChecksum(), soundInfo.getAbsolutePath()); }
Source:
<code>public ResponseEntity<?> createEventType(@Valid @RequestBody final EventType eventType, final Errors errors, final NativeWebRequest nativeWebRequest) { if (featureToggleService.isFeatureEnabled(DISABLE_EVENT_TYPE_CREATION)) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } if (errors.hasErrors()) { return create(new ValidationProblem(errors), nativeWebRequest); } try { assignTopic(eventType); validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); eventTypeRepository.saveEventType(eventType); <START> topicRepository.createTopic(eventType.getName(), eventType.getDefaultStatistic()); <END> return status(HttpStatus.CREATED).build(); } catch (final InvalidEventTypeException | NoSuchPartitionStrategyException | DuplicatedEventTypeNameException e) { LOG.debug("Failed to create EventType.", e); return create(e.asProblem(), nativeWebRequest); } catch (final TopicCreationException e) { LOG.error("Problem creating kafka topic. Rolling back event type database registration.", e); try { eventTypeRepository.removeEventType(eventType.getTopic()); } catch (final NakadiException e1) { return create(e.asProblem(), nativeWebRequest); } return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return create(e.asProblem(), nativeWebRequest); } }</code><technical_language>I eventType.getTopic()</technical_language>

Target:
public ResponseEntity<?> createEventType(@Valid @RequestBody final EventType eventType, final Errors errors, final NativeWebRequest nativeWebRequest) { if (featureToggleService.isFeatureEnabled(DISABLE_EVENT_TYPE_CREATION)) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } if (errors.hasErrors()) { return create(new ValidationProblem(errors), nativeWebRequest); } try { assignTopic(eventType); validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); eventTypeRepository.saveEventType(eventType); topicRepository.createTopic(eventType.getTopic(), eventType.getDefaultStatistic()); return status(HttpStatus.CREATED).build(); } catch (final InvalidEventTypeException | NoSuchPartitionStrategyException | DuplicatedEventTypeNameException e) { LOG.debug("Failed to create EventType.", e); return create(e.asProblem(), nativeWebRequest); } catch (final TopicCreationException e) { LOG.error("Problem creating kafka topic. Rolling back event type database registration.", e); try { eventTypeRepository.removeEventType(eventType.getTopic()); } catch (final NakadiException e1) { return create(e.asProblem(), nativeWebRequest); } return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return create(e.asProblem(), nativeWebRequest); } }
Source:
<code>public void testRegExpParentInSubpackageIsConsidered() { assertEquals("Invalid package", icCommonRegexpParen, icRootRegexpParent .locateFinest("com.kazgroup.courtlink.common.api")); assertEquals("Invalid package", icCommonRegexpParen, icRootRegexpParent .locateFinest("com.kazgroup.courtlink.common.api")); <START> } <END></code><technical_language>asserts meaningless. I is replace "comon" "other"</technical_language>

Target:
public void testRegExpParentInSubpackageIsConsidered() { assertEquals("Invalid package", icCommonRegexpParen, icRootRegexpParent .locateFinest("com.kazgroup.courtlink.common.api")); assertEquals("Invalid package", icCommonRegexpParen, icRootRegexpParent .locateFinest("com.kazgroup.courtlink.comon.api")); }
Source:
<code>public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { if (receiver instanceof IEditorInput) { IEditorInput editorInput = (IEditorInput) receiver; if (CONTENT_TYPE_ID.equals(property)) { String identifier = String.valueOf(expectedValue); IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); IContentType expected = contentTypeManager.getContentType(identifier); if (expected != null) { IContentType[] contentTypesFor = contentTypeManager.findContentTypesFor(editorInput.getName()); for (IContentType contentType : contentTypesFor) { <START> if (expected.equals(contentType)) { <END> return true; } } } } } return false; }</code><technical_language>This check current contentType is instance of target content type, isKindOf baseType too. FilePropertyTester for instance</technical_language>

Target:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { if (receiver instanceof IEditorInput) { IEditorInput editorInput = (IEditorInput) receiver; if (CONTENT_TYPE_ID.equals(property)) { String identifier = String.valueOf(expectedValue); return testContentType(editorInput, identifier, hasArgument(args, IS_KIND_OF)); } } return false; }
Source:
<code>public SSHLauncher(String host, int port, StandardUsernameCredentials credentials, String jvmOptions, String javaPath, JDKInstaller jdkInstaller, String prefixStartSlaveCmd, String suffixStartSlaveCmd, Integer launchTimeoutSeconds, Integer maxNumRetries, Integer retryWaitTime) { this.host = host; this.jvmOptions = fixEmpty(jvmOptions); this.port = port == 0 ? 22 : port; this.username = null; this.password = null; this.privatekey = null; this.credentials = credentials; this.credentialsId = credentials == null ? null : credentials.getId(); this.javaPath = fixEmpty(javaPath); if (jdkInstaller != null) { this.jdk = jdkInstaller; } this.prefixStartSlaveCmd = fixEmpty(prefixStartSlaveCmd); this.suffixStartSlaveCmd = fixEmpty(suffixStartSlaveCmd); this.launchTimeoutSeconds = launchTimeoutSeconds == null || launchTimeoutSeconds <= 0 ? null : launchTimeoutSeconds; <START> final Integer zero = 0; <END> this.maxNumRetries = maxNumRetries == null || maxNumRetries <= 0 ? zero : maxNumRetries; this.retryWaitTime = retryWaitTime == null || retryWaitTime <= 0 ? zero : retryWaitTime; }</code><technical_language>Integer.valueOf(0)</technical_language>

Target:
public SSHLauncher(String host, int port, StandardUsernameCredentials credentials, String jvmOptions, String javaPath, JDKInstaller jdkInstaller, String prefixStartSlaveCmd, String suffixStartSlaveCmd, Integer launchTimeoutSeconds, Integer maxNumRetries, Integer retryWaitTime) { this.host = host; this.jvmOptions = fixEmpty(jvmOptions); this.port = port == 0 ? 22 : port; this.username = null; this.password = null; this.privatekey = null; this.credentials = credentials; this.credentialsId = credentials == null ? null : credentials.getId(); this.javaPath = fixEmpty(javaPath); if (jdkInstaller != null) { this.jdk = jdkInstaller; } this.prefixStartSlaveCmd = fixEmpty(prefixStartSlaveCmd); this.suffixStartSlaveCmd = fixEmpty(suffixStartSlaveCmd); this.launchTimeoutSeconds = launchTimeoutSeconds == null || launchTimeoutSeconds <= 0 ? null : launchTimeoutSeconds; this.maxNumRetries = maxNumRetries != null && maxNumRetries > 0 ? maxNumRetries : 0; this.retryWaitTime = retryWaitTime != null && retryWaitTime > 0 ? retryWaitTime : 0; }
Source:
<code>public void testCreateDatabase() { sql("create database db1") .ok("CREATE DATABASE `DB1` WITH (\n" + " 'is_generic' = 'false'\n" + ")"); sql("create database db1 comment 'comment db1' location '/path/to/db1'") .ok("CREATE DATABASE `DB1`\n" + "COMMENT 'comment db1' WITH (\n" + " 'is_generic' = 'false',\n" + " 'database.location_uri' = '/path/to/db1'\n" + ")"); sql("create database db1 with dbproperties ('k1'='v1','k2'='v2')") .ok("CREATE DATABASE `DB1` WITH (\n" + " 'k1' = 'v1',\n" + " 'k2' = 'v2',\n" + <START> " 'is_generic' = 'false'\n" + <END> ")"); }</code><technical_language>unparse SQL is</technical_language>

Target:
public void testCreateDatabase() { sql("create database db1") .ok("CREATE DATABASE `DB1`"); sql("create database db1 comment 'comment db1' location '/path/to/db1'") .ok("CREATE DATABASE `DB1`\n" + "COMMENT 'comment db1'\n" + "LOCATION '/path/to/db1'"); sql("create database db1 with dbproperties ('k1'='v1','k2'='v2')") .ok("CREATE DATABASE `DB1` WITH DBPROPERTIES (\n" + " 'k1' = 'v1',\n" + " 'k2' = 'v2'\n" + ")"); }
Source:
<code>private void initNodeIdentifier() { if (arjPropertyManager.getCoreEnvironmentBean().getNodeIdentifier() == null) { <START> LOGGER.info("Node identifier was not set. Setting it to the default value: " + DEFAULT_NODE_IDENTIFIER); <END> try { arjPropertyManager.getCoreEnvironmentBean().setNodeIdentifier(DEFAULT_NODE_IDENTIFIER); } catch (CoreEnvironmentBeanException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } } jtaPropertyManager.getJTAEnvironmentBean() .setXaRecoveryNodes(Collections.singletonList(arjPropertyManager.getCoreEnvironmentBean().getNodeIdentifier())); }</code><technical_language>this a WARN</technical_language>

Target:
private void initNodeIdentifier() { if (arjPropertyManager.getCoreEnvironmentBean().getNodeIdentifier() == null) { LOGGER.warning("Node identifier was not set. Setting it to the default value: " + DEFAULT_NODE_IDENTIFIER); try { arjPropertyManager.getCoreEnvironmentBean().setNodeIdentifier(DEFAULT_NODE_IDENTIFIER); } catch (CoreEnvironmentBeanException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } } jtaPropertyManager.getJTAEnvironmentBean() .setXaRecoveryNodes(Collections.singletonList(arjPropertyManager.getCoreEnvironmentBean().getNodeIdentifier())); }
Source:
<code>public void run() throws IOException { ui.header("Gitiles"); if (!confirm()) { return; } gitweb.unset("cgi"); gitweb.unset("pathSeparator"); <START> gitweb.set("url", "/plugins/gitiles/"); <END> gitweb.set("type", "custom"); gitweb.set("revision", "${project}/+/${commit}"); gitweb.set("project", "${project}"); gitweb.set("branch", "${project}/+/${branch}"); gitweb.set("filehistory", "${project}/+log/${branch}/${file}"); gitweb.set("linkname", "gitiles"); gitilesConfig.createNewFile(); }</code><technical_language>This need omit leading /. want load plugin relative host page server root in case running in a subdirectory</technical_language>

Target:
public void run() throws IOException { ui.header("Gitiles"); if (!confirm()) { return; } gitweb.set("type", "custom"); gitweb.set("linkname", "gitiles"); gitweb.unset("cgi"); gitweb.unset("pathSeparator"); gitweb.set("url", "plugins/gitiles/"); gitweb.set("revision", "${project}/+/${commit}"); gitweb.set("project", "${project}"); gitweb.set("branch", "${project}/+/${branch}"); gitweb.set("filehistory", "${project}/+log/${branch}/${file}"); gitilesConfig.createNewFile(); }
Source:
<code>public void run() { if (fZoomEntryList == null) { return; } for (TimeGraphEntry entry : fZoomEntryList) { if (fMonitor.isCanceled()) { break; } zoom(entry, fMonitor); } List<TimeLinkEvent> events = getLinkList(fZoomStartTime, fZoomEndTime, fResolution, fMonitor); <START> fTimeGraphCombo.setLinks(events.toArray(new TimeLinkEvent[0])); <END> redraw(); }</code><technical_language>unnecessary transforming of list array? stick collection for performance reasons</technical_language>

Target:
public void run() { if (fZoomEntryList == null) { return; } for (TimeGraphEntry entry : fZoomEntryList) { if (fMonitor.isCanceled()) { break; } zoom(entry, fMonitor); } List<ILinkEvent> events = getLinkList(fZoomStartTime, fZoomEndTime, fResolution, fMonitor); fTimeGraphCombo.setLinks(events); redraw(); }
Source:
<code><START> private boolean newValidationSetExists() { <END> if (currentTrainingSetSize >= allTrainingData.size()) { return false; } else return true; }</code><technical_language>return inverse of conditional: return currentTrainingSetSize < allTrainingData.size();</technical_language>

Target:
private boolean newValidationSetExists() { return currentTrainingSetSize < allTrainingData.size(); }
Source:
<code>public int compareTo(DataNodeId o) { if (getClass() != o.getClass()) { throw new IllegalStateException("Incompatible objects to compare"); } AmbryDataNode other = (AmbryDataNode) o; <START> int compare = Integer.compare(plainTextPort.getPort(), other.plainTextPort.getPort()); <END> if (compare == 0) { compare = hostName.compareTo(other.hostName); } return compare; }</code><technical_language>Java 8 some constructs for multi-field comparison pattern encounter. Here, do following: java return Comparator.comparingInt((AmbryDataNode k) -> k.plainTextPort.getPort()). thenComparing(k -> k.hostName).compare(this, other);</technical_language>

Target:
public int compareTo(DataNodeId o) { if (getClass() != o.getClass()) { throw new IllegalStateException("Incompatible objects to compare"); } AmbryDataNode other = (AmbryDataNode) o; return Comparator.comparingInt((AmbryDataNode k) -> k.plainTextPort.getPort()). thenComparing(k -> k.hostName).compare(this, other); }