auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void producesPartsWithContentLength() throws IOException { final RqMultipart.Base multipart = new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?a=4 HTTP/1.1", "Host: rtw.example.com", "Content-Type: multipart/form-data; boundary=AaB01x", "Content-Length: 100007" ), Joiner.on("\r\n").join( "--AaB01x", new StringBuilder() .append("Content-Disposition: form-data; name=\"") .append(RqMultipartTest.PART_T2).append("\""), "", "447 N Wolfe Rd, Sunnyvale, CA 94085", "--AaB01x" ) ) ); try { MatcherAssert.assertThat( multipart.part(RqMultipartTest.PART_T2) .iterator() .next(), new HmRqHeader( "content-length", "102" <START> ) <END> ); } finally { multipart.body().close(); multipart.part(RqMultipartTest.PART_T2).iterator().next() .body().close(); } }</code><technical_language>@raphaelln 4 spaces</technical_language>

Target:
public void producesPartsWithContentLength() throws IOException { final String part = "t2"; final RqMultipart.Base multipart = new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?a=4 HTTP/1.1", "Host: rtw.example.com", "Content-Type: multipart/form-data; boundary=AaB01x", "Content-Length: 100007" ), Joiner.on("\r\n").join( "--AaB01x", String.format(RqMultipartTest.CONTENT, part), "", "447 N Wolfe Rd, Sunnyvale, CA 94085", "--AaB01x" ) ) ); try { MatcherAssert.assertThat( multipart.part(part) .iterator() .next(), new HmRqHeader( "content-length", "102" ) ); } finally { multipart.body().close(); multipart.part(part).iterator().next() .body().close(); } }
Source:
<code>private static Escaper createEscaper(char charToEscape) { final String escapedChar = "\\" + charToEscape; final Escaper result = Escapers.builder() .addEscape('\"', "\\\"") <START> .addEscape(':', "\\:") <END> .addEscape(charToEscape, escapedChar) .build(); return result; }</code><technical_language>do _still_ need escape colon character</technical_language>

Target:
private static Escaper createEscaper(char charToEscape) { final String escapedChar = "\\" + charToEscape; final Escaper result = Escapers.builder() .addEscape('\"', "\\\"") .addEscape(charToEscape, escapedChar) .build(); return result; }
Source:
<code>private SiteInit createSiteInit() { final ConsoleUI ui = ConsoleUI.getInstance(batchMode); final File sitePath = getSitePath(); final List<Module> m = new ArrayList<Module>(); m.add(new InitModule()); m.add(new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(File.class).annotatedWith(SitePath.class).toInstance(sitePath); <START> List<String> plugins = Optional.fromNullable(installPlugins).or(Lists.<String> newArrayList()); <END> bind(new TypeLiteral<List<String>>() {}).annotatedWith(InstallPlugins.class).toInstance(plugins); } }); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getMessage()); while (why != null) { buf.append("\n"); buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } }</code><technical_language>Objects.firstNonNull(installPlugins, Lists.<String> newArrayList());</technical_language>

Target:
private SiteInit createSiteInit() { final ConsoleUI ui = ConsoleUI.getInstance(batchMode); final File sitePath = getSitePath(); final List<Module> m = new ArrayList<Module>(); m.add(new InitModule()); m.add(new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(File.class).annotatedWith(SitePath.class).toInstance(sitePath); List<String> plugins = Objects.firstNonNull(installPlugins, Lists.<String> newArrayList()); bind(new TypeLiteral<List<String>>() {}).annotatedWith( InstallPlugins.class).toInstance(plugins); } }); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getMessage()); while (why != null) { buf.append("\n"); buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } }
Source:
<code>public void getReportTemplateHome_shouldCreateADirectoryAtGPValueIfItIsAnAbsolutePath() throws Exception { File tempFolder = temporaryFolder.newFolder("/mrrt_templates"); administrationService.setGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, tempFolder.getAbsolutePath()); File templateHome = radiologyProperties.getReportTemplateHome(); assertNotNull(templateHome); assertThat(templateHome.exists(), is(true)); <START> assertThat(templateHome.getName(), is(tempFolder.getName())); <END> assertThat(templateHome.isAbsolute(), is(true)); }</code><technical_language>@ivange94 here, good :+1:</technical_language>

Target:
public void getReportTemplateHome_shouldCreateADirectoryAtGPValueIfItIsAnAbsolutePath() throws Exception { File tempFolder = temporaryFolder.newFolder("/mrrt_templates"); administrationService.setGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, tempFolder.getAbsolutePath()); File templateHome = radiologyProperties.getReportTemplateHome(); File templateHomeFromGP = new File(administrationService.getGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR)); assertNotNull(templateHome); assertThat(templateHome.exists(), is(true)); assertThat(templateHome.getName(), is(templateHomeFromGP.getName())); assertThat(templateHome.getName(), is(tempFolder.getName())); assertThat(templateHome.isAbsolute(), is(true)); }
Source:
<code>public void modifyCachePool(CachePoolInfo info) throws IOException { if (this.vfs == null) { super.modifyCachePool(info); return; } throw new UnsupportedOperationException( <START> "listCacheDirectives is not supported in ViewDFS"); <END> }</code><technical_language>API name in exception. support cache commands, similar other ones</technical_language>

Target:
public void modifyCachePool(CachePoolInfo info) throws IOException { if (this.vfs == null) { super.modifyCachePool(info); return; } List<IOException> failedExceptions = new ArrayList<>(); boolean isDFSExistsInChilds = false; for (FileSystem fs : getChildFileSystems()) { if (!(fs instanceof DistributedFileSystem)) { continue; } isDFSExistsInChilds = true; DistributedFileSystem dfs = (DistributedFileSystem) fs; try { dfs.modifyCachePool(info); } catch (IOException ioe) { failedExceptions.add(ioe); } } if (!isDFSExistsInChilds) { throw new UnsupportedOperationException( "No DFS available in child file systems."); } if (failedExceptions.size() > 0) { throw MultipleIOException.createIOException(failedExceptions); } }
Source:
<code>private static String formatInstant(Instant instant, ZoneId timeZone, String pattern) { if (instant == null) { return ""; } ZonedDateTime zonedDateTime = instant.atZone(timeZone); String processedPattern; if (zonedDateTime.getHour() == 12 && zonedDateTime.getMinute() == 0) { processedPattern = pattern.replace("a", "'NOON'"); } else { <START> processedPattern = pattern; <END> } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(processedPattern); return zonedDateTime.format(formatter); }</code><technical_language>processedPattern</technical_language>

Target:
private static String formatInstant(Instant instant, ZoneId timeZone, String pattern) { if (instant == null) { return ""; } ZonedDateTime zonedDateTime = instant.atZone(timeZone); String processedPattern = pattern; if (zonedDateTime.getHour() == 12 && zonedDateTime.getMinute() == 0) { processedPattern = pattern.replace("a", "'NOON'"); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(processedPattern); return zonedDateTime.format(formatter); }
Source:
<code><START> private List<Object[]> fetchJudgmentsReferencingTags(List<Long> judgmentIds) { <END> String select = "SELECT refId\\:\\:text\\:\\:bigint refId, tag.judgment_id, tag.tag_type, tag.value\\:\\:text" + " FROM enrichment_tag tag" + " JOIN json_array_elements(tag.value) tagValue ON true" + " JOIN json_array_elements(tagValue->'judgmentIds') refId ON true" + " WHERE tag.tag_type = 'REFERENCED_COURT_CASES' AND refId\\:\\:text\\:\\:bigint in (:judgmentIds);"; Query query = entityManager.createNativeQuery(select); query.setParameter("judgmentIds", judgmentIds); @SuppressWarnings("unchecked") List<Object[]> results = query.getResultList(); return results; }</code><technical_language>return list of JudgmentEnrichmentTags</technical_language>

Target:
private Map<Long, JudgmentEnrichmentTags> fetchJudgmentsReferencingTags(List<Long> judgmentIds) { String select = "SELECT refId\\:\\:text\\:\\:bigint refId, tag.judgment_id, tag.tag_type, tag.value\\:\\:text" + " FROM enrichment_tag tag" + " JOIN json_array_elements(tag.value) tagValue ON true" + " JOIN json_array_elements(tagValue->'judgmentIds') refId ON true" + " WHERE tag.tag_type = 'REFERENCED_COURT_CASES' AND refId\\:\\:text\\:\\:bigint in (:judgmentIds);"; Query query = entityManager.createNativeQuery(select); query.setParameter("judgmentIds", judgmentIds); @SuppressWarnings("unchecked") List<Object[]> results = query.getResultList(); Map<Long, JudgmentEnrichmentTags> judgmentsEnrichmentTagsMap = Maps.newHashMap(); for (Object[] result : results) { long referencedJudgmentId = ((BigInteger)result[0]).longValue(); long judgmentId = ((BigInteger)result[1]).longValue(); String tagType = (String)result[2]; String value = (String)result[3]; EnrichmentTag tag = new EnrichmentTag(); tag.setJudgmentId(judgmentId); tag.setTagType(tagType); tag.setValue(value); putEnrichmentTagInMap(judgmentsEnrichmentTagsMap, referencedJudgmentId, tag); } return judgmentsEnrichmentTagsMap; }
Source:
<code><START> public void setup() throws Exception { <END> when(metadata.getDefinitionSetId()).thenReturn(DEF_SET_ID); when(profile.getProjectProfileName()).thenReturn(org.kie.workbench.common.profile.api.preferences.Profile.PLANNER_AND_RULES.getName()); doAnswer(invocation -> { ParameterizedCommand<ProfilePreferences> callback = (ParameterizedCommand<ProfilePreferences>) invocation.getArguments()[0]; callback.execute(profilePreferences); return null; }).when(profilePreferences).load(any(ParameterizedCommand.class), any(ParameterizedCommand.class)); when(profilePreferences.getProfile()).thenReturn(PROJECT_PROFILE); when(profileManager.getProfiles(eq(DEF_SET_ID))).thenReturn(Collections.singletonList(profile)); tested = new StunnerProfilePreferencesLoader(profileManager, profilePreferences, DEFAULT_PROFILE); }</code><technical_language>Method produce exception</technical_language>

Target:
public void setup() { when(metadata.getDefinitionSetId()).thenReturn(DEF_SET_ID); when(profile.getProjectProfileName()).thenReturn(org.kie.workbench.common.profile.api.preferences.Profile.PLANNER_AND_RULES.getName()); doAnswer(invocation -> { ParameterizedCommand<ProfilePreferences> callback = (ParameterizedCommand<ProfilePreferences>) invocation.getArguments()[0]; callback.execute(profilePreferences); return null; }).when(profilePreferences).load(any(ParameterizedCommand.class), any(ParameterizedCommand.class)); when(profilePreferences.getProfile()).thenReturn(PROJECT_PROFILE); when(profileManager.getProfiles(eq(DEF_SET_ID))).thenReturn(Collections.singletonList(profile)); tested = new StunnerProfilePreferencesLoader(profileManager, profilePreferences, DEFAULT_PROFILE); }
Source:
<code>public OSProcess[] getProcesses(int limit, ProcessSort sort) { List<OSProcess> procs = new ArrayList<>(); File[] pids = ProcUtil.getPidFiles(); <START> LinuxUserInfo userInfo = getUserInfo(); <END> Map<String, String> users = userInfo.getUsers(); Map<String, String> groups = userInfo.getGroups(); for (File pid : pids) { OSProcess proc = getProcess(ParseUtil.parseIntOrDefault(pid.getName(), 0), users, groups); if (proc != null) { procs.add(proc); } } List<OSProcess> sorted = processSort(procs, limit, sort); return sorted.toArray(new OSProcess[sorted.size()]); }</code><technical_language>Calling code this re-parse user group list time. However, this information rarely changes in reality. Is a check this information is updated (e.g., timestamp /etc/shadow (if available) /etc/passwd)? If so, this information stored/cached a class variable updated if timestamp is changed. Alternately cache trigger a re-read error (finding a UID in map) a longer time period (e.g., 5 minutes)</technical_language>

Target:
public OSProcess[] getProcesses(int limit, ProcessSort sort) { List<OSProcess> procs = new ArrayList<>(); File[] pids = ProcUtil.getPidFiles(); for (File pid : pids) { OSProcess proc = getProcess(ParseUtil.parseIntOrDefault(pid.getName(), 0)); if (proc != null) { procs.add(proc); } } List<OSProcess> sorted = processSort(procs, limit, sort); return sorted.toArray(new OSProcess[sorted.size()]); }
Source:
<code>public void log(RequestLogLine requestLogLine) throws IOException { final Map mdc = MDC.getCopyOfContextMap(); try { if (setMDC) { try { final Query query = requestLogLine.getQuery(); MDC.put("queryId", query.getId()); <START> MDC.put("dataSource", findInnerDatasource(query).toString()); <END> MDC.put("queryType", query.getType()); MDC.put("hasFilters", Boolean.toString(query.hasFilters())); MDC.put("remoteAddr", requestLogLine.getRemoteAddr()); MDC.put("duration", query.getDuration().toString()); MDC.put("descending", Boolean.toString(query.isDescending())); if (setContextMDC) { final Iterable<Map.Entry<String, Object>> entries = query.getContext() == null ? ImmutableList.of() : query.getContext().entrySet(); for (Map.Entry<String, Object> entry : entries) { MDC.put(entry.getKey(), entry.getValue() == null ? "NULL" : entry.getValue().toString()); } } } catch (RuntimeException re) { LOG.error(re, "Error preparing MDC"); } } final String line = requestLogLine.getLine(mapper); LOG.info("%s", line); } finally { if (setMDC) { if (mdc != null) { MDC.setContextMap(mdc); } else { MDC.clear(); } } } }</code><technical_language>adding a new field isNested this query is nested not</technical_language>

Target:
public void log(RequestLogLine requestLogLine) throws IOException { final Map mdc = MDC.getCopyOfContextMap(); try { if (setMDC) { try { final Query query = requestLogLine.getQuery(); MDC.put("queryId", query.getId()); MDC.put("dataSource", findInnerDatasource(query).toString()); MDC.put("queryType", query.getType()); MDC.put("isNested", String.valueOf(!(query.getDataSource() instanceof TableDataSource))); MDC.put("hasFilters", Boolean.toString(query.hasFilters())); MDC.put("remoteAddr", requestLogLine.getRemoteAddr()); MDC.put("duration", query.getDuration().toString()); MDC.put("descending", Boolean.toString(query.isDescending())); if (setContextMDC) { final Iterable<Map.Entry<String, Object>> entries = query.getContext() == null ? ImmutableList.of() : query.getContext().entrySet(); for (Map.Entry<String, Object> entry : entries) { MDC.put(entry.getKey(), entry.getValue() == null ? "NULL" : entry.getValue().toString()); } } } catch (RuntimeException re) { LOG.error(re, "Error preparing MDC"); } } final String line = requestLogLine.getLine(mapper); LOG.info("%s", line); } finally { if (setMDC) { if (mdc != null) { MDC.setContextMap(mdc); } else { MDC.clear(); } } } }
Source:
<code>ExecutionPlan getExecutionPlan(String runId) { Map<String, String> allowedUserConfig = new HashMap<>(userConfig); Map<String, String> generatedConfig = new HashMap<>(); if (!LegacyTaskApplication.class.isAssignableFrom(appDesc.getAppClass())) { <START> if (StringUtils.isBlank(userConfig.get(TaskConfig.INPUT_STREAMS()))) { <END> allowedUserConfig.remove(TaskConfig.INPUT_STREAMS()); } generatedConfig.putAll(getGeneratedConfig(runId)); } Config mergedConfig = JobNodeConfigurationGenerator.mergeConfig(allowedUserConfig, generatedConfig); StreamManager streamManager = buildAndStartStreamManager(mergedConfig); try { ExecutionPlanner planner = new ExecutionPlanner(mergedConfig, streamManager); return planner.plan(appDesc); } finally { streamManager.stop(); } }</code><technical_language>is this check required</technical_language>

Target:
ExecutionPlan getExecutionPlan(String runId) { Map<String, String> allowedUserConfig = new HashMap<>(userConfig); Map<String, String> generatedConfig = new HashMap<>(); if (!LegacyTaskApplication.class.isAssignableFrom(appDesc.getAppClass())) { if (StringUtils.isBlank(userConfig.get(TaskConfig.INPUT_STREAMS))) { allowedUserConfig.remove(TaskConfig.INPUT_STREAMS); } generatedConfig.putAll(getGeneratedConfig(runId)); } Config mergedConfig = JobNodeConfigurationGenerator.mergeConfig(allowedUserConfig, generatedConfig); StreamManager streamManager = buildAndStartStreamManager(mergedConfig); try { ExecutionPlanner planner = new ExecutionPlanner(mergedConfig, streamManager); return planner.plan(appDesc); } finally { streamManager.stop(); } }
Source:
<code>public void testCall() { String change_id = null; String commit_id = null; try { GitAccess gAccess = new GitAccess(); Git git = gAccess.getGitProject(); gAccess.addFile("EGerritTestReviewFile.java", "Hello reviewers community !\n This is the second line \n"); gAccess.pushFile(); change_id = gAccess.getChangeId(); commit_id = gAccess.getCommitId(); } catch (Exception e1) { e1.printStackTrace(); } <START> CreateDraftCommand command <END> = fGerrit.createDraftComments(change_id, commit_id); CommentInfo commentInfo = new CommentInfo(); commentInfo.setLine(2); commentInfo.setMessage("This is a test comment"); commentInfo.setPath("EGerritTestReviewFile.java"); command.setCommentInfo(commentInfo); command.requiresAuthentication(true); CommentInfo result = null; try { result = command.call(); } catch (EGerritException e) { fail(e.getMessage()); } assertEquals(result.getMessage(), commentInfo.getMessage()); }</code><technical_language>This test is testing for change id test id, another test testing a changeid a commit id, return data for a specific change id</technical_language>

Target:
public void testCall() { String change_id = null; String commit_id = null; try { GitAccess gAccess = new GitAccess(); Git git = gAccess.getGitProject(); gAccess.addFile("EGerritTestReviewFile.java", "Hello reviewers community !\n This is the second line \n"); gAccess.pushFile(); change_id = gAccess.getChangeId(); commit_id = gAccess.getCommitId(); } catch (Exception e1) { fail(e1.getMessage()); } CreateDraftCommand command = fGerrit.createDraftComments(change_id, commit_id); CommentInfo commentInfo = new CommentInfo(); commentInfo.setLine(2); commentInfo.setMessage("This is a test comment"); commentInfo.setPath("EGerritTestReviewFile.java"); command.setCommentInfo(commentInfo); CommentInfo result = null; try { result = command.call(); } catch (EGerritException e) { fail(e.getMessage()); } assertEquals(result.getLine(), commentInfo.getLine()); assertEquals(result.getMessage(), commentInfo.getMessage()); assertEquals(result.getPath(), commentInfo.getPath()); }
Source:
<code>public CqlQueryResponse executeCqlQuery(CqlRequest cqlRequest) throws UnsupportedQueryException, SourceUnavailableException, FederationException { QueryRequest request = cqlRequest.createQueryRequest(catalogFramework.getId(), filterBuilder); Stopwatch stopwatch = Stopwatch.createStarted(); List<QueryResponse> responses = Collections.synchronizedList(new ArrayList<>()); QueryFunction queryFunction = (queryRequest) -> { QueryResponse queryResponse = catalogFramework.query(queryRequest); responses.add(queryResponse); return queryResponse; }; List<Result> results; if (cqlRequest.getCount() == 0) { results = ResultIterable.resultIterable(queryFunction, request) .stream() .collect(Collectors.toList()); } else { results = ResultIterable.resultIterable(queryFunction, request, cqlRequest.getCount()) <START> .stream() <END> .collect(Collectors.toList()); } QueryResponse response = new QueryResponseImpl( request, results, true, responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getHits) .findFirst() .orElse(-1l), responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getProperties) .findFirst() .orElse(Collections.emptyMap())); stopwatch.stop(); return new CqlQueryResponse( cqlRequest.getId(), request, response, cqlRequest.getSource(), stopwatch.elapsed(TimeUnit.MILLISECONDS), cqlRequest.isNormalize(), filterAdapter, actionRegistry); }</code><technical_language>If duplicating stream collect always: (but is pretty similar) java ResultIterable iterable; if (cqlRequest.getCount() == 0) { iterable = resultIterable(queryFunction, request); } else { iterable = resultIterable(queryFunction, request, cqlRequest.getCount()) } List<Result> results = iterable.stream().collect(Collectors.toList());</technical_language>

Target:
public CqlQueryResponse executeCqlQuery(CqlRequest cqlRequest) throws UnsupportedQueryException, SourceUnavailableException, FederationException { QueryRequest request = cqlRequest.createQueryRequest(catalogFramework.getId(), filterBuilder); Stopwatch stopwatch = Stopwatch.createStarted(); List<QueryResponse> responses = Collections.synchronizedList(new ArrayList<>()); List<Result> results; if (cqlRequest.getCount() == 0) { results = retrieveHitCount(request, responses); } else { results = retrieveResults(cqlRequest, request, responses); } QueryResponse response = new QueryResponseImpl( request, results, true, responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getHits) .findFirst() .orElse(-1L), responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getProperties) .findFirst() .orElse(Collections.emptyMap())); stopwatch.stop(); return new CqlQueryResponse( cqlRequest.getId(), request, response, cqlRequest.getSource(), stopwatch.elapsed(TimeUnit.MILLISECONDS), cqlRequest.isNormalize(), filterAdapter, actionRegistry); }
Source:
<code>private void charge(StateTransitionThrottleConfig.RebalanceType rebalanceType, Map<StateTransitionThrottleConfig.RebalanceType, Long> quota) { if (StateTransitionThrottleConfig.RebalanceType.NONE.equals(rebalanceType)) { logger.error("Wrong rebalance type NONE as parameter"); return; } <START> quota.computeIfPresent(StateTransitionThrottleConfig.RebalanceType.ANY, (key, val) -> Math.max(0, val - 1)); <END> if (!rebalanceType.equals(StateTransitionThrottleConfig.RebalanceType.ANY)) { quota.computeIfPresent(rebalanceType, (key, val) -> Math.max(0, val - 1)); } }</code><technical_language>Minor: instead of (key, val) a more descriptive name: (rebalanceType, quota)</technical_language>

Target:
private void charge(StateTransitionThrottleConfig.RebalanceType rebalanceType, Map<StateTransitionThrottleConfig.RebalanceType, Long> quota) { if (StateTransitionThrottleConfig.RebalanceType.NONE.equals(rebalanceType)) { logger.error("Wrong rebalance type NONE as parameter"); return; } quota.computeIfPresent(StateTransitionThrottleConfig.RebalanceType.ANY, (type, quotaNumber) -> Math.max(0, quotaNumber - 1)); if (!rebalanceType.equals(StateTransitionThrottleConfig.RebalanceType.ANY)) { quota.computeIfPresent(rebalanceType, (type, quotaNumber) -> Math.max(0, quotaNumber - 1)); } }
Source:
<code><START> public void testConstructorModifiedSince() throws SearchException, IOException, ImapAsyncClientException { <END> final ExtendedSearchSequence searchSeq = new ExtendedSearchSequence(); final ExtendedModifiedSinceTerm extendedModifiedSinceTerm = new ExtendedModifiedSinceTerm(1L); final Argument args = new Argument(); args.append(searchSeq.generateSequence(extendedModifiedSinceTerm)); final String searchStr = args.toString(); Assert.assertEquals(searchStr, "MODSEQ 1", "result mismatched."); }</code><technical_language>ImapAsyncClientException thrown test</technical_language>

Target:
public void testConstructorModifiedSince() throws SearchException, IOException { final ExtendedSearchSequence searchSeq = new ExtendedSearchSequence(); final ExtendedModifiedSinceTerm extendedModifiedSinceTerm = new ExtendedModifiedSinceTerm(1L); final Argument args = new Argument(); args.append(searchSeq.generateSequence(extendedModifiedSinceTerm)); final String searchStr = args.toString(); Assert.assertEquals(searchStr, "MODSEQ 1", "generateSequence() mismatched."); }
Source:
<code>private boolean tryLockVmForUpdate(Pair<VM, VmInternalData> pair) { Guid vmId = getVmId(pair); if (vmId != null) { VmManager vmManager = getResourceManager().getVmManager(vmId); if (vmManager.trylock()) { <START> if (vmManager.getLastUpdateDate().compareTo(fetchTime) > 0) { <END> log.warn("skipping VM '{}' from this monitoring cycle" + " - the VM data has changed since fetching the data", vmId); vmManager.unlock(); } else { vmManagers.put(vmId, vmManager); return true; } } else { log.debug("skipping VM '{}' from this monitoring cycle" + " - the VM is locked by its VmManager ", getVmId(pair)); } } return false; }</code><technical_language>well, probability is low, I know, >= ? in terms of readability I prefer if (fetchTime.compareTo(vmManager.getLastUpdateDate()) > 0){... } else {.. } - subjective I guess, for consideration</technical_language>

Target:
private boolean tryLockVmForUpdate(Pair<VM, VmInternalData> pair) { Guid vmId = getVmId(pair); if (vmId != null) { VmManager vmManager = getResourceManager().getVmManager(vmId); if (vmManager.trylock()) { if (fetchTime - vmManager.getVmDataChangedTime() < 0) { log.warn("skipping VM '{}' from this monitoring cycle" + " - the VM data has changed since fetching the data", vmId); vmManager.unlock(); } else { vmManagers.put(vmId, vmManager); return true; } } else { log.debug("skipping VM '{}' from this monitoring cycle" + " - the VM is locked by its VmManager ", getVmId(pair)); } } return false; }
Source:
<code>public void handleLifecycleEvent(SaveablesLifecycleEvent event) { if (currentPart == null || event.getEventType() != SaveablesLifecycleEvent.DIRTY_CHANGED) { return; } Saveable[] saveables = event.getSaveables(); for (Saveable saveable : <START> saveables) { <END> if (new DefaultSaveable(PropertySheet.this).equals(saveable)) { return; } } if (event.getSource() instanceof SaveablesList) { SaveablesList saveablesList = (SaveablesList) event.getSource(); for (Saveable saveable : saveables) { IWorkbenchPart[] parts = saveablesList.getPartsForSaveable(saveable); for (IWorkbenchPart part : parts) { if (PropertySheet.this.currentPart == part) { firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY); return; } } } } }</code><technical_language>I saveables API in detail, sources this is null safe. I add a null check for-each iteration</technical_language>

Target:
public void handleLifecycleEvent(SaveablesLifecycleEvent event) { if (currentPart == null || event.getEventType() != SaveablesLifecycleEvent.DIRTY_CHANGED) { return; } Saveable[] saveables = event.getSaveables(); if (saveables == null) { return; } for (Saveable saveable : saveables) { if (new DefaultSaveable(PropertySheet.this).equals(saveable)) { return; } } if (event.getSource() instanceof SaveablesList) { SaveablesList saveablesList = (SaveablesList) event.getSource(); for (Saveable saveable : saveables) { IWorkbenchPart[] parts = saveablesList.getPartsForSaveable(saveable); for (IWorkbenchPart part : parts) { if (PropertySheet.this.currentPart == part) { firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY); return; } } } } }
Source:
<code>private Map<String, String> parseAccount(String account) { assertNotEmpty(account, "accountName"); this.accountName = account; Map<String, String> h = new HashMap<String, String>(); if (account.startsWith("http://") || account.startsWith("https://")) { try { URI uri = new URI(account); uri.getPort(); h.put("scheme", uri.getScheme()); h.put("hostname", uri.getHost()); h.put("port", new Integer(uri.getPort()).toString()); <START> if(uri.getUserInfo() != null && !uri.getUserInfo().isEmpty()) { <END> h.put("username", uri.getUserInfo().split(":")[0]); h.put("password", uri.getUserInfo().split(":")[1]); } } catch (URISyntaxException e) { } } else { h.put("scheme", "https"); h.put("hostname", account + ".cloudant.com"); h.put("port", "443"); } return h; }</code><technical_language>is this added here? I thought this happened in HttpConnection's execute method</technical_language>

Target:
private Map<String, String> parseAccount(String account) { assertNotEmpty(account, "accountName"); this.accountName = account; Map<String, String> h = new HashMap<String, String>(); if (account.startsWith("http://") || account.startsWith("https://")) { try { URI uri = new URI(account); uri.getPort(); h.put("scheme", uri.getScheme()); h.put("hostname", uri.getHost()); h.put("port", new Integer(uri.getPort()).toString()); } catch (URISyntaxException e) { } } else { h.put("scheme", "https"); h.put("hostname", account + ".cloudant.com"); h.put("port", "443"); } return h; }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { <START> return Collections.singletonList(new PermissionSubject(getUserId(), VdcObjectType.System, ActionGroup.EDIT_PROFILE)); <END> }</code><technical_language>i missed before, send "getActionType().getActionGroup()" instead of actionGroup here, correct action group in VdcActionType enum (where currently is wrongly MANIPULATE_USERS new EDIT_PROFILE</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { return Collections.singletonList(new PermissionSubject(getUserId(), VdcObjectType.System, getActionType().getActionGroup())); }
Source:
<code>protected List<MarketoField> getLeadColumns() { List<MarketoField> columns = marketoService.describeLead(); if (pluginTask.getIncludedLeadFields().isPresent() && !pluginTask.getIncludedLeadFields().get().isEmpty()) { List<MarketoField> filteredColumns = new ArrayList<>(); <START> List<String> includedFields = pluginTask.getIncludedLeadFields().get(); <END> for (String fieldName : includedFields) { Optional<MarketoField> includedField = lookupFieldIgnoreCase(columns, fieldName); if (includedField.isPresent()) { filteredColumns.add(includedField.get()); } else { LOGGER.warn("Included field not found in Marketo lead field", fieldName); } } columns = filteredColumns; } LOGGER.info("Included Fields option is set, included columns: [{}]", columns); return columns; }</code><technical_language>nit: code is totally okay, do improve a of readability? easily say: filter columns is included includedLeadFields. Anyway, for discussion. java final FluentIterable<String> includedFields = FluentIterable.from(pluginTask.getIncludedLeadFields().get()); return FluentIterable.from(columns).filter(new Predicate<MarketoField>() { @Override public boolean apply(final MarketoField col) { Predicate<String> equalsIgnoreCase = new Predicate<String>() { @Override public boolean apply(@Nullable String input) { return col.getName().equalsIgnoreCase(input); } }; return includedFields.anyMatch(equalsIgnoreCase); } }).toList();</technical_language>

Target:
protected List<MarketoField> getLeadColumns() { List<MarketoField> columns = marketoService.describeLead(); if (pluginTask.getIncludedLeadFields().isPresent() && !pluginTask.getIncludedLeadFields().get().isEmpty()) { List<MarketoField> filteredColumns = new ArrayList<>(); List<String> includedFields = pluginTask.getIncludedLeadFields().get(); for (String fieldName : includedFields) { Optional<MarketoField> includedField = lookupFieldIgnoreCase(columns, fieldName); if (includedField.isPresent()) { filteredColumns.add(includedField.get()); } else { LOGGER.warn("Included field not found in Marketo lead field", fieldName); } } columns = filteredColumns; LOGGER.info("Included Fields option is set, included columns: [{}]", columns); } return columns; }
Source:
<code>void prepare() throws InfrastructureException { KubernetesClient k8sClient = clientFactory.create(workspaceId); if (k8sClient.serviceAccounts().inNamespace(namespace).withName(serviceAccountName).get() == null) { createWorkspaceServiceAccount(k8sClient); } String execRoleName = "exec"; if (k8sClient.rbac().kubernetesRoles().inNamespace(namespace).withName(execRoleName).get() == null) { createExecRole(k8sClient, execRoleName); } String viewRoleName = "workspace-view"; if (k8sClient.rbac().kubernetesRoles().inNamespace(namespace).withName(viewRoleName).get() == null) { createViewRole(k8sClient, viewRoleName); } k8sClient .rbac() .kubernetesRoleBindings() .inNamespace(namespace) .createOrReplace(createExecRoleBinding()); k8sClient .rbac() .kubernetesRoleBindings() .inNamespace(namespace) .createOrReplace(createViewRoleBinding()); <START> String customClusterRoleName = System.getenv("CHE_WORKSPACE_CLUSTER_ROLE"); <END> if (!"".equals(customClusterRoleName)) { k8sClient .rbac() .kubernetesRoleBindings() .inNamespace(namespace) .createOrReplace(createCustomRoleBinding(customClusterRoleName)); } }</code><technical_language>P.S. che.infra.kubernetes.cluster_service_account_name right configuration property name, I guess. Also, add default che.properties file</technical_language>

Target:
void prepare() throws InfrastructureException { KubernetesClient k8sClient = clientFactory.create(workspaceId); if (k8sClient.serviceAccounts().inNamespace(namespace).withName(serviceAccountName).get() == null) { createWorkspaceServiceAccount(k8sClient); } String execRoleName = "exec"; if (k8sClient.rbac().kubernetesRoles().inNamespace(namespace).withName(execRoleName).get() == null) { createExecRole(k8sClient, execRoleName); } String viewRoleName = "workspace-view"; if (k8sClient.rbac().kubernetesRoles().inNamespace(namespace).withName(viewRoleName).get() == null) { createViewRole(k8sClient, viewRoleName); } k8sClient .rbac() .kubernetesRoleBindings() .inNamespace(namespace) .createOrReplace(createExecRoleBinding()); k8sClient .rbac() .kubernetesRoleBindings() .inNamespace(namespace) .createOrReplace(createViewRoleBinding()); if (!isNullOrEmpty(this.clusterRoleName)) { if (k8sClient.rbac().kubernetesClusterRoles().withName(this.clusterRoleName).get() != null) { k8sClient .rbac() .kubernetesRoleBindings() .inNamespace(namespace) .createOrReplace(createCustomRoleBinding(this.clusterRoleName)); } else { LOG.warn( "Unable to find the cluster role {}. Skip creating custom role binding.", this.clusterRoleName); } } }
Source:
<code><START> public RemoveAsset(final String assetId) { <END> super("removeAsset"); this.assetId = assetId; }</code><technical_language>ChangeAssetOrder: constructor private creation static constructor</technical_language>

Target:
private RemoveAsset(final String assetId) { super("removeAsset"); this.assetId = assetId; }
Source:
<code><START> private static boolean containsGlusterServer(ArrayList<VdcActionParametersBase> parameters) { <END> Set<Guid> processed = new HashSet<Guid>(); for(VdcActionParametersBase param : parameters) { VDS vds = DbFacade.getInstance().getVdsDao().get(((RemoveVdsParameters) param).getVdsId()); if (!processed.contains(vds.getvds_group_id())) { VDSGroup cluster = DbFacade.getInstance().getVdsGroupDao().get(vds.getvds_group_id()); if (cluster.supportsGlusterService()) { return true; } processed.add(vds.getvds_group_id()); } } return false; }</code><technical_language>(ArrayList<? extends VdsActionParameters> parameters) cast needed</technical_language>

Target:
private static boolean containsGlusterServer(ArrayList<VdcActionParametersBase> parameters) { Set<Guid> processed = new HashSet<Guid>(); for (VdcActionParametersBase param : parameters) { VDS vds = DbFacade.getInstance().getVdsDao().get(((RemoveVdsParameters) param).getVdsId()); if (vds != null && !processed.contains(vds.getvds_group_id())) { VDSGroup cluster = DbFacade.getInstance().getVdsGroupDao().get(vds.getvds_group_id()); if (cluster.supportsGlusterService()) { return true; } processed.add(vds.getvds_group_id()); } } return false; }
Source:
<code>public void handleGpioPinAnalogValueChangeEvent(GpioPinAnalogValueChangeEvent event) { GpioPin pin = event.getPin(); MCP3424GpioProvider provider = (MCP3424GpioProvider) pin.getProvider(); if (pin.getTag() instanceof NumberItem) { double value = provider.getAnalogValue(pin.getPin()); try { this.eventPublisher.postUpdate(pin.getName(), new DecimalType(value)); } catch (NumberFormatException exception) { logger.warn("Unable to convert '{}' for item to number", <START> new String[] { String.valueOf(value), pin.getName() }); <END> } logger.debug("GPIO channel change: = {}", pin, value); } else if (pin.getTag() instanceof DimmerItem) { double value = provider.getPercentValue(pin.getPin()); try { this.eventPublisher.postUpdate(pin.getName(), new PercentType((int) value)); } catch (NumberFormatException e) { logger.warn("Unable to convert '{}' for item to number", new String[] { String.valueOf(value), pin.getName() }); } logger.debug("GPIO channel change: = {}", pin, value); } }</code><technical_language>omit String[] object creation here</technical_language>

Target:
public void handleGpioPinAnalogValueChangeEvent(GpioPinAnalogValueChangeEvent event) { GpioPin pin = event.getPin(); MCP3424GpioProvider provider = (MCP3424GpioProvider) pin.getProvider(); if (pin.getTag() instanceof NumberItem) { double value = provider.getAnalogValue(pin.getPin()); try { this.eventPublisher.postUpdate(pin.getName(), new DecimalType(value)); } catch (NumberFormatException exception) { logger.warn("Unable to convert '{}' for item to number", String.valueOf(value), pin.getName()); } logger.debug("GPIO channel change: = {}", pin, value); } else if (pin.getTag() instanceof DimmerItem) { double value = provider.getPercentValue(pin.getPin()); try { this.eventPublisher.postUpdate(pin.getName(), new PercentType((int) value)); } catch (NumberFormatException e) { logger.warn("Unable to convert '{}' for item to number", String.valueOf(value), pin.getName()); } logger.debug("GPIO channel change: = {}", pin, value); } }
Source:
<code>public static List<NameValuePair> getQueryParametersWithPriceSelection(@Nullable final PriceSelection priceSelection, final List<NameValuePair> currentParameters) { final List<NameValuePair> currentParametersWithoutPriceSelectionParameters = currentParameters.stream() .filter(pair -> !ALL_PARAMETERS.contains(pair.getName())) .collect(toList()); final List<NameValuePair> resultingParameters = new LinkedList<>(currentParametersWithoutPriceSelectionParameters); if (priceSelection != null && priceSelection.getPriceCurrency() != null) { addParamIfNotNull(resultingParameters, PRICE_CURRENCY, priceSelection.getPriceCurrency()); addParamIfNotNull(resultingParameters, PRICE_COUNTRY, priceSelection.getPriceCountry()); addParamIfNotNull(resultingParameters, PRICE_CUSTOMER_GROUP, priceSelection.getPriceCustomerGroup()); addParamIfNotNull(resultingParameters, PRICE_CHANNEL, priceSelection.getPriceChannel()); addParamIfNotNull(resultingParameters, STORE_PROJECTION, priceSelection.getStoreProjection()); <START> addParamIfNotNull(resultingParameters, LOCALE_PROJECTION, priceSelection.getLocaleProjection()); <END> } return resultingParameters; }</code><technical_language>add items of localeProjection list</technical_language>

Target:
public static List<NameValuePair> getQueryParametersWithPriceSelection(@Nullable final PriceSelection priceSelection, final List<NameValuePair> currentParameters) { final List<NameValuePair> currentParametersWithoutPriceSelectionParameters = currentParameters.stream() .filter(pair -> !ALL_PARAMETERS.contains(pair.getName())) .collect(toList()); final List<NameValuePair> resultingParameters = new LinkedList<>(currentParametersWithoutPriceSelectionParameters); if (priceSelection != null && priceSelection.getPriceCurrency() != null) { addParamIfNotNull(resultingParameters, PRICE_CURRENCY, priceSelection.getPriceCurrency()); addParamIfNotNull(resultingParameters, PRICE_COUNTRY, priceSelection.getPriceCountry()); addParamIfNotNull(resultingParameters, PRICE_CUSTOMER_GROUP, priceSelection.getPriceCustomerGroup()); addParamIfNotNull(resultingParameters, PRICE_CHANNEL, priceSelection.getPriceChannel()); addParamIfNotNull(resultingParameters, STORE_PROJECTION, priceSelection.getStoreProjection()); priceSelection.getLocaleProjection().forEach(parameter -> addParamIfNotNull(resultingParameters, LOCALE_PROJECTION, parameter)); } return resultingParameters; }
Source:
<code>public boolean start() { if (s_logger.isInfoEnabled()) { <START> s_logger.info("Starting Alert Manager"); <END> } return true; }</code><technical_language>This log message deceptive. This class is quota statements alerts</technical_language>

Target:
public boolean start() { if (s_logger.isInfoEnabled()) { s_logger.info("Starting Statement Manager"); } return true; }
Source:
<code>public CleanCommand setCleanDirectories(boolean dirs) { <START> this.directories = dirs; <END> return this; }</code><technical_language>this keyword needed</technical_language>

Target:
public CleanCommand setCleanDirectories(boolean dirs) { directories = dirs; return this; }
Source:
<code>public boolean onPreferenceClick(Preference preference) { String preferenceKey = preference != null ? preference.getKey() : ""; if (preferenceKey.equals(getString(R.string.pref_key_device_settings))) { return handleDevicePreferenceClick(); } else if (preferenceKey.equals(getString(R.string.pref_key_app_about))) { return handleAboutPreferenceClick(); } else if (preferenceKey.equals(getString(R.string.pref_key_oss_licenses))) { return handleOssPreferenceClick(); } else if (preference == mPrivacySettings) { return handlePrivacyClick(); } else if (preference == mWhatsNew) { <START> if (getActivity() instanceof AppCompatActivity) { new FeatureAnnouncementDialogFragment() .show(((AppCompatActivity) getActivity()).getSupportFragmentManager(), FeatureAnnouncementDialogFragment.TAG); } else { throw new IllegalArgumentException( "Parent activity is not AppCompatActivity. FeatureAnnouncementDialogFragment must be called " + "using support fragment manager from AppCompatActivity."); } <END> } return false; }</code><technical_language>wondering if sense put this in a function align code above. wdyt? (Also of a difference returning a true assess managed event.)</technical_language>

Target:
public boolean onPreferenceClick(Preference preference) { String preferenceKey = preference != null ? preference.getKey() : ""; if (preferenceKey.equals(getString(R.string.pref_key_device_settings))) { return handleDevicePreferenceClick(); } else if (preferenceKey.equals(getString(R.string.pref_key_app_about))) { return handleAboutPreferenceClick(); } else if (preferenceKey.equals(getString(R.string.pref_key_oss_licenses))) { return handleOssPreferenceClick(); } else if (preference == mPrivacySettings) { return handlePrivacyClick(); } else if (preference == mWhatsNew) { return handleFeatureAnnouncementClick(); } return false; }
Source:
<code>public EEFViewDescription convert() { EEFViewDescription view = EefFactory.eINSTANCE.createEEFViewDescription(); <START> view.setLabelExpression("aql:self.name"); <END> for (PageDescription pageDescription : pageDescriptions) { createPage(pageDescription, view); } Set<Entry<EEFPropertyValidationRuleDescription, PropertyValidationRule>> entries = this.eefPropertyValidationRule2propertyValidationRule.entrySet(); for (Entry<EEFPropertyValidationRuleDescription, PropertyValidationRule> entry : entries) { List<WidgetDescription> widgets = entry.getValue().getTargets(); for (WidgetDescription widgetDescription : widgets) { EEFWidgetDescription eefWidgetDescription = this.widget2eefWidget.get(widgetDescription); if (eefWidgetDescription != null) { EEFPropertyValidationRuleDescription eefPropertyValidationRule = entry.getKey(); eefPropertyValidationRule.getTargets().add(eefWidgetDescription); } } } this.widget2eefWidget.clear(); this.eefPropertyValidationRule2propertyValidationRule.clear(); return view; }</code><technical_language>feature:name equivalent depend presence of AQL (feature: is hard-coded guaranteed present)</technical_language>

Target:
public EEFViewDescription convert() { EEFViewDescription view = EefFactory.eINSTANCE.createEEFViewDescription(); view.setLabelExpression("feature:name"); for (PageDescription pageDescription : pageDescriptions) { createPage(pageDescription, view); } Set<Entry<EEFPropertyValidationRuleDescription, PropertyValidationRule>> entries = this.eefPropertyValidationRule2propertyValidationRule.entrySet(); for (Entry<EEFPropertyValidationRuleDescription, PropertyValidationRule> entry : entries) { List<WidgetDescription> widgets = entry.getValue().getTargets(); for (WidgetDescription widgetDescription : widgets) { EEFWidgetDescription eefWidgetDescription = this.widget2eefWidget.get(widgetDescription); if (eefWidgetDescription != null) { EEFPropertyValidationRuleDescription eefPropertyValidationRule = entry.getKey(); eefPropertyValidationRule.getTargets().add(eefWidgetDescription); } } } this.widget2eefWidget.clear(); this.eefPropertyValidationRule2propertyValidationRule.clear(); return view; }
Source:
<code>public <V> V apply(InputStream stream, Type type) throws IOException { try { <START> Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create(); <END> return (V) gson.fromJson(Strings2.toStringAndClose(stream), type); } finally { if (stream != null) { stream.close(); } } }</code><technical_language>ArrayAdapterFactory is for concrete lists, sense adapters, specific for list remove generic logic</technical_language>

Target:
public <V> V apply(InputStream stream, Type type) throws IOException { try { GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapterFactory(new TypeAdapterFactory() { @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> tt) { return new ServerFirewallPolicyAdapter(tt); } }); Gson gson = gsonBuilder.create(); return (V) gson.fromJson(Strings2.toStringAndClose(stream), type); } finally { if (stream != null) { stream.close(); } } }
Source:
<code>public void run() { try { startupComplete(); while(isRunning()) { configureNewConnections(); processNewResponses(); long startSelectTime = SystemTime.getInstance().milliseconds(); int ready = selector.select(300); logger.trace("Processor id selection time = ms", id, (SystemTime.getInstance().milliseconds() - startSelectTime)); if(ready > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while(iter.hasNext() && isRunning()) { SelectionKey key = null; try { key = iter.next(); iter.remove(); if(key.isReadable()) { int bytesRead = read(key); <START> if(bytesRead == -1) <END> close(key); } else if(key.isWritable()) { write(key); } else if(!key.isValid()) { close(key); } else throw new IllegalStateException("Unrecognized key state for processor thread."); } catch (EOFException e) { close(key); logger.error("closing key on EOFException {}", e); } catch (Throwable e) { logger.error("closing key on exception remote host " + ((SocketChannel) key.channel()).socket().getRemoteSocketAddress(), e); close(key); } } } } logger.debug("Closing server socket and selector."); closeAll(); selector.close(); shutdownComplete(); } catch (Exception e) { logger.error("Error while shutting down processor thread {}", e); } }</code><technical_language>Do this read</technical_language>

Target:
public void run() { try { startupComplete(); while (isRunning()) { configureNewConnections(); processNewResponses(); long startSelectTime = SystemTime.getInstance().milliseconds(); int ready = selector.select(300); logger.trace("Processor id selection time = ms", id, (SystemTime.getInstance().milliseconds() - startSelectTime)); if (ready > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext() && isRunning()) { SelectionKey key = null; try { key = iter.next(); iter.remove(); if (key.isReadable()) { read(key); } else if (key.isWritable()) { write(key); } else if (!key.isValid()) { close(key); } else { throw new IllegalStateException("Unrecognized key state for processor thread."); } } catch (EOFException e) { close(key); logger.error("closing key on EOFException {}", e); } catch (Throwable e) { logger.error("closing key on exception remote host " + ((SocketChannel) key.channel()).socket() .getRemoteSocketAddress(), e); close(key); } } } } logger.debug("Closing server socket and selector."); closeAll(); selector.close(); shutdownComplete(); } catch (Exception e) { logger.error("Error while shutting down processor thread {}", e); } }