auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> ConfigurationParser() throws IOException, SAXException, JAXBException, ParserConfigurationException, TransformerConfigurationException { <END> serviceCreationConfigurationParser = ConfigurationParser.<CacheManagerServiceConfigurationParser<?>>stream( libraryServiceLoaderFor(CacheManagerServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheManagerServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceCreationConfigurationParser::new)); serviceConfigurationParser = ConfigurationParser.<CacheServiceConfigurationParser<?>>stream( libraryServiceLoaderFor(CacheServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceConfigurationParser::new)); resourceConfigurationParser = stream(libraryServiceLoaderFor(CacheResourceConfigurationParser.class)) .flatMap(p -> p.getResourceTypes().stream().map(t -> new AbstractMap.SimpleImmutableEntry<>(t, p))) .collect(collectingAndThen(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a.getClass().isInstance(b) ? b : a), m -> new ResourceConfigurationParser(new HashSet<>(m.values())))); schema = discoverSchema(new StreamSource(CORE_SCHEMA_URL.openStream())); documentBuilder = documentBuilder(schema); }</code><technical_language>TransformerConfigurationException is thrown. reason retain it</technical_language>

Target:
ConfigurationParser() throws IOException, SAXException, JAXBException, ParserConfigurationException { serviceCreationConfigurationParser = ConfigurationParser.<CacheManagerServiceConfigurationParser<?>>stream( libraryServiceLoaderFor(CacheManagerServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheManagerServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceCreationConfigurationParser::new)); serviceConfigurationParser = ConfigurationParser.<CacheServiceConfigurationParser<?>>stream( libraryServiceLoaderFor(CacheServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceConfigurationParser::new)); resourceConfigurationParser = stream(libraryServiceLoaderFor(CacheResourceConfigurationParser.class)) .flatMap(p -> p.getResourceTypes().stream().map(t -> new AbstractMap.SimpleImmutableEntry<>(t, p))) .collect(collectingAndThen(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a.getClass().isInstance(b) ? b : a), m -> new ResourceConfigurationParser(new HashSet<>(m.values())))); schema = discoverSchema(new StreamSource(CORE_SCHEMA_URL.openStream())); documentBuilder = documentBuilder(schema); }
Source:
<code>public final SPromise toFarRefWithResultPromise(final Object[] args) { Actor owner = EventualMessage.getActorCurrentMessageIsExecutionOn(); <START> SPromise result = SPromise.createPromise(owner, false, false, false); <END> SResolver resolver = SPromise.createResolver(result, "eventualSend:", selector); sendDirectMessage(args, owner, resolver); return result; }</code><technical_language>flags similar flags passed messages. some of overlap removed? feels is redundancy problems road</technical_language>

Target:
public final SPromise toFarRefWithResultPromise(final Object[] args) { Actor owner = EventualMessage.getActorCurrentMessageIsExecutionOn(); SPromise result = SPromise.createPromise(owner, promiseResolutionBreakpoint.executeCheckIsSetAndEnabled(), false, false); SResolver resolver = SPromise.createResolver(result); sendDirectMessage(args, owner, resolver); return result; }
Source:
<code>public void hopperOnBrew(InventoryMoveItemEvent e) { <START> if (e.getDestination().getType().equals(InventoryType.BREWING)) { <END> if (isUnallowed(SlimefunItem.getByItem(e.getItem()))) { e.setCancelled(true); } } }</code><technical_language>Enums compared ==, .equals()</technical_language>

Target:
public void hopperOnBrew(InventoryMoveItemEvent e) { if (e.getDestination().getType() == InventoryType.BREWING && isUnallowed(e.getItem())) { e.setCancelled(true); } }
Source:
<code>public void adminUserCanDeleteBoard() { ForumBoardPage forumBoard = new ForumBoardPage(); first = forumBoard.createNew(User.USER_ADMIN_FORUM); second = forumBoard.createNew(User.USER_ADMIN_FORUM); ForumPage forumMainPage = new ForumPage(); forumMainPage.openForumMainPage(wikiURL); ForumManageBoardsPageObject manageForum = forumMainPage.clickManageBoardsButton(); description = PageContent.FORUM_DESCRIPTION_PREFIX + manageForum.getTimeStamp(); manageForum.verifyForumExists(first, wikiURL); <START> manageForum.verifyForumExists(second, wikiURL); <END> manageForum.deleteForum(second, first); manageForum.verifyForumNotExists(second, wikiURL); }</code><technical_language>assertions in (Page Object side Tests side) debugging defects more difficult. refactor Tests Page Objects include assertions tests side. for example: Assert.assertTrue(manageForum.ForumExists() etc</technical_language>

Target:
public void adminUserCanDeleteBoard() { ForumBoardPage forumBoard = new ForumBoardPage(); first = forumBoard.createNew(User.USER_ADMIN_FORUM); second = forumBoard.createNew(User.USER_ADMIN_FORUM); ForumPage forumMainPage = new ForumPage(); forumMainPage.openForumMainPage(wikiURL); ForumManageBoardsPageObject manageForum = forumMainPage.clickManageBoardsButton(); description = PageContent.FORUM_DESCRIPTION_PREFIX + manageForum.getTimeStamp(); Assert.assertTrue(manageForum.verifyForumExists(first, wikiURL)); Assert.assertTrue(manageForum.verifyForumExists(second, wikiURL)); manageForum.deleteForum(second, first); Assert.assertTrue(manageForum.verifyForumNotExists(second, wikiURL)); }
Source:
<code>public static Literal toLiteral(Object value) { if (value instanceof Boolean) { return new BooleanLiteral(((Boolean) value).booleanValue()); } else if (value instanceof Calendar) { return new DateLiteral(toZonedDateTime((Calendar) value)); } else if (value instanceof Date) { return new DateLiteral(toZonedDateTime((Date) value)); <START> } else if (value instanceof Temporal) { <END> return new DateLiteral(ZonedDateTime.from((Temporal) value)); } else if (value instanceof ZonedDateTime) { return new DateLiteral((ZonedDateTime) value); } else if (value instanceof Double) { return new DoubleLiteral((Double) value); } else if (value instanceof Float) { return new DoubleLiteral((Float) value); } else if (value instanceof Integer) { return new IntegerLiteral((Integer) value); } else if (value instanceof Long) { return new IntegerLiteral((Long) value); } else if (value instanceof String) { return new StringLiteral((String) value); } throw new NuxeoException("Unknown type to convert to literal, value=" + value); }</code><technical_language>This condition is reached, ZonedDateTime implements Temporal</technical_language>

Target:
public static Literal toLiteral(Object value) { if (value instanceof Boolean) { return new BooleanLiteral(((Boolean) value).booleanValue()); } else if (value instanceof Calendar) { return new DateLiteral(toZonedDateTime((Calendar) value)); } else if (value instanceof Date) { return new DateLiteral(toZonedDateTime((Date) value)); } else if (value instanceof ZonedDateTime) { return new DateLiteral((ZonedDateTime) value); } else if (value instanceof Temporal) { return new DateLiteral(ZonedDateTime.from((Temporal) value)); } else if (value instanceof Double) { return new DoubleLiteral((Double) value); } else if (value instanceof Float) { return new DoubleLiteral((Float) value); } else if (value instanceof Integer) { return new IntegerLiteral((Integer) value); } else if (value instanceof Long) { return new IntegerLiteral((Long) value); } else if (value instanceof String) { return new StringLiteral((String) value); } throw new NuxeoException("Unknown type to convert to literal, value=" + value); }
Source:
<code>public TableRegistry(CorfuRuntime runtime) { this.runtime = runtime; this.classMap = new ConcurrentHashMap<>(); this.tableMap = new ConcurrentHashMap<>(); <START> this.protobufSerializer = new ProtobufSerializer((byte) 25, classMap); <END> Serializers.registerSerializer(this.protobufSerializer); this.registryTable = this.runtime.getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<TableName, CorfuRecord<TableDescriptors, Message>>>() { }) .setStreamName(getFullyQualifiedTableName(CORFU_SYSTEM_NAMESPACE, REGISTRY_TABLE_NAME)) .setSerializer(this.protobufSerializer) .open(); addTypeToClassMap(TableName.getDefaultInstance()); addTypeToClassMap(TableDescriptors.getDefaultInstance()); registerTable(CORFU_SYSTEM_NAMESPACE, REGISTRY_TABLE_NAME, TableName.getDescriptor().toProto(), TableDescriptors.getDescriptor().toProto()); }</code><technical_language>pass CorfuRuntime everywhere, a good idea</technical_language>

Target:
public TableRegistry(CorfuRuntime runtime) { this.runtime = runtime; this.classMap = new ConcurrentHashMap<>(); this.tableMap = new ConcurrentHashMap<>(); this.protobufSerializer = new ProtobufSerializer(PROTOBUF_SERIALIZER_CODE, classMap); Serializers.registerSerializer(this.protobufSerializer); this.registryTable = this.runtime.getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<TableName, CorfuRecord<TableDescriptors, Message>>>() { }) .setStreamName(getFullyQualifiedTableName(CORFU_SYSTEM_NAMESPACE, REGISTRY_TABLE_NAME)) .setSerializer(this.protobufSerializer) .open(); addTypeToClassMap(TableName.getDefaultInstance()); addTypeToClassMap(TableDescriptors.getDefaultInstance()); try { registerTable(CORFU_SYSTEM_NAMESPACE, REGISTRY_TABLE_NAME, TableName.class, TableDescriptors.class, null); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } }
Source:
<code>public PsAll(final List<Pass> pass, final int identity) { <START> super(); <END> this.all = pass; this.index = identity; }</code><technical_language>@lautarobock this is for? is super class</technical_language>

Target:
public PsAll(final List<Pass> pass, final int identity) { this.all = pass; this.index = identity; }
Source:
<code>private void markExpiredCommandsAsFailure() { long maxTime = DateTime.getNow() .addMinutes((-1) * Config.<Integer>getValue(ConfigValues.CoCoCommandLifeInMinutes)).getTime(); <START> Iterator<Entry<Guid, CommandContainer>> iterator = cmdCallbackMap.entrySet().iterator(); <END> while (iterator.hasNext()) { Entry<Guid, CommandContainer> entry = iterator.next(); List<Guid> childCmdIds = coco.getChildCommandIds(entry.getKey()); if (childCmdIds.isEmpty()) { markExpiredCommandAsFailure(entry.getKey(), maxTime); } else { for (Guid childId : childCmdIds) { markExpiredCommandAsFailure(childId, maxTime); } } } }</code><technical_language>anonymous iterator ? for (Entry<Guid, CommandContainer> entry cmdCallbackMap.entrySet()) { ... }</technical_language>

Target:
private void markExpiredCommandsAsFailure() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, (-1) * Config.<Integer>getValue(ConfigValues.CoCoCommandLifeInMinutes)); long maxTime = cal.getTime().getTime(); for (Entry<Guid, CommandContainer> entry : cmdCallbackMap.entrySet()) { List<Guid> childCmdIds = coco.getChildCommandIds(entry.getKey()); if (childCmdIds.isEmpty()) { markExpiredCommandAsFailure(entry.getKey(), maxTime); } else { for (Guid childId : childCmdIds) { markExpiredCommandAsFailure(childId, maxTime); } } } }
Source:
<code>public AuditLogType <START> getAuditLogTypeValue() <END> { return getSucceeded() ? AuditLogType.NETWORK_UPDATE_NETWORK : AuditLogType.NETWORK_UPDATE_NETWORK_FAILED; }</code><technical_language>Do need update this method Command's status execution part (to prevent printing exact message CommandBase.logCommand() )</technical_language>

Target:
public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: return getSucceeded() ? AuditLogType.NETWORK_UPDATE_NETWORK_STARTED : AuditLogType.NETWORK_UPDATE_NETWORK_FAILED; case END_FAILURE: return hasChildCommands() ? AuditLogType.UPDATE_NETWORK_ON_HOSTS_FAILED : super.getAuditLogTypeValue(); case END_SUCCESS: return AuditLogType.NETWORK_UPDATE_NETWORK_FINISHED; } return super.getAuditLogTypeValue(); }
Source:
<code>private List<QueryStateInfo> getAggregatedRunningQueriesInfo() { synchronized (root) { if (!subGroups.isEmpty()) { return subGroups.values().stream() .map(InternalResourceGroup::getAggregatedRunningQueriesInfo) .flatMap(List::stream) .collect(toImmutableList()); } List<ResourceGroupInfo> pathToRoot = getPathToRoot(); return runningQueries.stream() .map(QueryExecution::getQueryInfo) <START> .map(queryInfo -> createQueryStateInfo(queryInfo, Optional.of(id), Optional.of(pathToRoot))) <END> .collect(toImmutableList()); } }</code><technical_language>reverse logic? I thought write termination condition first, recursion</technical_language>

Target:
private List<QueryStateInfo> getAggregatedRunningQueriesInfo() { synchronized (root) { if (subGroups.isEmpty()) { List<ResourceGroupInfo> pathToRoot = getPathToRoot(); return runningQueries.stream() .map(QueryExecution::getQueryInfo) .map(queryInfo -> createQueryStateInfo(queryInfo, Optional.of(id), Optional.of(pathToRoot))) .collect(toImmutableList()); } return subGroups.values().stream() .map(InternalResourceGroup::getAggregatedRunningQueriesInfo) .flatMap(List::stream) .collect(toImmutableList()); } }
Source:
<code>public void setUidHash(String uidHash) { <START> throw new UnsupportedOperationException("Do not support set UidHash for SinkTransformation."); <END> }</code><technical_language>suggestion throw new UnsupportedOperationException("Setting a UidHash is supported for SinkTransformation.");</technical_language>

Target:
public void setUidHash(String uidHash) { throw new UnsupportedOperationException("Setting a UidHash is not supported for SinkTransformation."); }
Source:
<code>private static void saveMetacards(CatalogFramework framework, List<Metacard> metacards) { Subject userSubject = SECURITY.getSubject("dummyUser", "dummyPassword"); userSubject.execute( () -> { try { framework.create(new CreateRequestImpl(metacards)).getCreatedMetacards(); <START> } catch (IngestException e) { <END> LOGGER.warn("Unable to create metacard under this user", e); } catch (SourceUnavailableException e) { LOGGER.warn("Unable to create metacard under this user", e); } }); }</code><technical_language>This condensed catch block -> catch (IngestException | SourceUnavailableException). want consider logging user</technical_language>

Target:
private static void saveMetacards(CatalogFramework framework, List<Metacard> metacards) { SECURITY.runAsAdmin( () -> { try { return SECURITY.runWithSubjectOrElevate( () -> framework.create(new CreateRequestImpl(metacards)).getCreatedMetacards()); } catch (SecurityServiceException | InvocationTargetException e) { LOGGER.warn( "Can't create metacard for system search template, was unable to elevate privileges", e); } return null; }); }
Source:
<code>static public void main(String[] args) throws IOException { if (args.length < 3) { <START> System.err.println("This executable requires four arguments:\n" <END> + " OntonotesTreebankReader <OntoNotes Directory> <language> <output_directory>"); System.exit(-1); } String topdir = args[0]; String outputdir = args[2]; OntonotesNamedEntityReader otr = new OntonotesNamedEntityReader(topdir, args[1]); int count = 0; final boolean producejson = false; while (otr.hasNext()) { XmlTextAnnotation xta = otr.next(); String path = otr.currentfile; if (producejson) { try { String json = SerializationHelper.serializeToJson(xta.getTextAnnotation()); String outfile = otr.currentfile.replace(topdir, args[2]); File outputfile = new File(outfile); outputfile.getParentFile().mkdirs(); try (PrintWriter out = new PrintWriter(outputfile)) { out.print(json); } } catch (Throwable t) { System.out.println(otr.currentfile+" produced the incorrect offset."); } } else { TextAnnotation ta = xta.getTextAnnotation(); path = outputdir+path.substring(topdir.length()); path += ".conll"; System.out.println(count+":"+path); CoNLL2002Writer.writeViewInCoNLL2003Format(ta.getView(ViewNames.NER_ONTONOTES), ta, path); } count++; if ((count % 10) == 0) System.out.println("Completed "+count+" of "+otr.filelist.size()); } System.out.println("Processed a total of "+count+" of "+otr.filelist.size()+" treebanks."); }</code><technical_language>message "three arguments", four..</technical_language>

Target:
static public void main(String[] args) throws IOException { if (args.length < 3) { System.err.println("This executable requires three arguments:\n" + " OntonotesTreebankReader <OntoNotes Directory> <language> <output_directory>"); System.exit(-1); } String topdir = args[0]; String outputdir = args[2]; OntonotesNamedEntityReader otr = new OntonotesNamedEntityReader(topdir, args[1]); int count = 0; final boolean producejson = false; while (otr.hasNext()) { XmlTextAnnotation xta = otr.next(); String path = otr.currentfile; if (producejson) { try { String json = SerializationHelper.serializeToJson(xta.getTextAnnotation()); String outfile = otr.currentfile.replace(topdir, args[2]); File outputfile = new File(outfile); outputfile.getParentFile().mkdirs(); try (PrintWriter out = new PrintWriter(outputfile)) { out.print(json); } } catch (Throwable t) { System.out.println(otr.currentfile+" produced the incorrect offset."); } } else { TextAnnotation ta = xta.getTextAnnotation(); path = outputdir+path.substring(topdir.length()); path += ".conll"; System.out.println(count+":"+path); CoNLL2002Writer.writeViewInCoNLL2003Format(ta.getView(ViewNames.NER_ONTONOTES), ta, path); } count++; if ((count % 10) == 0) System.out.println("Completed "+count+" of "+otr.filelist.size()); } System.out.println(otr.generateReport()); }
Source:
<code>public String getFullRequestURL() { final PublicAddress publicAddress = context.get(PublicAddress.class); <START> return publicAddress.getAddress(context).toString() + context.getRequest().getUri(); <END> }</code><technical_language>currently a helper method in this class for public address. I this line become: return getAddress().toString() + context.getRequest().getUri();</technical_language>

Target:
public String getFullRequestURL() { return getAddress().toString() + context.getRequest().getUri(); }
Source:
<code>protected void executeCommand() { StoragePoolIsoMap map = loadStoragePoolIsoMap(); changeDomainStatusWithCompensation(map, StorageDomainStatus.Unknown, StorageDomainStatus.Locked, getCompensationContext()); if (shouldPerformOvfUpdate()) { <START> runInternalAction(VdcActionType.ProcessOvfUpdateForStoragePool, new StoragePoolParametersBase(getStoragePoolId()), null); <END> if (ovfOnAnyDomainSupported()) { VdcReturnValueBase tmpRetValue = runInternalActionWithTasksContext(VdcActionType.ProcessOvfUpdateForStorageDomain, createProcessOvfUpdateForDomainParams(), null); getReturnValue().getVdsmTaskIdList().addAll(tmpRetValue.getInternalVdsmTaskIdList()); } } if (getReturnValue().getVdsmTaskIdList().isEmpty()) { setSucceeded(executeDeactivateCommand(true)); } else { setCommandShouldBeLogged(false); setSucceeded(true); } }</code><technical_language>for DC in 3.4 comptability level ProcessOvfUpdateForStoragePool try update OVF storage (on master domain), if fails OVF data completely updated in DB is want here. update command support update of db (and here)</technical_language>

Target:
protected void executeCommand() { StoragePoolIsoMap map = loadStoragePoolIsoMap(); changeDomainStatusWithCompensation(map, StorageDomainStatus.Unknown, StorageDomainStatus.Locked, getCompensationContext()); if (shouldPerformOvfUpdate()) { StoragePoolParametersBase parameters = new StoragePoolParametersBase(getStoragePoolId()); parameters.setShouldOnlyUpdateDB(true); runInternalAction(VdcActionType.ProcessOvfUpdateForStoragePool, parameters, null); if (ovfOnAnyDomainSupported()) { VdcReturnValueBase tmpRetValue = runInternalActionWithTasksContext(VdcActionType.ProcessOvfUpdateForStorageDomain, createProcessOvfUpdateForDomainParams(), null); getReturnValue().getVdsmTaskIdList().addAll(tmpRetValue.getInternalVdsmTaskIdList()); } } if (getReturnValue().getVdsmTaskIdList().isEmpty()) { setSucceeded(executeDeactivateCommand(true)); } else { setCommandShouldBeLogged(false); setSucceeded(true); } }
Source:
<code>public static void main(String[] args) throws Exception { CommandLine cmdLine = new CommandLine(); Config config = cmdLine.loadConfig(cmdLine.parser().parse(args)); <START> ApplicationRunner standaloneEnv = ApplicationRunner.getLocalRunner(config); <END> standaloneEnv.run(new KeyValueStoreExample(), config); }</code><technical_language>Nitpick: update variable names too, elsewhere</technical_language>

Target:
public static void main(String[] args) throws Exception { CommandLine cmdLine = new CommandLine(); Config config = cmdLine.loadConfig(cmdLine.parser().parse(args)); ApplicationRunner localRunner = ApplicationRunner.getLocalRunner(config); localRunner.run(new KeyValueStoreExample(), config); }
Source:
<code>public static String toPath(String path) { String workDir = DfBuildProperties.getInstance().getWorkDir(); try { <START> return new File(workDir, path).getCanonicalPath(); <END> } catch (IOException e) { String msg = "Failed to derived path. workDir=" + workDir + ", path=" + path; throw new IllegalStateException(msg, e); } }</code><technical_language>getCanonicalPath() provides clean path. this method returns absolute path. need confirm logic is problem not..</technical_language>

Target:
public static String toPath(String path) { String workDir = DfBuildProperties.getInstance().getWorkDir(); if (workDir == null || new File(path).isAbsolute()) { return path; } try { return new File(workDir, path).getCanonicalPath(); } catch (IOException e) { String msg = "Failed to derived path. workDir=" + workDir + ", path=" + path; throw new IllegalStateException(msg, e); } }
Source:
<code><START> public void getPostsOfUserShouldReturnEmptyPageInNoBranchesAllowed() { <END> String page = "1"; long branchId = 1L; int pageSize = 50; Branch branch = new Branch("branch",""); branch.setId(branchId); Topic topic = new Topic(); topic.setBranch(branch); Post post = new Post(user, ""); post.setTopic(topic); List<Post> posts = Arrays.asList(post); Page<Post> postsOfUser = new PageImpl<>(posts); when(postDao.getUserPosts(Matchers.<JCUser>any(), Matchers.<PageRequest>any(), Matchers.anyList())) .thenReturn(postsOfUser); when(topicDao.getAllowedBranchesIds(Matchers.<JCUser>any())).thenReturn(Collections.EMPTY_LIST); currentUser.setPageSize(pageSize); Page<Post> actualPostsPage = postService.getPostsOfUser(user, page); assertEquals(actualPostsPage.getSize(), 0); }</code><technical_language>large.. refactored, clear tested</technical_language>

Target:
public void getPostsOfUserShouldReturnEmptyPageInNoBranchesAllowed() { when(postDao.getUserPosts(Matchers.<JCUser>any(), Matchers.<PageRequest>any(), Matchers.anyList())) .thenReturn(getPageWithPost()); when(topicDao.getAllowedBranchesIds(Matchers.<JCUser>any())).thenReturn(Collections.EMPTY_LIST); currentUser.setPageSize(50); Page<Post> actualPostsPage = postService.getPostsOfUser(user, "1"); assertEquals(actualPostsPage.getSize(), 0); }
Source:
<code>private static boolean isSameVariables(DetailAST ast1, DetailAST ast2) { final DetailAST classOrMethodOfAst1 = findClassOrConstructorOrMethodInWhichItIsDefined(ast1); final DetailAST classOrMethodOfAst2 = findClassOrConstructorOrMethodInWhichItIsDefined(ast2); <START> return classOrMethodOfAst1 == classOrMethodOfAst2; <END> }</code><technical_language>![Codacy](<LINK_0> Issue found: [Use equals() compare object references.](<LINK_1></technical_language>

Target:
private static boolean isSameVariables(DetailAST ast1, DetailAST ast2) { final DetailAST classOrMethodOfAst1 = findFirstUpperNamedBlock(ast1); final DetailAST classOrMethodOfAst2 = findFirstUpperNamedBlock(ast2); return classOrMethodOfAst1 == classOrMethodOfAst2; }
Source:
<code><START> public String[] getGroupAdd() { <END> return groupAdd; }</code><technical_language>lists</technical_language>

Target:
public List<String> getGroupAdd() { return groupAdd; }
Source:
<code>public AddressMessage(NetworkParameters params, final PeerAddress addr){ super(params); <START> addresses = new LinkedList<PeerAddress>(){{ <END> add(addr); }}; }</code><technical_language>I guess Collections.singletonList() here</technical_language>

Target:
public AddressMessage(NetworkParameters params, final PeerAddress addr){ super(params); addresses = Collections.singletonList(addr); }
Source:
<code>public void inputChanged(@Nullable Viewer viewer, @Nullable Object oldInput, @Nullable Object newInput) { if (!(newInput instanceof List)) { return; } List<?> list = (List<?>) newInput; if (list.isEmpty()) { return; } final ITmfTrace trace = getTrace(); if (trace == null) { return; } <START> fSyncLock.lock(); BuildThread buildThread = fBuildThread; if (buildThread != null) { buildThread.cancel(); } buildThread = new BuildThread(trace); buildThread.start(); fBuildThread = buildThread; fSyncLock.unlock(); <END> }</code><technical_language>need pattern reentrant lock. happen lock unlocked if exception in lock unlock. lock.lock(); // block condition holds try { // ... method body } finally { lock.unlock() }</technical_language>

Target:
public void inputChanged(@Nullable Viewer viewer, @Nullable Object oldInput, @Nullable Object newInput) { if (!(newInput instanceof List)) { return; } List<?> list = (List<?>) newInput; if (list.isEmpty()) { return; } final ITmfTrace trace = getTrace(); if (trace == null) { return; } fSyncLock.lock(); try { BuildThread buildThread = fBuildThread; if (buildThread != null) { buildThread.cancel(); } buildThread = new BuildThread(trace); buildThread.start(); fBuildThread = buildThread; } finally { fSyncLock.unlock(); } }
Source:
<code>public DirContext getContext() throws UserStoreException { DirContext context = null; if (dcMap == null) { try { context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection.Trying again to get connection... ", e); try { context = new InitialDirContext(environment); } catch (Exception e1) { throw new UserStoreException("Error obtaining connection. " + e.getMessage(), e); } } } else if (dcMap != null && dcMap.size() != 0) { try { Integer firstKey = dcMap.firstKey(); SRVRecord firstRecord = dcMap.get(firstKey); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord)); context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection to first Domain Controller.Trying to connect with other Domain" + " Controllers...", e); for (Integer integer : dcMap.keySet()) { <START> try { <END> SRVRecord srv = dcMap.get(integer); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv)); context = new InitialDirContext(environment); break; } catch (NamingException e1) { if(integer == (dcMap.lastKey())){ throw new UserStoreException("Error obtaining connection for all " + integer + " Domain Controllers.", e); } } } } } return (context); }</code><technical_language>add debug log</technical_language>

Target:
public DirContext getContext() throws UserStoreException { DirContext context = null; if (dcMap == null) { try { context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection.Trying again to get connection... ", e); try { context = new InitialDirContext(environment); } catch (Exception e1) { String errorMessage = "Error obtaining connection."; if (log.isDebugEnabled()) { log.debug(errorMessage, e1); } throw new UserStoreException(errorMessage, e); } } } else if (dcMap != null && dcMap.size() != 0) { try { Integer firstKey = dcMap.firstKey(); SRVRecord firstRecord = dcMap.get(firstKey); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord)); context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection to first Domain Controller.Trying to connect with other Domain" + " Controllers...", e); for (Integer integer : dcMap.keySet()) { try { SRVRecord srv = dcMap.get(integer); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv)); context = new InitialDirContext(environment); break; } catch (NamingException e1) { if(integer == (dcMap.lastKey())){ String errorMessage = "Error obtaining connection for all " + integer + " Domain Controllers."; if (log.isDebugEnabled()) { log.debug(errorMessage, e1); } throw new UserStoreException(errorMessage, e1); } } } } } return (context); }
Source:
<code>private boolean otherBranchCommit(Change change, PatchSet patchSet) throws RepositoryNotFoundException, IOException, PatchSetInfoNotAvailableException { Repository git = repoManager.openRepository(change.getProject()); String targetBranch = change.getDest().get(); try { RefDatabase refDb = git.getRefDatabase(); RevWalk rw = new RevWalk(git); RevCommit pushedCommit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); <START> Ref targetRef = refDb.getRef(targetBranch); <END> RevCommit mergeBase; RevFilter oldRevFilter = rw.getRevFilter(); try { rw.reset(); rw.setRevFilter(RevFilter.MERGE_BASE); rw.markStart(pushedCommit); RevCommit target = rw.parseCommit(targetRef.getObjectId()); rw.markStart(target); if (rw.next() != null) { mergeBase = rw.next(); } else { return true; } } finally { rw.reset(); rw.setRevFilter(oldRevFilter); } try { rw.markStart(pushedCommit); Collection<Ref> branches = refDb.getRefs(Constants.R_HEADS).values(); for (Ref branch : branches) { if (!branch.getObjectId().equals(mergeBase)) { rw.markUninteresting(rw.parseCommit(branch.getObjectId())); } } for (RevCommit n; (n = rw.next()) != null;) { if (n.equals(mergeBase)) { return false; } } return true; } finally { rw.release(); } } finally { git.close(); } }</code><technical_language>targetRef is line 160, move this line line 159</technical_language>

Target:
private boolean otherBranchCommit(Change change, PatchSet patchSet) throws RepositoryNotFoundException, IOException, PatchSetInfoNotAvailableException { Repository git = repoManager.openRepository(change.getProject()); String targetBranch = change.getDest().get(); boolean commitBranchFlag = true; try { RefDatabase refDb = git.getRefDatabase(); Ref targetRef = refDb.getRef(targetBranch); Collection<Ref> branches = refDb.getRefs(Constants.R_HEADS).values(); RevWalk rw = new RevWalk(git); RevCommit pushedCommit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); RevCommit target = rw.parseCommit(targetRef.getObjectId()); RevCommit mergeBase = null; RevFilter oldRevFilter = rw.getRevFilter(); try { rw.reset(); rw.setRevFilter(RevFilter.MERGE_BASE); rw.markStart(pushedCommit); rw.markStart(target); if (rw.next() != null) { mergeBase = rw.next(); } } finally { rw.reset(); rw.setRevFilter(oldRevFilter); } try { rw.markStart(pushedCommit); for (Ref branch : branches) { if (branch.getObjectId() != targetRef.getObjectId()) { rw.markUninteresting(rw.parseCommit(branch.getObjectId())); } } for (RevCommit n; (n = rw.next()) != null;) { if (n.equals(mergeBase)) { commitBranchFlag = false; break; } } } finally { rw.release(); } } finally { git.close(); } return commitBranchFlag; }
Source:
<code>public void getRetryOptionsTest() { AmqpRetryOptions testRetryOption = eventHubConnectionProcessor.getRetryOptions(); <START> Assertions.assertNotNull(testRetryOption); <END> }</code><technical_language>Assert values of retry mode, maxDelay, maxRetries well</technical_language>

Target:
public void getRetryOptionsTest() { AmqpRetryOptions testRetryOption = eventHubConnectionProcessor.getRetryOptions(); Assertions.assertEquals(AMQP_RETRY_OPTIONS.getTryTimeout(), testRetryOption.getTryTimeout()); Assertions.assertEquals(AMQP_RETRY_OPTIONS.getDelay(), testRetryOption.getDelay()); Assertions.assertEquals(AMQP_RETRY_OPTIONS.getMaxRetries(), testRetryOption.getMaxRetries()); Assertions.assertEquals(AMQP_RETRY_OPTIONS.getMaxDelay(), testRetryOption.getMaxDelay()); Assertions.assertEquals(AMQP_RETRY_OPTIONS.getMode(), testRetryOption.getMode()); }
Source:
<code>public void checkParityFor(long currentId) { final Optional<ChargeEntity> maybeCharge = chargeDao.findById(currentId); try { if (maybeCharge.isPresent()) { final ChargeEntity charge = maybeCharge.get(); MDC.put("chargeId", charge.getExternalId()); if (chargeExistsInLedger(charge) && refundsExistInLedger(charge.getRefunds())) { logger.info("transaction (its refunds) exists in ledger and have the same state [id={}]", currentId); chargeService.updateChargeParityStatus(charge.getExternalId(), ParityCheckStatus.EXISTS_IN_LEDGER); } else { <START> logger.info("transaction (its refunds) does not exist in ledger or is in a different state [id={}] -", currentId); <END> chargeService.updateChargeParityStatus(charge.getExternalId(), ParityCheckStatus.MISSING_IN_LEDGER); emitHistoricalEvents(charge); } } else { logger.info("[{}/{}] - not found", currentId, maxId); } } finally { MDC.remove("chargeId"); } }</code><technical_language>useful split this Charge in ledger Charge status mismatched able quantity type (missing / mismatch ..)</technical_language>

Target:
public void checkParityFor(long currentId) { final Optional<ChargeEntity> maybeCharge = chargeDao.findById(currentId); try { if (maybeCharge.isPresent()) { final ChargeEntity charge = maybeCharge.get(); MDC.put("chargeId", charge.getExternalId()); ParityCheckStatus parityCheckStatus = getChargeAndRefundsParityCheckStatus(charge); chargeService.updateChargeParityStatus(charge.getExternalId(), parityCheckStatus); logger.info("transaction parity check finished [id={},status={}]", currentId, parityCheckStatus); if (!parityCheckStatus.equals(ParityCheckStatus.EXISTS_IN_LEDGER)) { emitHistoricalEvents(charge); } } else { logger.info("[{}/{}] - not found", currentId, maxId); } } finally { MDC.remove("chargeId"); } }
Source:
<code>protected final void setDatabaseName(final String databaseName) { if (!setup) { <START> throw new IllegalStateException("Can only set this variable during valid times"); <END> } this.databaseName = databaseName; }</code><technical_language>"valid times" "setup time" "setup"</technical_language>

Target:
protected final void setDatabaseName(final String databaseName) { if (!setup) { throw new IllegalStateException("Can only set this variable during setup"); } this.databaseName = databaseName; }
Source:
<code>public void onAttach(Context context) { super.onAttach(context); <START> if (!(context instanceof GeoTagActivity)) { <END> throw new IllegalStateException("Activity is not instance of " + GeoTagActivity.class.getSimpleName()); } activity = (GeoTagActivity) context; lbm = LocalBroadcastManager.getInstance(context); }</code><technical_language>@chaviw getActivity() instead of context. guarantee context is derived parent activity</technical_language>

Target:
public void onAttach(Context context) { super.onAttach(context); Activity activity = getActivity(); if (!(activity instanceof GeoTagActivity)) { throw new IllegalStateException("Activity is not instance of " + GeoTagActivity.class.getSimpleName()); } this.activity = (GeoTagActivity) activity; lbm = LocalBroadcastManager.getInstance(context); }
Source:
<code>public ParameterListBuilder add(final Class<?> type, final String name, final boolean optional, final boolean varArgs) { final int ordinal = builder.size(); builder.add( new FunctionParameter() { public int getOrdinal() { return ordinal; } public String getName() { return name; } public RelDataType getType(RelDataTypeFactory typeFactory) { <START> return typeFactory.createJavaType(varArgs ? type.getComponentType() : type); <END> } public boolean isOptional() { return optional; } public boolean isVarArgs() { return varArgs; } }); return this; }</code><technical_language>a local var hold</technical_language>

Target:
public ParameterListBuilder add(final Class<?> type, final String name, final boolean optional, final boolean varArgs) { final int ordinal = builder.size(); builder.add( new FunctionParameter() { public int getOrdinal() { return ordinal; } public String getName() { return name; } public RelDataType getType(RelDataTypeFactory typeFactory) { final Class paramType = varArgs ? type.getComponentType() : type; return typeFactory.createJavaType(paramType); } public boolean isOptional() { return optional; } public boolean isVarArgs() { return varArgs; } }); return this; }
Source:
<code>private <V> V syncExec(final NoCheckedExceptionCallable<V> callable) { final AtomicReference<V> r = new AtomicReference<V>(); final AtomicReference<RuntimeException> exception = new AtomicReference<RuntimeException>(); browser .getDisplay() .syncExec( <START> () -> { <END> try { r.set(callable.call()); } catch (RuntimeException e) { exception.set(e); } }); if (exception.get() != null) { throw exception.get(); } return r.get(); }</code><technical_language><LINK_0> Do want swallow "Error"</technical_language>

Target:
private <V> V syncExec(final NoCheckedExceptionCallable<V> callable) { final AtomicReference<V> r = new AtomicReference<V>(); final AtomicReference<RuntimeException> exception = new AtomicReference<RuntimeException>(); final AtomicReference<Error> error = new AtomicReference<Error>(); browser .getDisplay() .syncExec( () -> { try { r.set(callable.call()); } catch (RuntimeException e) { exception.set(e); } catch (Error e) { error.set(e); } }); if (exception.get() != null) throw exception.get(); if (error.get() != null) throw error.get(); return r.get(); }
Source:
<code>public Builder argument(BuilderFunction<GraphQLArgument.Builder> builderFunction) { GraphQLArgument.Builder builder = GraphQLArgument.newArgument(); builder = builderFunction.apply(builder); this.arguments.add(builder.build()); return this; <START> } <END></code><technical_language>call return argument(GraphQLArgument.Builder builder) overload defined below</technical_language>

Target:
public Builder argument(BuilderFunction<GraphQLArgument.Builder> builderFunction) { GraphQLArgument.Builder builder = GraphQLArgument.newArgument(); builder = builderFunction.apply(builder); return argument(builder); }
Source:
<code>public void onEntityCollision(World world, Entity entity) { if(new BlockPos(0, 1, 1).equals(posInMultiblock)&&!world.isRemote&&entity!=null&&entity.isAlive()&&entity instanceof ItemEntity) { SawmillTileEntity master = master(); if(master==null) return; ItemStack stack = ((ItemEntity)entity).getItem(); if(stack.isEmpty()) return; master.insertItemToProcess(stack, false); if(stack.getCount() <= 0) entity.remove(); <START> } <END> }</code><technical_language>disappointed, stepping giant exposed spinning sawblade hurt you</technical_language>

Target:
public void onEntityCollision(World world, Entity entity) { if(!world.isRemote&&entity!=null&&entity.isAlive()) { SawmillTileEntity master = master(); if(master==null) return; if(new BlockPos(0, 1, 1).equals(posInMultiblock)&&entity instanceof ItemEntity) { ItemStack stack = ((ItemEntity)entity).getItem(); if(stack.isEmpty()) return; master.insertItemToProcess(stack, false); if(stack.getCount() <= 0) entity.remove(); } else if(entity instanceof LivingEntity&&!master.sawblade.isEmpty() &&CACHED_SAWBLADE_AABB.apply(master).intersects(entity.getBoundingBox())) { if(entity instanceof PlayerEntity&&((PlayerEntity)entity).abilities.disableDamage) return; int consumed = master.energyStorage.extractEnergy(80, true); if(consumed > 0) { master.energyStorage.extractEnergy(consumed, false); entity.attackEntityFrom(IEDamageSources.sawmill, 7); } } } }
Source:
<code>public OAuthToken getToken(String userId) throws IOException { final OAuthToken token = super.getToken(userId); if (!(token == null || token.getToken() == null || token.getToken().isEmpty())) { <START> String tokenVerifyUrl = this.openshiftEndpoint + "oapi/v1/projects"; <END> HttpURLConnection http = null; try { http = (HttpURLConnection) new URL(tokenVerifyUrl).openConnection(); http.setInstanceFollowRedirects(false); http.setRequestMethod("GET"); http.setRequestProperty("Authorization", "Bearer " + token.getToken()); http.setRequestProperty("Accept", "application/json"); if (http.getResponseCode() == 401) { return null; } } finally { if (http != null) { http.disconnect(); } } return token; } return null; }</code><technical_language>checked this OpenShift 3.9(not need it), 3.11, 4,2</technical_language>

Target:
public OAuthToken getToken(String userId) throws IOException { final OAuthToken token = super.getToken(userId); if (!(token == null || token.getToken() == null || token.getToken().isEmpty())) { HttpURLConnection http = null; try { http = (HttpURLConnection) new URL(verifyTokenUrl).openConnection(); http.setInstanceFollowRedirects(false); http.setRequestMethod("GET"); http.setRequestProperty("Authorization", "Bearer " + token.getToken()); http.setRequestProperty("Accept", "application/json"); if (http.getResponseCode() == 401) { return null; } } finally { if (http != null) { http.disconnect(); } } return token; } return null; }
Source:
<code>public LabelsNeededSummary getSummaryOfLabelsNeeded(final LabelsInfoInput labelsInfoInput) { final LabelsNeededSummary labelsNeededSummary = new LabelsNeededSummary(); final List<InstanceInfomationDTO> observationsByInstance = this.middlewareDatasetService.getInformationInstance(labelsInfoInput.getDatasetId(), labelsInfoInput.getStudyId()); long totalNumberOfLabelsNeeded = 0; <START> for (InstanceInfomationDTO instanceInfomationDTO:observationsByInstance) { <END> final LabelsNeededSummary.Row row = new LabelsNeededSummary.Row(instanceInfomationDTO.getEnvironment().toString(), instanceInfomationDTO.getnOfObservations(),instanceInfomationDTO.getnOfObservations(), instanceInfomationDTO.getnOfReps(), instanceInfomationDTO.getnOfEntries()); labelsNeededSummary.addRow(row); totalNumberOfLabelsNeeded += row.getLabelsNeeded(); } labelsNeededSummary.setTotalNumberOfLabelsNeeded(totalNumberOfLabelsNeeded); return labelsNeededSummary; }</code><technical_language>add final</technical_language>

Target:
public LabelsNeededSummary getSummaryOfLabelsNeeded(final LabelsInfoInput labelsInfoInput) { final LabelsNeededSummary labelsNeededSummary = new LabelsNeededSummary(); final List<InstanceDetailsDTO> InstanceDetailsDTOs = this.middlewareDatasetService.getInstanceDetails(labelsInfoInput.getDatasetId(), labelsInfoInput.getStudyId()); long totalNumberOfLabelsNeeded = 0; for (final InstanceDetailsDTO instanceDetailsDTO :InstanceDetailsDTOs) { final LabelsNeededSummary.Row row = new LabelsNeededSummary.Row(instanceDetailsDTO.getEnvironment().toString(), instanceDetailsDTO.getnOfObservations(), instanceDetailsDTO.getnOfObservations(), instanceDetailsDTO.getnOfReps(), instanceDetailsDTO.getnOfEntries()); labelsNeededSummary.addRow(row); totalNumberOfLabelsNeeded += row.getLabelsNeeded(); } labelsNeededSummary.setTotalNumberOfLabelsNeeded(totalNumberOfLabelsNeeded); return labelsNeededSummary; }
Source:
<code>public String getUniqueUsername(String providerId) { String id = null; while (true) { id = "USR" + generateUniqueId() + "_" + providerId; Object existingFile = null; try { existingFile = getUser(id); } catch (QuadrigaStorageException e) { <START> e.printStackTrace(); <END> } if (existingFile == null) { break; } } return id; }</code><technical_language>a logger</technical_language>

Target:
public String getUniqueUsername(String providerId) { String id = null; while (true) { id = "USR" + generateUniqueId() + "_" + providerId; Object existingUser = null; try { existingUser = getUser(id); } catch (QuadrigaStorageException e) { logger.error("Error while retrieving user details",e); break; } if (existingUser == null) { break; } } return id; }
Source:
<code>private void createEmptyCommit(final Repository repo, final Project.NameKey project, final String ref) throws IOException { ObjectInserter oi = repo.newObjectInserter(); try { CommitBuilder cb = new CommitBuilder(); cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {})); cb.setCommitter(currentUser.newCommitterIdent()); cb.setAuthor(cb.getCommitter()); cb.setMessage("Initial empty repository"); ObjectId id = oi.insert(cb); oi.flush(); RefUpdate ru = repo.updateRef(Constants.HEAD); ru.setNewObjectId(id); final Result result = ru.update(); switch (result) { case NEW: rq.scheduleUpdate(project, ref); break; default: { final String msg = "Cannot create empty commit for " + projectName + ": " + result.name(); <START> log.error(msg); <END> throw new IOException(result.name()); } } } catch (IOException e) { log.error("Cannot create empty commit for " + projectName, e); throw e; } finally { oi.release(); } }</code><technical_language>This is redundant catch block below, resulting in exception logged twice. :-( Drop this line allow catch block handle logging</technical_language>

Target:
private void createEmptyCommit(final Repository repo, final Project.NameKey project, final String ref) throws IOException { ObjectInserter oi = repo.newObjectInserter(); try { CommitBuilder cb = new CommitBuilder(); cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {})); cb.setCommitter(serverIdent); cb.setAuthor(cb.getCommitter()); cb.setMessage("Initial empty repository"); ObjectId id = oi.insert(cb); oi.flush(); RefUpdate ru = repo.updateRef(Constants.HEAD); ru.setNewObjectId(id); final Result result = ru.update(); switch (result) { case NEW: rq.scheduleUpdate(project, ref); break; default: { throw new IOException(result.name()); } } } catch (IOException e) { log.error("Cannot create empty commit for " + projectName, e); throw e; } finally { oi.release(); } }
Source:
<code>public boolean isActivated(String name) { for (IClassCollectionRole classCollection : classCollections) { if (classCollection.getConfigName().equals(name)) { return classCollection.isActivated(); } } <START> try { <END> return Utils.getComponentManager().lookup(ClassPackage.class, name).isActivated(); } catch (ComponentLookupException exc) { LOGGER.debug("ClassDefinitionPackage '{}' doesn't exist", name); return false; } }</code><technical_language>please move "lookup" for loop</technical_language>

Target:
public boolean isActivated(String name) { try { return Utils.getComponentManager().lookup(ClassPackage.class, name).isActivated(); } catch (ComponentLookupException exc) { LOGGER.debug("ClassDefinitionPackage '{}' doesn't exist", name); } for (IClassCollectionRole classCollection : classCollections) { if (classCollection.getConfigName().equals(name)) { return classCollection.isActivated(); } } return false; }
Source:
<code>private void commit() { if (getEntity() != null) { if (getWindow() != null) { return; } <START> Optional<Snapshot> inPreviewSnapshot = getItems().stream().filter(s -> s.getStatus() == SnapshotStatus.IN_PREVIEW).findFirst(); <END> if (!inPreviewSnapshot.isPresent()) { return; } Snapshot snapshot = inPreviewSnapshot.get(); ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().commitSnapshotTitle()); model.setHelpTag(HelpTag.commit_snapshot); model.setHashName("commit_snapshot"); model.setMessage(ConstantsManager.getInstance() .getMessages() .areYouSureYouWantToCommitSnapshot( DateTimeFormat.getFormat(DATE_FORMAT).format(snapshot.getCreationDate()), snapshot.getDescription())); model.getCommands().add(UICommand.createDefaultOkUiCommand("OnCommit", this)); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); } }</code><technical_language>perform this iteration if getSelectedItem() == null</technical_language>

Target:
private void commit() { if (getEntity() != null) { if (getWindow() != null) { return; } Snapshot snapshot; if (getSelectedItem() == null) { snapshot = getItems().stream() .filter(s -> s.getStatus() == SnapshotStatus.IN_PREVIEW) .findFirst() .orElse(null); } else { snapshot = getSelectedItem(); } if (snapshot == null) { return; } ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().commitSnapshotTitle()); model.setHelpTag(HelpTag.commit_snapshot); model.setHashName("commit_snapshot"); model.setMessage(ConstantsManager.getInstance() .getMessages() .areYouSureYouWantToCommitSnapshot( DateTimeFormat.getFormat(DATE_FORMAT).format(snapshot.getCreationDate()), snapshot.getDescription())); model.getCommands().add(UICommand.createDefaultOkUiCommand("OnCommit", this)); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); } }