auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testConvertADateToMagmaDate() throws Exception { dsFactory.addFile(getResourceFile("org/obiba/magma/datasource/spss/date-value-types.sav")); Datasource ds = dsFactory.create(); ds.initialise(); ValueTable valueTable = ds.getValueTable("date-value-types"); assertThat(valueTable).isNotNull(); Iterator<VariableEntity> iterator = valueTable.getVariableEntities().iterator(); Value v; if(iterator.hasNext()) { SpssValueSet valueSet = (SpssValueSet) valueTable.getValueSet(iterator.next()); <START> v = valueSet.getValue(ds.getValueTable("date-value-types").getVariable("var1")); <END> assertThat(v.compareTo(DateType.get().valueOf("2013-4-15"))).isEqualTo(0); v = valueSet.getValue(ds.getValueTable("date-value-types").getVariable("var2")); assertThat(v.compareTo(DateType.get().valueOf("2012-12-30"))).isEqualTo(0); v = valueSet.getValue(ds.getValueTable("date-value-types").getVariable("var3")); assertThat(v.compareTo(DateType.get().valueOf("2014-03-12"))).isEqualTo(0); v = valueSet.getValue(ds.getValueTable("date-value-types").getVariable("var4")); assertThat(v.compareTo(DateType.get().valueOf("2010-09-23"))).isEqualTo(0); v = valueSet.getValue(ds.getValueTable("date-value-types").getVariable("var5")); assertThat(v.compareTo(DateType.get().valueOf("2010-03-12"))).isEqualTo(0); v = valueSet.getValue(ds.getValueTable("date-value-types").getVariable("var5")); assertThat(v.compareTo(DateType.get().valueOf("2010-03-12"))).isEqualTo(0); v = valueSet.getValue(ds.getValueTable("date-value-types").getVariable("var6")); assertThat(v.compareTo(DateType.get().valueOf("2010-02-12"))).isEqualTo(0); } }</code><technical_language>reuse variable</technical_language>

Target:
public void testConvertADateToMagmaDate() throws Exception { dsFactory.addFile(getResourceFile("org/obiba/magma/datasource/spss/date-value-types.sav")); Datasource ds = dsFactory.create(); ds.initialise(); ValueTable valueTable = ds.getValueTable("date-value-types"); assertThat(valueTable).isNotNull(); Iterator<VariableEntity> iterator = valueTable.getVariableEntities().iterator(); if(iterator.hasNext()) { SpssValueSet valueSet = (SpssValueSet) valueTable.getValueSet(iterator.next()); assertThat(valueSet.getValue(valueTable.getVariable("var1")).compareTo(DateType.get().valueOf("2013-4-15"))) .isEqualTo(0); assertThat(valueSet.getValue(valueTable.getVariable("var2")).compareTo(DateType.get().valueOf("2012-12-30"))) .isEqualTo(0); assertThat(valueSet.getValue(valueTable.getVariable("var3")).compareTo(DateType.get().valueOf("2014-03-12"))) .isEqualTo(0); assertThat(valueSet.getValue(valueTable.getVariable("var4")).compareTo(DateType.get().valueOf("2010-09-23"))) .isEqualTo(0); assertThat(valueSet.getValue(valueTable.getVariable("var5")).compareTo(DateType.get().valueOf("2010-03-12"))) .isEqualTo(0); assertThat(valueSet.getValue(valueTable.getVariable("var6")).compareTo(DateType.get().valueOf("2010-02-12"))) .isEqualTo(0); } }
Source:
<code>public Map<String, Object> findDonors( @RequestParam(value = "firstName", required = false, defaultValue = "") String firstName, @RequestParam(value = "lastName", required = false, defaultValue = "") String lastName, @RequestParam(value = "donorNumber", required = false) String donorNumber, @RequestParam(value = "usePhraseMatch", required = false) boolean usePhraseMatch, @RequestParam(value = "donationIdentificationNumber", required = false) String donationIdentificationNumber) { List<Donor> results = new ArrayList<>(); <START> if (StringUtils.isNotEmpty(donorNumber)) { <END> try { results = Arrays.asList(donorRepository.findDonorByDonorNumber(donorNumber)); } catch (NoResultException nre) { } } else if (StringUtils.isNotEmpty(donationIdentificationNumber)) { try { results = Arrays.asList(donorRepository.findDonorByDonationIdentificationNumber(donationIdentificationNumber)); } catch (NoResultException nre) { } } else { results = donorRepository.findAnyDonor(firstName, lastName, usePhraseMatch); } List<DonorViewModel> donors = new ArrayList<DonorViewModel>(); for (Donor donor : results) { donors.add(donorViewModelFactory.createDonorViewModelWithPermissions(donor)); } Map<String, Object> map = new HashMap<>(); map.put("donors", donors); map.put("canAddDonors", canAddDonors()); return map; }</code><technical_language>Tto safer, prefer isNotBlank isNotEmpty accept a donorNumber spaces empty</technical_language>

Target:
public Map<String, Object> findDonors( @RequestParam(value = "firstName", required = false, defaultValue = "") String firstName, @RequestParam(value = "lastName", required = false, defaultValue = "") String lastName, @RequestParam(value = "donorNumber", required = false) String donorNumber, @RequestParam(value = "usePhraseMatch", required = false) boolean usePhraseMatch, @RequestParam(value = "donationIdentificationNumber", required = false) String donationIdentificationNumber) { List<Donor> donors = new ArrayList<>(); if (StringUtils.isNotBlank(donorNumber)) { try { donors = Arrays.asList(donorRepository.findDonorByDonorNumber(donorNumber)); } catch (NoResultException nre) { } } else if (StringUtils.isNotBlank(donationIdentificationNumber)) { try { donors = Arrays.asList(donorRepository.findDonorByDonationIdentificationNumber(donationIdentificationNumber)); } catch (NoResultException nre) { } } else { donors = donorRepository.findAnyDonor(firstName, lastName, usePhraseMatch); } Map<String, Object> map = new HashMap<>(); map.put("donors", donorViewModelFactory.createDonorSummaryViewModels(donors)); map.put("canAddDonors", canAddDonors()); return map; }
Source:
<code>private void assertKeyType(TypeDescription schema) { <START> TypeDescription keyType = schema.getChildren().get(0); <END> String keyTypeName = keyType.getCategory().getName(); if (!keyTypeName.equals("string")) { throw new IllegalArgumentException( String.format("Unsupported key type: %s", keyTypeName)); } }</code><technical_language>guarantee schema Children? children schema representing</technical_language>

Target:
private void assertKeyType(TypeDescription schema) { TypeDescription keyType = schema.getChildren().get(0); String keyTypeName = keyType.getCategory().getName(); if (!keyTypeName.equalsIgnoreCase("string")) { throw new IllegalArgumentException( String.format("Unsupported key type: %s", keyTypeName)); } }
Source:
<code>public String setChangeTooltip(MergeMode mode, Diff diff, boolean isFromLeft) { boolean isUnset = false; String tooltip; if (diff instanceof ReferenceChange) { if (isUnset((ReferenceChange)diff)) { isUnset = true; } } else if (diff instanceof AttributeChange) { AttributeChange change = (AttributeChange)diff; if (isUnset(change, getChangedValueFromModel(change))) { isUnset = true; } } if <START> (isUnset) { <END> tooltip = setUnsetTooltip(mode, diff, isFromLeft); } else { tooltip = setSetTooltip(mode, diff, isFromLeft); } return tooltip; }</code><technical_language>extract this a method isUnset(Diff) well. util methods for determining is unset? generic there, if yet</technical_language>

Target:
public String setChangeTooltip(MergeMode mode, Diff diff, boolean isFromLeft) { boolean isUnset = isUnset(diff); String tooltip; if (isUnset) { tooltip = setUnsetTooltip(mode, diff, isFromLeft); } else { tooltip = setSetTooltip(mode, diff, isFromLeft); } return tooltip; }
Source:
<code>public synchronized void move(Unit unit, int dx, int dy){ if (!isGameRunning() || !grid.contains(unit)){ return; } Point origin = grid.find(unit); Point dest = new Point(origin); dest.translate(dx, dy); if (!grid.getPossibleMoves(origin).contains(dest)){ return; } grid.set(unit, dest); for (Entity entity : grid.get(dest)){ if (entity instanceof Unit && !unit.equals(entity)){ if (unit instanceof Player) { <START> if(((Player) unit).canBeHurtBy(entity)){ <END> killPlayer((Player) unit); } } if (entity instanceof Player){ if(((Player) entity).canBeHurtBy(unit)){ killPlayer((Player) entity); } } } } if (unit instanceof Player){ for (Entity entity : grid.get(dest)){ if (entity instanceof Door){ send(new WinEvent((Player)unit, grid)); endGame(); } } } if(unit instanceof Player){ for(Entity entity : grid.get(dest)){ if(entity instanceof Powerup){ ((Player) unit).addPowerup((Powerup)entity); grid.remove(entity); } } } }</code><technical_language>Remove casting here</technical_language>

Target:
public synchronized void move(Unit unit, int dx, int dy){ if (!isGameRunning() || !grid.contains(unit)){ return; } Point origin = grid.find(unit); Point dest = new Point(origin); dest.translate(dx, dy); if (!grid.getPossibleMoves(origin).contains(dest)){ return; } grid.set(unit, dest); for (Entity entity : grid.get(dest)){ if (entity instanceof Unit && !unit.equals(entity)){ if(unit.canBeHurtBy(entity)){ killUnit(unit); } if (entity instanceof Unit){ if(((Unit) entity).canBeHurtBy(unit)){ killUnit((Unit) entity); } } } } if(unit instanceof Player){ for(Entity entity : grid.get(dest)){ if(entity instanceof Powerup){ ((Player) unit).addPowerup((Powerup)entity); grid.remove(entity); } } } if (unit instanceof Player){ for (Entity entity : grid.get(dest)){ if (entity instanceof Door){ send(new WinEvent((Player)unit, grid)); endGame(); } } } }
Source:
<code>public void visitToken(Token token) { if (token.getType().equals(PythonTokenType.STRING)) { highlight(token, TypeOfText.STRING); } else if (token.getType() instanceof PythonKeyword) { highlight(token, TypeOfText.KEYWORD); } else if (token.getType().equals(GenericTokenType.COMMENT)) { highlight(token, TypeOfText.COMMENT); } <START> if (token.hasTrivia()) { <END> for (Trivia trivia : token.getTrivia()) { if (trivia.isComment()) { highlight(trivia.getToken(), TypeOfText.COMMENT); } } } }</code><technical_language>@ivandalbosco drop this line token.getTrivia() return empty list</technical_language>

Target:
public void visitToken(Token token) { if (token.getType().equals(PythonTokenType.STRING)) { highlight(token, TypeOfText.STRING); } else if (token.getType() instanceof PythonKeyword) { highlight(token, TypeOfText.KEYWORD); } for (Trivia trivia : token.getTrivia()) { highlight(trivia.getToken(), TypeOfText.COMMENT); } }
Source:
<code>public TimeGraphScale(Composite parent, TimeGraphColorScheme colors, int style) { super(parent, colors, SWT.NO_BACKGROUND | SWT.NO_FOCUS | SWT.DOUBLE_BUFFERED); TmfSignalManager.register(this); addMouseListener(this); addMouseMoveListener(this); TimeDraw.updateTimeZone(); addDisposeListener((e) -> { TmfSignalManager.deregister(TimeGraphScale.this); }); GC gc = new GC(parent.getDisplay()); fDigitWidth = gc.getCharWidth('0'); gc.dispose(); int styleMask = SWT.TOP | SWT.BOTTOM; <START> fAlign = (style & styleMask) == 0 ? SWT.TOP : style & styleMask; <END> }</code><technical_language>I do: if SWT.BOTTOM SWT.TOP</technical_language>

Target:
public TimeGraphScale(Composite parent, TimeGraphColorScheme colors, int style) { super(parent, colors, SWT.NO_BACKGROUND | SWT.NO_FOCUS | SWT.DOUBLE_BUFFERED); TmfSignalManager.register(this); addMouseListener(this); addMouseMoveListener(this); TimeDraw.updateTimeZone(); addDisposeListener((e) -> { TmfSignalManager.deregister(TimeGraphScale.this); }); GC gc = new GC(parent.getDisplay()); fDigitWidth = gc.getCharWidth('0'); gc.dispose(); fAlign = (style & SWT.BOTTOM) == 0 ? SWT.TOP : style & SWT.BOTTOM; }
Source:
<code>public void updateWriterUsage(PublicKeyHash writer, MaybeMultihash target, Set<PublicKeyHash> ownedKeys, long retainedStorage) { String owner = getOwner(writer); int writerId = getWriterId(writer); try (PreparedStatement insert = conn.prepareStatement("UPDATE writerusage SET target=?, direct_size=? WHERE writer_id = ?;")) { insert.setBytes(1, target.isPresent() ? target.get().toBytes() : null); insert.setLong(2, retainedStorage); insert.setInt(3, writerId); int count = insert.executeUpdate(); if (count != 1) throw new IllegalStateException("Didn't update one record!"); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } <START> setWriters(owner, writer, ownedKeys); <END> }</code><technical_language>deal other place. I guess if call updateWroterUsage() for writerId is concurrent, ok</technical_language>

Target:
public void updateWriterUsage(PublicKeyHash writer, MaybeMultihash target, Set<PublicKeyHash> ownedKeys, long retainedStorage) { int writerId = getWriterId(writer); try (Connection conn = getNonCommittingConnection(); PreparedStatement insert = conn.prepareStatement("UPDATE writerusage SET target=?, direct_size=? WHERE writer_id = ?;"); PreparedStatement delete = conn.prepareStatement("DELETE FROM ownedkeys WHERE parent_id = ?;"); PreparedStatement writerSelect = conn.prepareStatement("SELECT id FROM writers WHERE key_hash = ?;"); PreparedStatement insertOwned = conn.prepareStatement("INSERT INTO ownedkeys (parent_id, owned_id) VALUES(?, ?);")) { try { insert.setBytes(1, target.isPresent() ? target.get().toBytes() : null); insert.setLong(2, retainedStorage); insert.setInt(3, writerId); int count = insert.executeUpdate(); if (count != 1) throw new IllegalStateException("Didn't update one record!"); delete.setInt(1, writerId); delete.executeUpdate(); for (PublicKeyHash owned : ownedKeys) { writerSelect.setBytes(1, owned.toBytes()); ResultSet writerRes = writerSelect.executeQuery(); writerRes.next(); int ownedId = writerRes.getInt(1); insertOwned.setInt(1, writerId); insertOwned.setInt(2, ownedId); insertOwned.execute(); } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } }
Source:
<code>private static boolean isCollectionUtilsIsEmpty(Symbol.MethodSymbol symbol) { Type type = symbol.owner().type(); return (type.is("org.apache.commons.collections4.CollectionUtils") || type.is("org.apache.commons.collections.CollectionUtils")) <START> && "isEmpty".equals(symbol.name()); <END> }</code><technical_language>I include [CollectionUtils.isNotEmpty()](<LINK_0>, a null-safe check, method yields in case of false result : - result is false, arg0 is null; - result is false, arg0 is not-null ( empty ) - result is true, arg0 is not-null (and not-empty)</technical_language>

Target:
private static boolean isCollectionUtilsIsEmpty(Symbol.MethodSymbol symbol) { Type type = symbol.owner().type(); return (type.is("org.apache.commons.collections4.CollectionUtils") || type.is("org.apache.commons.collections.CollectionUtils")) && ("isEmpty".equals(symbol.name()) || "isNotEmpty".equals(symbol.name())); }
Source:
<code>public static Collection<ThreadGroup> findThreadGroups(final ThreadGroup group, final boolean recurse, final ThreadGroupPredicate predicate){ if (group == null) { throw new IllegalArgumentException("The group must not be null"); } if (predicate == null) { throw new IllegalArgumentException("The predicate must not be null"); } int count = group.activeGroupCount(); ThreadGroup[] threadGroups; do { <START> threadGroups = new ThreadGroup[count + (count>>1) + 1]; <END> count = group.enumerate(threadGroups, recurse); } while(count >= threadGroups.length); final List<ThreadGroup> result = new ArrayList<ThreadGroup>(count); for(int i = 0; i<count; ++i) { if(predicate.test(threadGroups[i])) { result.add(threadGroups[i]); } } return Collections.unmodifiableCollection(result); }</code><technical_language>magic right shift? is this based experience</technical_language>

Target:
public static Collection<ThreadGroup> findThreadGroups(final ThreadGroup group, final boolean recurse, final ThreadGroupPredicate predicate){ if (group == null) { throw new IllegalArgumentException("The group must not be null"); } if (predicate == null) { throw new IllegalArgumentException("The predicate must not be null"); } int count = group.activeGroupCount(); ThreadGroup[] threadGroups; do { threadGroups = new ThreadGroup[count + (count / 2) + 1]; count = group.enumerate(threadGroups, recurse); } while(count >= threadGroups.length); final List<ThreadGroup> result = new ArrayList<ThreadGroup>(count); for(int i = 0; i < count; ++i) { if(predicate.test(threadGroups[i])) { result.add(threadGroups[i]); } } return Collections.unmodifiableCollection(result); }
Source:
<code>protected void commonInitialize() { super.commonInitialize(); getModel().getIsHighlyAvailable().getEntityChangedEvent().addListener((ev, sender, args) -> { boolean <START> ha = <END> getModel().getIsHighlyAvailable().getEntity(); if (ha) { Guid bootableDiskStorageDomainId = getBootableDiskStorageDomainId(); if (bootableDiskStorageDomainId != null) { setVmleaseDefaultStorageDomain(bootableDiskStorageDomainId); } } }); getModel().getIsStateless().getEntityChangedEvent().addListener(new UpdateTemplateWithVersionListener() { @Override protected void beforeUpdate() { updateStatelessFlag = false; } @Override protected boolean isAddLatestVersion() { return getModel().getIsStateless().getEntity(); } }); }</code><technical_language>local var removed, helpful here.</technical_language>

Target:
protected void commonInitialize() { super.commonInitialize(); getModel().getIsHighlyAvailable().getEntityChangedEvent().addListener((ev, sender, args) -> { if (getModel().getIsHighlyAvailable().getEntity()) { Guid bootableDiskStorageDomainId = getBootableDiskStorageDomainId(); if (bootableDiskStorageDomainId != null) { setVmLeaseDefaultStorageDomain(bootableDiskStorageDomainId); } } }); getModel().getIsStateless().getEntityChangedEvent().addListener(new UpdateTemplateWithVersionListener() { @Override protected void beforeUpdate() { updateStatelessFlag = false; } @Override protected boolean isAddLatestVersion() { return getModel().getIsStateless().getEntity(); } }); }
Source:
<code><START> public static synchronized void removeSession(SyncConfiguration syncConfiguration) { <END> if (syncConfiguration == null) { throw new IllegalArgumentException("A non-empty 'syncConfiguration' is required."); } SyncSession syncSession = sessions.remove(syncConfiguration.getPath()); if (syncSession != null) { syncSession.close(); } }</code><technical_language>Create io.realm.internal.objectserver.SessionManager move sessions there? I uncomfortable expose removeSession() public</technical_language>

Target:
private static synchronized void removeSession(SyncConfiguration syncConfiguration) { if (syncConfiguration == null) { throw new IllegalArgumentException("A non-empty 'syncConfiguration' is required."); } SyncSession syncSession = sessions.remove(syncConfiguration.getPath()); if (syncSession != null) { syncSession.close(); } }
Source:
<code>private String chooseQueue(String requestedQueue, List<String> roles, Map<String, String> olapServerIsolatedRoles) { if (requestedQueue != null) { for (String role: roles) { if (requestedQueue.equals(olapServerIsolatedRoles.get(role))) { return requestedQueue; } } return "default"; } for (String role: roles) { if (olapServerIsolatedRoles.get(role) != null) { return olapServerIsolatedRoles.get(role); } } <START> return "default"; <END> }</code><technical_language>return "default" expression in method _iff_ if else for inside. code hard read is now. if (requestedQueue != null) { ... // return "default"; } else { ... // return "default"; } return "default";</technical_language>

Target:
private String chooseQueue(String requestedQueue, List<String> roles, Map<String, String> olapServerIsolatedRoles) { if (requestedQueue != null) { for (String role: roles) { if (requestedQueue.equals(olapServerIsolatedRoles.get(role))) { return requestedQueue; } } } else { for (String role : roles) { if (olapServerIsolatedRoles.get(role) != null) { return olapServerIsolatedRoles.get(role); } } } return SIConstants.OLAP_DEFAULT_QUEUE_NAME; }
Source:
<code>public int hashCode() { int[] hashArr = {0}; final TreeWalkTraverseProcessor treeWalkTraverseProcessor = new TreeWalkTraverseProcessorImpl(); treeWalkTraverseProcessor .traverse(this, new AbstractTreeTraverseCallback<Graph, Node, Edge>() { int[] myHashArr = hashArr; @Override public void startGraphTraversal(final org.kie.workbench.common.stunner.core.graph.Graph graph) { super.startGraphTraversal(graph); } @Override public boolean startEdgeTraversal(final Edge edge) { super.startEdgeTraversal(edge); final Object content = edge.getContent(); myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], content.hashCode()); if (content instanceof Child) { myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], edge.getSourceNode().hashCode()); } else if (content instanceof View) { if (null != edge.getTargetNode()) { myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], edge.getTargetNode().hashCode()); } if (null != edge.getSourceNode()) { myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], edge.getSourceNode().hashCode()); } } else if (content instanceof Dock) { final Node parent = edge.getSourceNode(); final Node docked = edge.getTargetNode(); myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], parent.hashCode(), docked.hashCode()); } return true; } @Override <START> public void endEdgeTraversal(final Edge edge) { <END> super.endEdgeTraversal(edge); } @Override public boolean startNodeTraversal(final Node node) { super.startNodeTraversal(node); myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], node.hashCode()); if (!(node.getContent() instanceof DefinitionSet) && node.getContent() instanceof Definition) { Object def = ((Definition) (node.getContent())).getDefinition(); myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], def.hashCode()); } return true; } }); return hashArr[0]; }</code><technical_language>method endEdgeTraversal removed - need override this method, exist a default method interface</technical_language>

Target:
public int hashCode() { int[] hashArr = {0}; final TreeWalkTraverseProcessor treeWalkTraverseProcessor = new TreeWalkTraverseProcessorImpl(); treeWalkTraverseProcessor .traverse(this, new AbstractTreeTraverseCallback<Graph, Node, Edge>() { int[] myHashArr = hashArr; @Override public boolean startEdgeTraversal(final Edge edge) { super.startEdgeTraversal(edge); final Object content = edge.getContent(); myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], content.hashCode()); return true; } @Override public boolean startNodeTraversal(final Node node) { super.startNodeTraversal(node); myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], node.hashCode()); if (!(node.getContent() instanceof DefinitionSet) && node.getContent() instanceof Definition) { Object def = ((Definition) (node.getContent())).getDefinition(); myHashArr[0] = HashUtil.combineHashCodes(myHashArr[0], def.hashCode()); } return true; } }); return hashArr[0]; }
Source:
<code><START> public void <END> checkCertificationValidity() { try { if (!checkCertificate(EngineEncryptionUtils.getCertificate(EngineLocalConfig.getInstance().getPKICACert()), AuditLogType.ENGINE_CA_CERTIFICATION_HAS_EXPIRED, AuditLogType.ENGINE_CA_CERTIFICATION_IS_ABOUT_TO_EXPIRE_ALERT, AuditLogType.ENGINE_CA_CERTIFICATION_IS_ABOUT_TO_EXPIRE, null) ^ !checkCertificate((X509Certificate) EngineEncryptionUtils.getCertificate(), AuditLogType.ENGINE_CERTIFICATION_HAS_EXPIRED, AuditLogType.ENGINE_CERTIFICATION_IS_ABOUT_TO_EXPIRE_ALERT, AuditLogType.ENGINE_CERTIFICATION_IS_ABOUT_TO_EXPIRE, null)) { return; } if (!Config.<Boolean>getValue(ConfigValues.EncryptHostCommunication)) { return; } hostDao.getAll() .stream() .filter(host -> host.getStatus() == VDSStatus.Up || host.getStatus() == VDSStatus.NonOperational) .forEach(this::checkHostCertificateValidity); } catch (Exception e) { log.error("Failed to check certification validity: {}", e.getMessage()); log.error("Exception", e); } }</code><technical_language>ManagedExecutorService able execute this method if private</technical_language>

Target:
private void checkCertificationValidity() { try { if (!checkCertificate(EngineEncryptionUtils.getCertificate(EngineLocalConfig.getInstance().getPKICACert()), AuditLogType.ENGINE_CA_CERTIFICATION_HAS_EXPIRED, AuditLogType.ENGINE_CA_CERTIFICATION_IS_ABOUT_TO_EXPIRE_ALERT, AuditLogType.ENGINE_CA_CERTIFICATION_IS_ABOUT_TO_EXPIRE, null) ^ !checkCertificate((X509Certificate) EngineEncryptionUtils.getCertificate(), AuditLogType.ENGINE_CERTIFICATION_HAS_EXPIRED, AuditLogType.ENGINE_CERTIFICATION_IS_ABOUT_TO_EXPIRE_ALERT, AuditLogType.ENGINE_CERTIFICATION_IS_ABOUT_TO_EXPIRE, null)) { return; } if (!Config.<Boolean>getValue(ConfigValues.EncryptHostCommunication)) { return; } hostDao.getAll() .stream() .filter(host -> host.getStatus() == VDSStatus.Up || host.getStatus() == VDSStatus.NonOperational) .forEach(this::checkHostCertificateValidity); } catch (Exception e) { log.error("Failed to check certification validity: {}", e.getMessage()); log.error("Exception", e); } }
Source:
<code>public void testSupplySuite() { insertBenchmarkQuery(handle, QUERY_SET, "Q1", "SELECT 1"); insertBenchmarkQuery(handle, QUERY_SET, "Q2", "SELECT 2"); insertBenchmarkQuery(handle, QUERY_SET, "Q3", "SELECT 3"); <START> insertBenchmarkSuite(handle, SUITE, QUERY_SET, "[{\"executionStrategy\": \"STREAM\",\"streamConfiguration\": [[\"Q1\", \"Q2\"],[\"Q2\", \"Q3\"]]}, {\"executionStrategy\": \"CONCURRENT\",\"streamConfiguration\": [[\"Q2\", \"Q3\"],[\"Q1\",\"Q2\"]]}]", "{\"max\":\"5\"}"); <END> assertEquals(new DbBenchmarkSuiteSupplier(jdbi, config.setSuite(SUITE)).get(), getBenchmarkSuiteObject(SUITE, QUERY_SET)); }</code><technical_language>Avoid constructing json stream yourself. private static final PHASE_SPECIFICATIONS_CODEC = jsonCodec(PhaseSpecification.class); PHASE_SPECIFICATIONS_CODEC.toJson(new ....);</technical_language>

Target:
public void testSupplySuite() { insertBenchmarkQuery(handle, QUERY_SET, "Q1", "SELECT 1"); insertBenchmarkQuery(handle, QUERY_SET, "Q2", "SELECT 2"); insertBenchmarkQuery(handle, QUERY_SET, "Q3", "SELECT 3"); insertBenchmarkSuite(handle, SUITE, QUERY_SET, PHASE_SPECIFICATION_LIST_CODEC.toJson(getBenchmarkSuitePhases()), MAP_CODEC.toJson(getBenchmarkSuiteSessionProperties())); assertEquals(new DbBenchmarkSuiteSupplier(jdbi, new BenchmarkSuiteConfig().setSuite(SUITE)).get(), getBenchmarkSuiteObject(SUITE, QUERY_SET)); }
Source:
<code><START> protected void invokeCommands(ArrayList<VdcReturnValueBase> returnValues) { <END> if (canRunActions(returnValues)) { if (isWaitForResult) { invokeSyncCommands(); } else { invokeCommands(); } } }</code><technical_language>please this method private</technical_language>

Target:
private void invokeCommands(ArrayList<VdcReturnValueBase> returnValues) { if (canRunActions(returnValues)) { if (isWaitForResult) { invokeSyncCommands(); } else { invokeCommands(); } } }
Source:
<code>private List<TreeItem> getTreeItems(Iterator<TreeItem> iterator, String... path) { <START> if (path.length == 0 || path == null) { <END> throw new IllegalArgumentException("Path to a tree item cannot be null"); } int index = 0; Iterator<TreeItem> nestedItemsIterator = iterator; List<TreeItem> resultItems = new ArrayList<TreeItem>(); while (index < path.length) { List<TreeItem> nestedItems = new ArrayList<TreeItem>(); while (nestedItemsIterator.hasNext()) { TreeItem item = nestedItemsIterator.next(); if (getNonStyledText(item).equals(path[index])) { if (!item.isExpanded()) { item.expand(); } if (index == path.length - 1) { resultItems.add(item); } else { nestedItems.addAll(item.getItems()); } } } nestedItemsIterator = nestedItems.iterator(); index++; } if (resultItems.size() == 0) { throw new JFaceLayerException("There is no tree item with path " + Arrays.toString(path)); } return resultItems; }</code><technical_language>null check length check</technical_language>

Target:
private List<TreeItem> getTreeItems(Iterator<TreeItem> iterator, String... path) { if (path == null || path.length == 0) { throw new IllegalArgumentException("Path to a tree item cannot be null"); } int index = 0; Iterator<TreeItem> nestedItemsIterator = iterator; List<TreeItem> resultItems = new ArrayList<TreeItem>(); while (index < path.length) { List<TreeItem> nestedItems = new ArrayList<TreeItem>(); while (nestedItemsIterator.hasNext()) { TreeItem item = nestedItemsIterator.next(); if (getNonStyledText(item).equals(path[index])) { if (index == path.length - 1) { resultItems.add(item); } else { nestedItems.addAll(item.getItems()); } } } nestedItemsIterator = nestedItems.iterator(); index++; } if (resultItems.size() == 0) { throw new JFaceLayerException("There is no tree item with path " + Arrays.toString(path)); } return resultItems; }
Source:
<code>public void selectionRangeUpdated(TmfSelectionRangeUpdatedSignal signal) { if (signal.getSource() == this || TmfTraceManager.getInstance().getActiveTrace() == null) { return; } if (fFollowTimeSelection) { getContentProvider().setTimeRange(new TmfTimeRange(signal.getBeginTime(), signal.getEndTime())); final TableViewer tableViewer = getTableViewer(); <START> if (!tableViewer.getTable().isDisposed()) { <END> tableViewer.setInput(tableViewer.getInput()); final LatencyContentProvider latencyContentProvider = (LatencyContentProvider) tableViewer.getContentProvider(); tableViewer.setItemCount(latencyContentProvider.getSegmentCount()); } } else { } }</code><technical_language>reset top index 0 set selection empty setting new input, do in updateModel(). This fix exceptions in content provider</technical_language>

Target:
public void selectionRangeUpdated(TmfSelectionRangeUpdatedSignal signal) { if (signal.getSource() == this || TmfTraceManager.getInstance().getActiveTrace() == null) { return; } if (fFollowTimeSelection) { getContentProvider().setTimeRange(new TmfTimeRange(signal.getBeginTime(), signal.getEndTime())); final TableViewer tableViewer = getTableViewer(); if (!tableViewer.getTable().isDisposed()) { tableViewer.setSelection(null); tableViewer.setInput(tableViewer.getInput()); final LatencyContentProvider latencyContentProvider = (LatencyContentProvider) tableViewer.getContentProvider(); tableViewer.setItemCount(latencyContentProvider.getSegmentCount()); } } else { } }
Source:
<code>ByteBuf buffer() throws IOException { if (buf == null) { buf = Netty4Utils.toByteBuf(context.get()); context = null; <START> } <END> return buf; }</code><technical_language>assert context == null here</technical_language>

Target:
ByteBuf buffer() throws IOException { if (buf == null) { buf = Netty4Utils.toByteBuf(context.get()); context = null; } assert context == null; return buf; }
Source:
<code>SonarLintJob(Map<Module, Collection<VirtualFile>> files, TriggerType trigger, @Nullable AnalysisCallback callback) { this.callback = callback; Preconditions.checkNotNull(files); Preconditions.checkNotNull(trigger); <START> Preconditions.checkArgument(!files.isEmpty(), "List of filesPerModule is empty"); <END> Map<Module, Collection<VirtualFile>> fileMap = new HashMap<>(); fileMap.putAll(files); this.files = Collections.unmodifiableMap(fileMap); this.trigger = trigger; this.creationTime = System.currentTimeMillis(); }</code><technical_language>unintended replace</technical_language>

Target:
SonarLintJob(Map<Module, Collection<VirtualFile>> files, TriggerType trigger, @Nullable AnalysisCallback callback) { this.callback = callback; Preconditions.checkNotNull(files); Preconditions.checkNotNull(trigger); Preconditions.checkArgument(!files.isEmpty(), "List of files is empty"); Map<Module, Collection<VirtualFile>> fileMap = new HashMap<>(); fileMap.putAll(files); this.files = Collections.unmodifiableMap(fileMap); this.trigger = trigger; this.creationTime = System.currentTimeMillis(); }
Source:
<code>public void execute() { if (Strings.isNullOrEmpty(getRoleName())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Empty role name provided"); } if (getRoleType() == null || getRoleType() == RoleType.Unknown) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Invalid role type provided"); } CallContext.current().setEventDetails("Role: " + getRoleName() + ", type:" + getRoleType() + ", description: " + getRoleDescription()); Role role = roleService.createRole(getRoleName(), getRoleType(), getRoleDescription()); if (role == null) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create role"); } RoleResponse response = new RoleResponse(); response.setId(role.getUuid()); response.setRoleName(role.getName()); response.setRoleType(role.getRoleType()); response.setResponseName(getCommandName()); response.setObjectName("role"); setResponseObject(response); <START> } <END></code><technical_language>in other api command classes this is done in ApiResponseHelper. sense do for readability factor out in a private method</technical_language>

Target:
public void execute() { CallContext.current().setEventDetails("Role: " + getRoleName() + ", type:" + getRoleType() + ", description: " + getRoleDescription()); final Role role = roleService.createRole(getRoleName(), getRoleType(), getRoleDescription()); if (role == null) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create role"); } setupResponse(role); }
Source:
<code>public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); <START> final Resource[] resources = new Resource[] { new ClassPathResource("schemas/common.xsd"), <END> new ClassPathResource("schemas/devicemanagement.xsd"), }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }</code><technical_language>a constant for this path</technical_language>

Target:
public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); final Resource[] resources = new Resource[] { new ClassPathResource(COMMON_XSD_PATH), new ClassPathResource(DEVICE_MANAGEMENT_XSD_PATH), }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }
Source:
<code>public List<HtmlData> getCustomActionUrls(BusinessObject businessObject, List pkNames) { LOG.debug("getCustomActionUrls, entering"); List<HtmlData> anchorHtmlDataList = new ArrayList<HtmlData>(); if (canInitAward()) { <START> anchorHtmlDataList.add(getUrlData(businessObject, KRADConstants.MAINTENANCE_EDIT_METHOD_TO_CALL, pkNames)); <END> if (allowsMaintenanceNewOrCopyAction()) { anchorHtmlDataList.add(getUrlData(businessObject, KRADConstants.MAINTENANCE_COPY_METHOD_TO_CALL, pkNames)); } } if (canViewInvoiceLink() && getAccountsReceivableModuleBillingService().isContractsGrantsBillingEnhancementActive()) { AnchorHtmlData invoiceUrl = getInvoicesLookupUrl(businessObject); anchorHtmlDataList.add(invoiceUrl); } return anchorHtmlDataList; }</code><technical_language>want place this line "if" block checks "allowsMaintenanceEditAction" method, in of superclasses in hierarchy</technical_language>

Target:
public List<HtmlData> getCustomActionUrls(BusinessObject businessObject, List pkNames) { LOG.debug("getCustomActionUrls, entering"); List<HtmlData> anchorHtmlDataList = new ArrayList<HtmlData>(); if (canInitAward() && allowsMaintenanceEditAction(businessObject)) { anchorHtmlDataList.add(getUrlData(businessObject, KRADConstants.MAINTENANCE_EDIT_METHOD_TO_CALL, pkNames)); if (allowsMaintenanceNewOrCopyAction()) { anchorHtmlDataList.add(getUrlData(businessObject, KRADConstants.MAINTENANCE_COPY_METHOD_TO_CALL, pkNames)); } } if (canViewInvoiceLink() && getAccountsReceivableModuleBillingService().isContractsGrantsBillingEnhancementActive()) { AnchorHtmlData invoiceUrl = getInvoicesLookupUrl(businessObject); anchorHtmlDataList.add(invoiceUrl); } return anchorHtmlDataList; }
Source:
<code>public String[] getFilePaths(RepoObject repoObject) throws RepoException { String paths[] = null; if (!hasXReproxy()) return new String[0]; <START> String path = new String(reproxyBaseUrl + "/" + repoObject.getBucketName() + "/" + repoObject.getChecksum().substring(0, 2) + "/" + repoObject.getChecksum()); <END> if(path != null){ paths = new String[]{path}; } return paths; }</code><technical_language>new String</technical_language>

Target:
public String[] getFilePaths(RepoObject repoObject) throws RepoException { String path = null; try { if (!hasXReproxy()) return new String[0]; path = reproxyBaseUrl + "/" + repoObject.getBucketName() + "/" + repoObject.getChecksum().substring(0, 2) + "/" + repoObject.getChecksum(); if (path == null) { throw new RepoException(RepoException.Type.ObjectFilePathMissing); } }catch (Exception e){ throw new RepoException(e); } return new String[]{path}; }
Source:
<code>ContentBootstrapController contentBootstrapController() { return ContentBootstrapController.builder() .withRead(persistence.legacyContentResolver()) .withContentLister(persistence.legacyContentLister()) .withWrite(persistence.nullMessageSendingContentStore()) .withContentIndex(search.equivContentIndex()) .withEquivalenceMigrator(explicitEquivalenceMigrator) <START> .withMaxSourceBootstrapThreads(NUMBER_OF_SOURCE_BOOTSTRAP_TRHEADS) <END> .withProgressStore(progressStore()) .withMetrics(metrics) .withEquivalentContentStore(persistence.nullMessageSendingEquivalentContentStore()) .withEquivalenceGraphStore(persistence.nullMessageSendingEquivalenceGraphStore()) .withContentStore(persistence.contentStore()) .withNeo4JContentStore(persistence.neo4jContentStore()) .build(); }</code><technical_language>rename TRHEADS while in</technical_language>

Target:
ContentBootstrapController contentBootstrapController() { return ContentBootstrapController.builder() .withRead(persistence.legacyContentResolver()) .withContentLister(persistence.legacyContentLister()) .withWrite(persistence.nullMessageSendingContentStore()) .withContentIndex(search.equivContentIndex()) .withEquivalenceMigrator(explicitEquivalenceMigrator) .withMaxSourceBootstrapThreads(NUMBER_OF_SOURCE_BOOTSTRAP_THREADS) .withProgressStore(progressStore()) .withMetrics(metrics) .withEquivalentContentStore(persistence.nullMessageSendingEquivalentContentStore()) .withEquivalenceGraphStore(persistence.nullMessageSendingEquivalenceGraphStore()) .withContentStore(persistence.contentStore()) .withNeo4JContentStore(persistence.neo4jContentStore()) .withLegacyResolver(persistence.legacyContentResolver()) .withAstyanaxStore(persistence.astyanaxContentStore()) .withReplayConsumerFactory(worker -> workers.bootstrapQueueFactory() .createConsumer( worker, new EntityUpdatedLegacyMessageSerializer(), contentChanges, "ReplayContentBootstrap" ) .withConsumerSystem(consumerSystem) .withDefaultConsumers(contentChangesReplayNumOfConsumers) .withMaxConsumers(contentChangesReplayNumOfConsumers) .withPersistentRetryPolicy(persistence.databasedWriteMongo()) .withMetricRegistry(metricsModule.metrics()) .startFrom(StartPoint.BEGINNING) .build() ).build(); }
Source:
<code><START> private static @Nullable String findVersion(Map<Interval, String> versions, Interval interval) <END> { return versions.entrySet().stream() .filter(entry -> entry.getKey().contains(interval)) .map(Entry::getValue) .findFirst() .orElse(null); }</code><technical_language>nit: add annotation method</technical_language>

Target:
private static String findVersion(Map<Interval, String> versions, Interval interval) { return versions.entrySet().stream() .filter(entry -> entry.getKey().contains(interval)) .map(Entry::getValue) .findFirst() .orElse(null); }
Source:
<code>public void testHlsSampleAes_bbb_unmuxed_1500k() throws Exception { if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) { return; } MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); for (MediaCodecInfo info : mcl.getCodecInfos()) { if (info.isEncoder() || info.getName().toLowerCase().startsWith("omx.google.")) { continue; } try { CodecCapabilities caps = info.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_AVC); VideoCapabilities vcaps = caps.getVideoCapabilities(); if (vcaps.areSizeAndRateSupported(1920 ,1080, 30)) { playLiveVideoTest( "<LINK_0>" + "bbb_1080p_30fps_11min/unmuxed_1500k/prog_index.m3u8", 60 * 1000); } else { playLiveVideoTest( "<LINK_1>" + "bbb_480p_30fps/unmuxed_1000k/bbb_h264_main_480p_30fps_1000.m3u8", <START> 10 * <END> 1000); } } catch (IllegalArgumentException e) { } } }</code><technical_language>This stay 60, play clear lead play encrypted content</technical_language>

Target:
public void testHlsSampleAes_bbb_unmuxed_1500k() throws Exception { if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) { return; } MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); for (MediaCodecInfo info : mcl.getCodecInfos()) { if (info.isEncoder() || info.getName().toLowerCase().startsWith("omx.google.")) { continue; } try { CodecCapabilities caps = info.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_AVC); VideoCapabilities vcaps = caps.getVideoCapabilities(); if (vcaps.areSizeAndRateSupported(1920 ,1080, 30)) { playLiveVideoTest( "<LINK_0>" + "bbb_1080p_30fps_11min/unmuxed_1500k/prog_index.m3u8", 60 * 1000); } else { playLiveVideoTest( "<LINK_1>" + "bbb_480p_30fps/unmuxed_1000k/bbb_h264_main_480p_30fps_1000.m3u8", 60 * 1000); } } catch (IllegalArgumentException e) { } } }
Source:
<code>private static ExtensionElement checkForIllegalPayloadsAndPossiblyThrow(ExtensionElement payloadItem) { <START> for (QName qn : BLACKLISTED_QNAMES) { <END> if (qn.equals(payloadItem.getQName())) { throw new IllegalArgumentException("Element identified by " + payloadItem.getQName().toString() + " is not allowed as payload item. See <LINK_0>"); } } for (String ns : BLACKLISTED_NAMESPACES) { if (ns.equals(payloadItem.getNamespace())) { throw new IllegalArgumentException("Elements of namespace '" + payloadItem.getNamespace() + "' are not allowed as payload items. See <LINK_0>"); } } return payloadItem; }</code><technical_language>simply contains() here</technical_language>

Target:
private static ExtensionElement checkForIllegalPayloadsAndPossiblyThrow(ExtensionElement payloadItem) { QName qName = payloadItem.getQName(); if (BLACKLISTED_QNAMES.contains(qName)) { throw new IllegalArgumentException("Element identified by " + qName + " is not allowed as payload item. See <LINK_0>"); } String namespace = payloadItem.getNamespace(); if (BLACKLISTED_NAMESPACES.contains(namespace)) { throw new IllegalArgumentException("Elements of namespace '" + namespace + "' are not allowed as payload items. See <LINK_0>"); } return payloadItem; }
Source:
<code>public TikaTextExtractor(Content content) { this.content = content; if(content instanceof AbstractFile) { parser = new AutoDetectParser(new Detector() { @Override public MediaType detect(InputStream in, Metadata mtdt) throws IOException { <START> return MediaType.parse(AbstractFile.class.cast(content).getMIMEType()); <END> } }); } else { parser = new AutoDetectParser(); } }</code><technical_language>if mime type calculated yet</technical_language>

Target:
public TikaTextExtractor(Content content) { this.content = content; parser = new AutoDetectParser(); if (content instanceof AbstractFile) { AbstractFile file = (AbstractFile) content; if (file.getMIMEType() != null && !file.getMIMEType().isEmpty()) { parser.setDetector((InputStream inStream, Metadata metaData) -> MediaType.parse(file.getMIMEType())); } } }
Source:
<code>public void waitTextNotPresentIntoRightEditor(String expText) { <START> webDriverWaitFactory <END> .get() .until( (ExpectedCondition<Boolean>) webDriver -> !(getTextFromRightEditorCompare().contains(expText))); }</code><technical_language>rewrite code SeleniumWebDriverHelper class</technical_language>

Target:
public void waitTextNotPresentIntoRightEditor(String expText) { seleniumWebDriverHelper.waitTextIsNotPresented(rightCompareEditor, expText); }
Source:
<code>public final void fetchesName() throws Exception { final Content content = Mockito.mock(Content.class); Mockito.doReturn( Json.createObjectBuilder() .add("name", "this is some name") .build() ).when(content).json(); MatcherAssert.assertThat( new Content.Smart(content).name(), <START> Matchers.notNullValue() <END> ); }</code><technical_language>again, compare "this is some name"</technical_language>

Target:
public final void fetchesName() throws Exception { final Content content = Mockito.mock(Content.class); final String prop = "this is some name"; Mockito.doReturn( Json.createObjectBuilder() .add("name", prop) .build() ).when(content).json(); MatcherAssert.assertThat( new Content.Smart(content).name(), Matchers.is(prop) ); }
Source:
<code>private void onUpdateRepairOutput(CallbackInfo ci) { ItemStack itemstack = this.inputSlots.getStackInSlot(0); ItemStack itemstack2 = this.inputSlots.getStackInSlot(1); ItemStack result = this.outputSlot.getStackInSlot(0); UpdateAnvilEvent event = SpongeCommonEventFactory.callUpdateAnvilEvent((ContainerRepair) (Object) this, itemstack, itemstack2, result, this.repairedItemName, this.maximumCost, this.materialCost); ItemStackSnapshot finalItem = event.getItem().getFinal(); <START> if (event.isCancelled() || finalItem.isEmpty()) { <END> this.outputSlot.setInventorySlotContents(0, ItemStack.EMPTY); this.maximumCost = 0; this.materialCost = 0; this.detectAndSendChanges(); return; } this.outputSlot.setInventorySlotContents(0, ItemStackUtil.fromSnapshotToNative(event.getItem().getFinal())); this.maximumCost = event.getCosts().getFinal().getLevelCost(); this.materialCost = event.getCosts().getFinal().getMaterialCost(); this.listeners.forEach(l -> l.sendWindowProperty(((ContainerRepair)(Object) this), 0, this.maximumCost)); this.detectAndSendChanges(); }</code><technical_language>do a check if event is listened ShouldFire</technical_language>

Target:
private void onUpdateRepairOutput(CallbackInfo ci) { if (!ShouldFire.UPDATE_ANVIL_EVENT) { return; } ItemStack itemstack = this.inputSlots.getStackInSlot(0); ItemStack itemstack2 = this.inputSlots.getStackInSlot(1); ItemStack result = this.outputSlot.getStackInSlot(0); UpdateAnvilEvent event = SpongeCommonEventFactory.callUpdateAnvilEvent((ContainerRepair) (Object) this, itemstack, itemstack2, result, this.repairedItemName, this.maximumCost, this.materialCost); ItemStackSnapshot finalItem = event.getResult().getFinal(); if (event.isCancelled() || finalItem.isEmpty()) { this.outputSlot.setInventorySlotContents(0, ItemStack.EMPTY); this.maximumCost = 0; this.materialCost = 0; this.detectAndSendChanges(); return; } this.outputSlot.setInventorySlotContents(0, ItemStackUtil.fromSnapshotToNative(event.getResult().getFinal())); this.maximumCost = event.getCosts().getFinal().getLevelCost(); this.materialCost = event.getCosts().getFinal().getMaterialCost(); this.listeners.forEach(l -> l.sendWindowProperty(((ContainerRepair)(Object) this), 0, this.maximumCost)); this.detectAndSendChanges(); }
Source:
<code>private void onUpdateMsg(final AvroElasticMemoryMessage msg) { try (final TraceScope onUpdateMsgScope = Trace.startSpan(ON_UPDATE_MSG, HTraceUtils.fromAvro(msg.getTraceInfo()))) { final String operationId = msg.getOperationId().toString(); final UpdateResult updateResult; final Update update = pendingUpdates.remove(operationId); if (update == null) { LOG.log(Level.WARNING, "The update with id {0} seems already handled.", operationId); return; } switch (update.getType()) { case ADD: <START> final Add add = (Add) update; <END> add.apply(memoryStore); updateResult = UpdateResult.RECEIVER_UPDATED; break; case REMOVE: final Remove remove = (Remove) update; remove.apply(memoryStore); updateResult = UpdateResult.SUCCESS; break; default: throw new RuntimeException("Undefined Message type of Update: " + update); } sender.get().sendUpdateAckMsg(operationId, updateResult, TraceInfo.fromSpan(onUpdateMsgScope.getSpan())); } }</code><technical_language>cast? apply part of Update interface</technical_language>

Target:
private void onUpdateMsg(final AvroElasticMemoryMessage msg) { try (final TraceScope onUpdateMsgScope = Trace.startSpan(ON_UPDATE_MSG, HTraceUtils.fromAvro(msg.getTraceInfo()))) { final String operationId = msg.getOperationId().toString(); final UpdateResult updateResult; final Update update = pendingUpdates.remove(operationId); if (update == null) { LOG.log(Level.WARNING, "The update with id {0} seems already handled.", operationId); return; } switch (update.getType()) { case ADD: update.apply(memoryStore); updateResult = UpdateResult.RECEIVER_UPDATED; break; case REMOVE: update.apply(memoryStore); movingRanges.removeAll(update.getRanges()); updateResult = UpdateResult.SENDER_UPDATED; break; default: throw new RuntimeException("Undefined Message type of Update: " + update); } sender.get().sendUpdateAckMsg(operationId, updateResult, TraceInfo.fromSpan(onUpdateMsgScope.getSpan())); } }