auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void addHostBondDevices(VDS vds, Map<String, Object> xmlRpcStruct) { Map<String, Map<String, Object>> bonds = (Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_BONDINGS); if (bonds != null) { boolean cfgEntriesDeprecated = FeatureSupported.cfgEntriesDeprecated(vds.getVdsGroupCompatibilityVersion()); for (Entry<String, Map<String, Object>> entry : bonds.entrySet()) { VdsNetworkInterface bond = new Bond(); updateCommonInterfaceData(bond, vds, entry); bond.setBonded(true); Map<String, Object> bondProperties = entry.getValue(); if (bondProperties != null) { bond.setMacAddress((String) bondProperties.get("hwaddr")); if (bondProperties.get("slaves") != null) { addBondDeviceToHost(vds, bond, (Object[]) bondProperties.get("slaves")); } Object bondOptions = null; if (cfgEntriesDeprecated) { Map<String, Object> bondOptionsMap = (Map<String, Object>)bondProperties.get("opts"); String miimon = (String)bondOptionsMap.get("miimon"); String mode = (String)bondOptionsMap.get("mode"); bondOptions = String.format("mode=%s miimon=%s", mode, miimon); } else { Map<String, Object> config = (Map<String, Object>) bondProperties.get("cfg"); bondOptions = (config == null) ? null : config.get("BONDING_OPTS"); } if (bondOptions != null) { bond.setBondOptions(bondOptions.toString()); } } } } }

Target:
private static void addHostBondDevices(VDS vds, Map<String, Object> xmlRpcStruct) { Map<String, Map<String, Object>> bonds = (Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_BONDINGS); if (bonds != null) { boolean cfgEntriesDeprecated = FeatureSupported.cfgEntriesDeprecated(vds.getVdsGroupCompatibilityVersion()); for (Entry<String, Map<String, Object>> entry : bonds.entrySet()) { VdsNetworkInterface bond = new Bond(); updateCommonInterfaceData(bond, vds, entry); bond.setBonded(true); Map<String, Object> bondProperties = entry.getValue(); if (bondProperties != null) { bond.setMacAddress((String) bondProperties.get("hwaddr")); if (bondProperties.get("slaves") != null) { addBondDeviceToHost(vds, bond, (Object[]) bondProperties.get("slaves")); } Object bondOptions = null; if (cfgEntriesDeprecated) { Map<String, Object> bondOptionsMap = new HashMap<>(); bondOptionsMap.putAll((Map<String, Object>) bondProperties.get("opts")); String bondOptionsString = ""; String mode = (String) bondOptionsMap.get("mode"); String miimon = (String) bondOptionsMap.get("miimon"); if (mode != null && miimon != null) { bondOptionsString = String.format("mode=%s miimon=%s", mode, miimon); bondOptionsMap.remove("mode"); bondOptionsMap.remove("miimon"); } for (Map.Entry<String, Object> optionEntry : bondOptionsMap.entrySet()) { bondOptionsString = String.format("%s %s=%s", bondOptionsString, optionEntry.getKey(), optionEntry.getValue()); } bondOptions = bondOptionsString.isEmpty() ? null : bondOptionsString; } else { Map<String, Object> config = (Map<String, Object>) bondProperties.get("cfg"); bondOptions = (config == null) ? null : config.get("BONDING_OPTS"); } if (bondOptions != null) { bond.setBondOptions(bondOptions.toString()); } } } } }
Source:
default void addResources(Object kbuilder, Collection<ResourceWithConfiguration> resources, ResourceType type) throws Exception { for (ResourceWithConfiguration rd : resources) { rd.getBeforeAdd().accept(kbuilder); addResource(kbuilder, rd.getResource(), type, rd.getResourceConfigutation()); rd.getAfterAdd().accept(kbuilder); } }

Target:
default void addResources(Object kbuilder, Collection<ResourceWithConfiguration> resources, ResourceType type) throws Exception { for (ResourceWithConfiguration rd : resources) { rd.getBeforeAdd().accept(kbuilder); addResource(kbuilder, rd.getResource(), type, rd.getResourceConfiguration()); rd.getAfterAdd().accept(kbuilder); } }
Source:
private static void addHostBondDevices(VDS vds, Map<String, Object> xmlRpcStruct) { Map<String, Object> bonds = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.NETWORK_BONDINGS); if (bonds != null) { for (Entry<String, Object> entry : bonds.entrySet()) { VdsNetworkInterface iface = new Bond(); updateCommonInterfaceData(iface, vds, entry); iface.setBonded(true); Map<String, Object> bond = (Map<String, Object>) entry.getValue(); if (bond != null) { iface.setMacAddress((String) bond.get("hwaddr")); if (bond.get("slaves") != null) { addBondDeviceToHost(vds, iface, (Object[]) bond.get("slaves")); } Map<String, Object> config = (Map<String, Object>) bond.get("cfg"); if (config != null && config.get("BONDING_OPTS") != null) { iface.setBondOptions(config.get("BONDING_OPTS").toString()); } } } } }

Target:
private static void addHostBondDevices(VDS vds, Map<String, Object> xmlRpcStruct) { Map<String, Map<String, Object>> bonds = (Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_BONDINGS); if (bonds != null) { for (Entry<String, Map<String, Object>> entry : bonds.entrySet()) { VdsNetworkInterface iface = new Bond(); updateCommonInterfaceData(iface, vds, entry); iface.setBonded(true); Map<String, Object> bond = entry.getValue(); if (bond != null) { iface.setMacAddress((String) bond.get("hwaddr")); if (bond.get("slaves") != null) { addBondDeviceToHost(vds, iface, (Object[]) bond.get("slaves")); } Map<String, Object> config = (Map<String, Object>) bond.get("cfg"); if (config != null && config.get("BONDING_OPTS") != null) { iface.setBondOptions(config.get("BONDING_OPTS").toString()); } } } } }
Source:
protected int getFontStyle(String fontStyleExpression, EAttribute eAttribute, FontData defaultFontData, StyledText text) { int fontStyle = defaultFontData.getStyle(); if (fontStyleExpression != null && !fontStyleExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); String fontStyleValue = eval.get(eAttribute, fontStyleExpression, String.class); fontStyle = getFontStyle(fontStyleValue, fontStyle, text); } return fontStyle; }

Target:
private int getFontStyle(String fontStyleExpression, EAttribute eAttribute, FontData defaultFontData, StyledText text) { int fontStyle = defaultFontData.getStyle(); if (fontStyleExpression != null && !fontStyleExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); String fontStyleValue = eval.get(eAttribute, fontStyleExpression, String.class); fontStyle = getFontStyle(fontStyleValue, fontStyle, text); } return fontStyle; }
Source:
public void testValidTextFile() { MappingFile mf = getMappingFile("nm-output-example"); assertNotNull("global symbol file", mf); assertTrue(mf.getPid() < 0); mf = getMappingFile("symbol-123.map"); assertNotNull("Symbol file with pid", mf); assertEquals(123, mf.getPid()); Path nmOutput = Paths.get("..", "..", "tmf", "org.eclipse.tracecompass.tmf.core.tests", "testfiles", "callstack" , "symbol-123.map"); assertTrue(Files.exists(nmOutput)); String filePath = nmOutput.toFile().getAbsolutePath(); assertNotNull(filePath); mf = MappingFile.create(filePath, false, 2); assertNotNull("Symbol file for different pid", mf); assertEquals(2, mf.getPid()); }

Target:
public void testValidTextFile() { IMappingFile mf = getMappingFile("nm-output-example"); assertNotNull("global symbol file", mf); assertTrue(mf.getPid() < 0); mf = getMappingFile("symbol-123.map"); assertNotNull("Symbol file with pid", mf); assertEquals(123, mf.getPid()); Path nmOutput = Paths.get("..", "..", "tmf", "org.eclipse.tracecompass.tmf.core.tests", "testfiles", "callstack" , "symbol-123.map"); assertTrue(Files.exists(nmOutput)); String filePath = nmOutput.toFile().getAbsolutePath(); assertNotNull(filePath); mf = IMappingFile.create(filePath, false, 2); assertNotNull("Symbol file for different pid", mf); assertEquals(2, mf.getPid()); }
Source:
public void testVerifyInvalidToken() { Header header = new Header("X-Auth-Token", "invalid"); given(). header(header). when(). post("/token/verify"). then(). statusCode(HttpStatus.SC_UNAUTHORIZED); }

Target:
public void testVerifyInvalidToken() { Header header = new Header(AUTH_HEADER, "invalid"); given(). header(header). when(). post("/token/verify"). then(). statusCode(HttpStatus.SC_UNAUTHORIZED); }
Source:
private static <T extends DocumentResult> void validateDocumentResult(boolean showStatistics, DocumentResultCollection<T> expectedResults, DocumentResultCollection<T> actualResults, BiConsumer<T, T> additionalAssertions) { final Map<String, T> expected = expectedResults.stream().collect(Collectors.toMap(r -> r.getId(), r -> r)); final Map<String, T> actual = actualResults.stream().collect(Collectors.toMap(r -> r.getId(), r -> r)); assertEquals(expected.size(), actual.size()); if (showStatistics) { validateBatchStatistics(expectedResults.getStatistics(), actualResults.getStatistics()); } expected.forEach((key, expectedValue) -> { T actualValue = actual.get(key); assertTrue(actual.containsKey(key)); assertNotNull(actualValue); if (showStatistics) { validateDocumentStatistics(expectedValue.getStatistics(), actualValue.getStatistics()); } if (expectedValue.getError() == null) { assertNull(actualValue.getError()); } else { assertNotNull(actualValue.getError()); assertEquals(expectedValue.getError().getCode(), actualValue.getError().getCode()); validateErrorDocument(expectedValue.getError(), actualValue.getError()); } additionalAssertions.accept(expectedValue, actualValue); }); }

Target:
private static <T extends DocumentResult> void validateDocumentResult(boolean showStatistics, DocumentResultCollection<T> expectedResults, DocumentResultCollection<T> actualResults, BiConsumer<T, T> additionalAssertions) { final Map<String, T> expected = expectedResults.stream().collect(Collectors.toMap(r -> r.getId(), r -> r)); final Map<String, T> actual = actualResults.stream().collect(Collectors.toMap(r -> r.getId(), r -> r)); assertEquals(expected.size(), actual.size()); if (showStatistics) { validateBatchStatistics(expectedResults.getStatistics(), actualResults.getStatistics()); } expected.forEach((key, expectedValue) -> { T actualValue = actual.get(key); assertNotNull(actualValue); if (showStatistics) { validateDocumentStatistics(expectedValue.getStatistics(), actualValue.getStatistics()); } if (expectedValue.getError() == null) { assertNull(actualValue.getError()); } else { assertNotNull(actualValue.getError()); assertEquals(expectedValue.getError().getCode(), actualValue.getError().getCode()); validateErrorDocument(expectedValue.getError(), actualValue.getError()); } additionalAssertions.accept(expectedValue, actualValue); }); }
Source:
private void handleSingle(DoorsTableRow current, RowType rt) { switch (rt) { case SINGLE: stack.pop(); stack.push(current); break; case MULTI_START: stack.peek().setRowType(RowType.MULTI_START); current.setRowType(RowType.MULTI_MID); stack.push(current); break; case MULTI_MID: case MULTI_END: break; case FIRST_ROW: break; } }

Target:
private void handleSingle(DoorsTableRow current, RowType rt) { switch (rt) { case SINGLE: stack.pop(); stack.push(current); break; case MULTI_START: stack.peek().setRowType(RowType.MULTI_START); current.setRowType(RowType.MULTI_MID); stack.push(current); break; case MULTI_MID: case MULTI_END: break; case FIRST_ROW: break; default: throw new OseeStateException("Unhandled enumeration", current); } }
Source:
void initLocalServer(int hostId, boolean clearLocalDataDirectories) throws IOException { CommandLine cmdln = (templateCmdLine.makeCopy()); cmdln.startCommand(StartAction.INITIALIZE); cmdln.setJavaProperty(clusterHostIdProperty, String.valueOf(hostId)); if (this.m_additionalProcessEnv != null) { for (String name : this.m_additionalProcessEnv.keySet()) { cmdln.setJavaProperty(name, this.m_additionalProcessEnv.get(name)); } } if (clearLocalDataDirectories) { cmdln.setForceVoltdbCreate(true); } else { cmdln.setForceVoltdbCreate(false); } ServerThread th = new ServerThread(cmdln); File root = VoltFile.getServerSpecificRoot(String.valueOf(hostId), clearLocalDataDirectories); cmdln.voltdbRoot(root + "/voltdbroot"); th.start(); try { th.join(); VoltDB.resetInstance(); String hostIdStr = cmdln.getJavaProperty(clusterHostIdProperty); m_hostRoots.put(hostIdStr, cmdln.voltdbRoot().getAbsolutePath()); } catch (Exception ex) { ex.printStackTrace(); } }

Target:
void initLocalServer(int hostId, boolean clearLocalDataDirectories) throws IOException { CommandLine cmdln = (templateCmdLine.makeCopy()); cmdln.startCommand(StartAction.INITIALIZE); cmdln.setJavaProperty(clusterHostIdProperty, String.valueOf(hostId)); if (this.m_additionalProcessEnv != null) { for (String name : this.m_additionalProcessEnv.keySet()) { cmdln.setJavaProperty(name, this.m_additionalProcessEnv.get(name)); } } if (clearLocalDataDirectories) { cmdln.setForceVoltdbCreate(true); } else { cmdln.setForceVoltdbCreate(false); } ServerThread th = new ServerThread(cmdln); File root = VoltFile.getServerSpecificRoot(String.valueOf(hostId), clearLocalDataDirectories); cmdln.voltdbRoot(root + "/voltdbroot"); try { th.initialize(); } catch (VoltDB.SimulatedExitException expected) { } catch (Exception ex) { log.error("Failed to initialize cluster process:" + ex.getMessage(), ex); assert (false); } String hostIdStr = cmdln.getJavaProperty(clusterHostIdProperty); m_hostRoots.put(hostIdStr, cmdln.voltdbRoot().getAbsolutePath()); }
Source:
private int getChildrenPos(int elementStartPos) { if (getChildrenLenght(elementStartPos) == 0) { return -1; } else { return elementStartPos + HEADER_LENGTH + getValueLength(elementStartPos); } }

Target:
private int getChildrenPos(int elementStartPos) { if (getChildrenLength(elementStartPos) == 0) { return -1; } else { return elementStartPos + HEADER_LENGTH + getValueLength(elementStartPos); } }
Source:
@Override public void handleFailure() { }

Target:
public void handleFailure() { }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; if (httpRequest.getHeader(ORIGIN) == null) { chain.doFilter(request, response); return; } String requestOrigin = null; Enumeration<String> originHeaders = httpRequest.getHeaders(ORIGIN); if (originHeaders != null && originHeaders.hasMoreElements()) { String originHeaderValue = originHeaders.nextElement(); if (originHeaderValue != null && !originHeaderValue.equals("null")) { requestOrigin = originHeaderValue.split(",")[0]; } } if (allowAnyOrigin || OriginValidation.isAllowedOrigin(requestOrigin, allowedOrigins)) { httpResponse.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, requestOrigin); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_METHODS, DEFAULT_CORS_ACCESS_CONTROL_ALLOW_METHODS); httpResponse.addHeader(ACCESS_CONTROL_MAX_AGE, (72 * 60 * 60) + ""); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, DEFAULT_CORS_ACCESS_CONTROL_ALLOW_HEADERS); if (!isPreflightRequest((HttpServletRequest) request)) { chain.doFilter(request, response); } } else { httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); httpResponse.setContentLength(0); return; } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; String requestOrigin = httpRequest.getHeader(ORIGIN); if (requestOrigin == null) { chain.doFilter(request, response); return; } if (allowAnyOrigin || OriginValidation.isAllowedOrigin(requestOrigin, allowedOrigins)) { httpResponse.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, requestOrigin); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_METHODS, DEFAULT_CORS_ACCESS_CONTROL_ALLOW_METHODS); httpResponse.addHeader(ACCESS_CONTROL_MAX_AGE, (72 * 60 * 60) + ""); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, DEFAULT_CORS_ACCESS_CONTROL_ALLOW_HEADERS); if (!isPreflightRequest((HttpServletRequest) request)) { chain.doFilter(request, response); } } else { httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); httpResponse.setContentLength(0); return; } }
Source:
public ConstraintMatch deserialize(JsonParser parser, DeserializationContext context) throws IOException { try { JsonNode tree = parser.getCodec().readTree(parser); String constraintPackage = tree.get("constraintPackage").asText(); String constraintName = tree.get("constraintName").asText(); Score<?> score = DeserializationUtils.deserializePolymorphicProperty(context, tree, "score"); List<Object> justificationList = new ArrayList<>(); tree.get("justificationList").forEach((t) -> { try { justificationList.add(DeserializationUtils.deserializePolymorphicProperty(context, t, "justification")); } catch (Exception e) { throw new IllegalStateException(e); } }); return new ConstraintMatch(constraintPackage, constraintName, justificationList, score); } catch (ClassNotFoundException e) { throw new IllegalStateException("Cannot find class " + e.getClass().getName(), e); } }

Target:
public ConstraintMatch deserialize(JsonParser parser, DeserializationContext context) throws IOException { JsonNode tree = parser.getCodec().readTree(parser); String constraintPackage = tree.get("constraintPackage").asText(); String constraintName = tree.get("constraintName").asText(); Score<?> score = DeserializationUtils.deserializePolymorphicProperty(parser, context, tree, "score"); List<Object> justificationList = new ArrayList<>(); for (JsonNode t : tree.get("justificationList")) { justificationList.add(DeserializationUtils.deserializePolymorphicProperty(parser, context, t, "justification")); } return new ConstraintMatch(constraintPackage, constraintName, justificationList, score); }
Source:
protected boolean accepts(final HttpServletRequest request) { if (!super.accepts(request)) { log.debug("Not accepting request because it is not coming from the dispatcher."); return false; } try (ResourceResolver resourceResolver = resourceResolverFactory.getServiceResourceResolver(AUTH_INFO)) { PathInfo pathInfo = new PathInfo(request.getRequestURI()); Resource reqResource = resourceResolver.getResource(pathInfo.getResourcePath()); if (reqResource != null) { Resource childResource = reqResource.getChild(JcrConstants.JCR_CONTENT); if (childResource != null) { return verifyResourceType(childResource); } } } catch (LoginException e) { log.error("Could not get resource resolver", e); } return false; }

Target:
protected boolean accepts(final HttpServletRequest request) { if (!super.accepts(request)) { log.debug("Not accepting request because it is not coming from the dispatcher."); return false; } if (request instanceof SlingHttpServletRequest) { SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; Resource resource = getResource(slingRequest); return verifyResourceType(resource); } return false; }
Source:
protected Iterable<EntityStorageRecord> readBulkInternal(final Iterable<I> givenIds, FieldMask fieldMask) { final Map<I, EntityStorageRecord> storage = getStorage(); final Collection<EntityStorageRecord> result = new LinkedList<>(); TypeUrl typeUrl = null; for (I recordId : storage.keySet()) { for (I givenId : givenIds) { if (recordId.equals(givenId)) { final EntityStorageRecord.Builder matchingRecord = storage.get(recordId).toBuilder(); final Any state = matchingRecord.getState(); if (typeUrl == null) { typeUrl = TypeUrl.of(state.getTypeUrl()); } final Any processed = AnyPacker.pack( FieldMasks.applyIfValid( fieldMask, AnyPacker.unpack(state), typeUrl)); matchingRecord.setState(processed); result.add(matchingRecord.build()); continue; } result.add(null); } } return result; }

Target:
protected Iterable<EntityStorageRecord> readBulkInternal(final Iterable<I> givenIds, FieldMask fieldMask) { final Map<I, EntityStorageRecord> storage = getStorage(); final Collection<EntityStorageRecord> result = new LinkedList<>(); TypeUrl typeUrl = null; for (I recordId : storage.keySet()) { for (I givenId : givenIds) { if (recordId.equals(givenId)) { final EntityStorageRecord.Builder matchingRecord = storage.get(recordId).toBuilder(); final Any state = matchingRecord.getState(); if (typeUrl == null) { typeUrl = TypeUrl.of(state.getTypeUrl()); } final Message wholeState = AnyPacker.unpack(state); final Message maskedState = FieldMasks.applyIfValid(fieldMask, wholeState, typeUrl); final Any processed = AnyPacker.pack(maskedState); matchingRecord.setState(processed); result.add(matchingRecord.build()); } else { result.add(null); } } } return result; }
Source:
public void start() { int count = Runtime.getRuntime().availableProcessors(); if (count > 4) { count = count / 2; } if (count > 8) { count = 8; } ScheduledExecutorService[] execs = new ScheduledExecutorService[count]; for (int i = 0; i < count; i++) { execs[i] = Executors.newScheduledThreadPool(count, THREAD_FACTORY); } if (executor.compareAndSet(NONE, execs)) { for (ScheduledExecutorService exec : execs) { if (!NewThreadWorker.tryEnableCancelPolicy(exec)) { if (exec instanceof ScheduledThreadPoolExecutor) { NewThreadWorker.registerExecutor((ScheduledThreadPoolExecutor)exec); } } } } else { for (ScheduledExecutorService exec : execs) { exec.shutdownNow(); } } }

Target:
public void start() { int count = Runtime.getRuntime().availableProcessors(); if (count > 4) { count = count / 2; } if (count > 8) { count = 8; } ScheduledExecutorService[] execs = new ScheduledExecutorService[count]; for (int i = 0; i < count; i++) { execs[i] = Executors.newScheduledThreadPool(1, THREAD_FACTORY); } if (executor.compareAndSet(NONE, execs)) { for (ScheduledExecutorService exec : execs) { if (!NewThreadWorker.tryEnableCancelPolicy(exec)) { if (exec instanceof ScheduledThreadPoolExecutor) { NewThreadWorker.registerExecutor((ScheduledThreadPoolExecutor)exec); } } } } else { for (ScheduledExecutorService exec : execs) { exec.shutdownNow(); } } }
Source:
protected static void validateEnumVersionValue(Enum<?> enumValue, ExchangeVersion requestVersion) throws ServiceVersionException { Map<String, ExchangeVersion> enumVersionDict = enumVersionDictionaries .getMember().get(enumValue.getClass()); if (enumVersionDict.containsKey(enumValue.toString())) { ExchangeVersion enumVersion = enumVersionDict.get(enumValue .toString()); int i = requestVersion.compareTo(enumVersion); if (i < 0) { throw new ServiceVersionException(String.format("%S,%S,%S,%S", "Enumeration value %s in enumeration type %s is only valid for Exchange version %s or later.", enumValue.toString(), enumValue.getClass().getName(), enumVersion)); } } }

Target:
protected static void validateEnumVersionValue(Enum<?> enumValue, ExchangeVersion requestVersion) throws ServiceVersionException { Map<String, ExchangeVersion> enumVersionDict = enumVersionDictionaries .getMember().get(enumValue.getClass()); if (enumVersionDict.containsKey(enumValue.toString())) { ExchangeVersion enumVersion = enumVersionDict.get(enumValue .toString()); int i = requestVersion.compareTo(enumVersion); if (i < 0) { throw new ServiceVersionException( String.format("Enumeration value %s in enumeration type %s is only valid for Exchange version %s " + "or later.", enumValue.toString(), enumValue.getClass().getName(), enumVersion)); } } }
Source:
private void updateBecauseYouRead() { for (Card card : cards) { if (card instanceof BecauseYouReadCard) { cards.remove(card); } } new MainPageReadMoreTopicTask(getActivity()) { @Override public void onFinish(final PageTitle title) { try { byrClient.get(title.getText(), new BecauseYouReadClient.BecauseYouReadCallback() { @Override public void success(MwQueryResponse<BecauseYouReadClient.Pages> pages) { if (!isAdded()) { return; } if (!pages.hasError() && pages.query() != null && pages.query().results() != null) { SearchResults results = SearchResults.filter(pages.query().results(), title.getText(), false); List<BecauseYouReadItemCard> itemCards = MwApiResultPage.searchResultsToCards(results); cards.add(new BecauseYouReadCard(title.getText(), itemCards)); feedView.update(); } } @Override public void failure(Throwable t) { L.w("Error fetching 'because you read' suggestions", t); } }); } catch (IOException e) { L.w("Error fetching 'because you read' suggestions", e); } } @Override public void onCatch(Throwable caught) { L.w("Error getting history entry for 'because you read' card", caught); } }.execute(); }

Target:
private void updateBecauseYouRead() { for (Card card : cards) { if (card instanceof BecauseYouReadCard) { cards.remove(card); } } new BecauseYouReadTopicTask(getActivity(), this, byrClient).execute(); }
Source:
public Player(int playerId){ super("Player " + playerId); this.playerId = playerId; powerups = new ArrayList<Powerup>(); addedBombs = 0; addedBombRange = 0; invulnerableTill = 0; immuneToBombs = false; factory = new BombFactory(); }

Target:
public Player(int playerId){ super("Player " + playerId); this.playerId = playerId; invulnerableTill = 0; immuneToBombsTill = 0; factory = new BombFactory(); }
Source:
public List<FieldVariable> byFieldVariableKey(final String key) throws DotDataException { DotConnect dc = new DotConnect(); dc.setSQL(sql.selectFieldVarByKey); dc.addParam(key); List<Map<String, Object>> results = dc.loadObjectResults(); if (results.size() == 0) { return Collections.emptyList(); } return new DbFieldVariableTransformer(dc.loadObjectResults()).asList(); }

Target:
public List<FieldVariable> byFieldVariableKey(final String key) throws DotDataException { final DotConnect dc = new DotConnect(); dc.setSQL(sql.selectFieldVarByKey); dc.addParam(key); final List<Map<String, Object>> results = dc.loadObjectResults(); return UtilMethods.isSet(results) ? new DbFieldVariableTransformer(dc.loadObjectResults()) .asList() : Collections.emptyList(); }
Source:
private void setRepairLogTruncationHandle(long newHandle) { if (newHandle < m_repairLogTruncationHandle) { throw new RuntimeException("Updating truncation point from " + TxnEgo.debugTxnId(m_repairLogTruncationHandle) + "to" + TxnEgo.debugTxnId(newHandle)); } assert newHandle >= m_repairLogTruncationHandle; if (newHandle > m_repairLogTruncationHandle) { m_repairLogTruncationHandle = newHandle; if (! m_isLeader) { return; } if (m_defaultConsistencyReadLevel == ReadLevel.SAFE) { m_bufferedReadLog.releaseBufferedReads(m_mailbox, m_repairLogTruncationHandle); } scheduleRepairLogTruncateMsg(); } }

Target:
private void setRepairLogTruncationHandle(long newHandle) { if (newHandle < m_repairLogTruncationHandle) { throw new RuntimeException("Updating truncation point from " + TxnEgo.txnIdToString(m_repairLogTruncationHandle) + "to" + TxnEgo.txnIdToString(newHandle)); } if (newHandle > m_repairLogTruncationHandle) { m_repairLogTruncationHandle = newHandle; if (! m_isLeader) { return; } if (m_defaultConsistencyReadLevel == ReadLevel.SAFE) { m_bufferedReadLog.releaseBufferedReads(m_mailbox, m_repairLogTruncationHandle); } scheduleRepairLogTruncateMsg(); } }
Source:
public JavaScriptParseSpec( @JsonProperty("timestampSpec") TimestampSpec timestampSpec, @JsonProperty("dimensionsSpec") DimensionsSpec dimensionsSpec, @JsonProperty("function") String function, @JacksonInject JavaScriptConfig config ) { super(timestampSpec, dimensionsSpec); Preconditions.checkState(config.isEnabled(), "JavaScript is disabled"); this.function = function; this.config = config; }

Target:
public JavaScriptParseSpec( @JsonProperty("timestampSpec") TimestampSpec timestampSpec, @JsonProperty("dimensionsSpec") DimensionsSpec dimensionsSpec, @JsonProperty("function") String function, @JacksonInject JavaScriptConfig config ) { super(timestampSpec, dimensionsSpec); this.function = function; this.config = config; }
Source:
public Map<String, String> toConfig(Config jobConfig) { validate(); Map<String, String> tableConfig = new HashMap<>(config); tableConfig.put( String.format(JavaTableConfig.TABLE_PROVIDER_FACTORY, tableId), getProviderFactoryClassName()); generateConfig(jobConfig, tableConfig); return Collections.unmodifiableMap(tableConfig); }

Target:
public Map<String, String> toConfig(Config jobConfig) { validate(); Map<String, String> tableConfig = new HashMap<>(config); tableConfig.put( String.format(JavaTableConfig.TABLE_PROVIDER_FACTORY, tableId), getProviderFactoryClassName()); return Collections.unmodifiableMap(tableConfig); }
Source:
protected ServiceRegistration<?> unregisterService(final String interfaceName) { ServiceRegistration<?> reg = null; List<ServiceRegistration<?>> regList = registeredServices.remove(interfaceName); if (regList != null) { reg = regList.get(0); registeredServices.get(interfaceName).forEach(r -> r.unregister()); registeredServices.remove(interfaceName); } return reg; }

Target:
protected ServiceRegistration<?> unregisterService(final String interfaceName) { ServiceRegistration<?> reg = null; List<ServiceRegistration<?>> regList = registeredServices.get(interfaceName); if (regList != null) { reg = regList.get(0); regList.forEach(r -> r.unregister()); registeredServices.remove(interfaceName); } return reg; }
Source:
public Collection<FormElementFilter> provideFilters(String elementUUID, Object definition) { Predicate predicate = o -> isParentAnEventSubProcess(elementUUID) && isInterruptingEnabled(elementUUID); FormElementFilter isInterruptingFilter = new FormElementFilter("executionSet.isInterrupting", predicate); return Collections.singletonList(isInterruptingFilter); }

Target:
public Collection<FormElementFilter> provideFilters(String elementUUID, Object definition) { Predicate parentPredicate = o -> isParentAnEventSubProcess(elementUUID); Predicate isInterruptingPredicate = o -> isInterruptingEnabled(elementUUID); Predicate predicate = parentPredicate.and(isInterruptingPredicate); FormElementFilter isInterruptingFilter = new FormElementFilter("executionSet.isInterrupting", parentPredicate.and(predicate)); return Collections.singletonList(isInterruptingFilter); }
Source:
public Command getCommand() { return null; }

Target:
public Command getCommand() { return this.currentCommand; }
Source:
public SerializationContext getGlobalCtx() { synchronized (global) { return global.ctx; } }

Target:
public ImmutableSerializationContext getGlobalCtx() { synchronized (global) { return global.ctx; } }
Source:
private int totalFileCount(File inputFile) throws IOException { if (inputFile.isDirectory()) { int currentFileCount = 0; try (DirectoryStream<Path> stream = Files.newDirectoryStream(inputFile.toPath())) { return (int) StreamSupport.stream(stream.spliterator(), false) .map(Path::toFile) .filter(file -> !file.isHidden()) .count(); } } return inputFile.isHidden() ? 0 : 1; }

Target:
private int totalFileCount(File inputFile) throws IOException { if (inputFile.isDirectory()) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(inputFile.toPath())) { return (int) StreamSupport.stream(stream.spliterator(), false) .map(Path::toFile) .filter(file -> !file.isHidden()) .count(); } } return inputFile.isHidden() ? 0 : 1; }
Source:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null); }

Target:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null, null); }
Source:
public Object getTransactionId() { throw LOG.transactionIdIsNull(); }

Target:
public Object getTransactionId() { throw LOG.transactionIdIsNotAvailable(); }
Source:
public BasicAuthentication() throws Exception { File passwdFile = new File(HTPASSWD_FILE); if (passwdFile.exists() && passwdFile.isFile()) { BufferedReader reader = new BufferedReader(new FileReader(passwdFile)); String line = reader.readLine(); while (line != null) { String[] values = line.split(":", 2); if (values.length == 2) { users.put(values[0], values[1]); } line = reader.readLine(); } } }

Target:
public BasicAuthentication() throws IOException { File passwdFile = new File(HTPASSWD_FILE); if (passwdFile.exists() && passwdFile.isFile()) { try (BufferedReader reader = new BufferedReader(new FileReader(passwdFile))) { String line = reader.readLine(); while (line != null) { String[] values = line.split(":", 2); if (values.length == 2) { users.put(values[0], values[1]); } line = reader.readLine(); } } } }
Source:
public void getFCStorageTypeForLun() throws Exception { LUNs lun = new LUNs(); ArrayList<storage_server_connections> connections = new ArrayList<storage_server_connections>(); lun.setLunConnections(connections); StorageType storageType = command.getLUNStorageType(lun); assertEquals("Lun disk should be of FC storage type since it does not had connections", storageType, storageType.FCP); }

Target:
public void getFCStorageTypeForLun() throws Exception { LUNs lun = new LUNs(); ArrayList<storage_server_connections> connections = new ArrayList<storage_server_connections>(); lun.setLunConnections(connections); StorageType storageType = command.getLUNStorageType(lun); assertEquals("Lun disk should be of FC storage type since it does not had connections", StorageType.FCP, storageType); }
Source:
private void createBinaryOnlyDataSet() { realm.beginTransaction(); realm.delete(BinaryOnly.class); for (byte[] binary : binaries) { BinaryOnly binaryOnly = realm.createObject(BinaryOnly.class); binaryOnly.setBinary(binary); } realm.commitTransaction(); }

Target:
private void createBinaryOnlyDataSet() { realm.beginTransaction(); for (int i = 0; i < binaries.length; i++) { AllJavaTypes binaryOnly = new AllJavaTypes((long) i); binaryOnly.setFieldBinary(binaries[i]); realm.copyToRealm(binaryOnly); } realm.commitTransaction(); }
Source:
public String asString() { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : this.arguments.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()); } return "@" + this.type.getId() + "[" + sb.toString() + "]"; }

Target:
public String asString() { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : this.arguments.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()).append(","); } return "@" + this.type.getId() + "[" + sb.deleteCharAt(sb.length()-1).toString() + "]"; }
Source:
public String locate(String name, StatementContext ctx) { final Object cache_key; boolean isSqlObjectMethod = false; if (ctx.getSqlObjectType() != null) { if (ctx.getSqlObjectMethod() != null) { isSqlObjectMethod = true; cache_key = ctx.getSqlObjectMethod(); } else { cache_key = '/' + mungify(ctx.getSqlObjectType().getName() + '.' + name) + ".sql"; } } else { cache_key = name; } String cached = found.get(cache_key); if (cached != null) { return cached; } if (looksLikeSql(name)) { if (isSqlObjectMethod) { found.put(cache_key, name); } return name; } final ClassLoader loader = selectClassLoader(); InputStream in_stream = null; try { in_stream = loader.getResourceAsStream(name); if (in_stream == null) { in_stream = loader.getResourceAsStream(name + ".sql"); } if (in_stream == null && ctx.getSqlObjectType() != null) { String filename = '/' + mungify(ctx.getSqlObjectType().getName() + '.' + name) + ".sql"; in_stream = loader.getResourceAsStream(filename); if (in_stream == null) { in_stream = ctx.getSqlObjectType().getResourceAsStream(filename); } } if (in_stream == null) { found.put(cache_key, name == cache_key ? new String(name) : name); return name; } String sql; try { sql = SQL_SCRIPT_PARSER.parse(new ANTLRInputStream(in_stream)); } catch (IOException e) { throw new UnableToCreateStatementException(e.getMessage(), e, ctx); } found.put(cache_key, sql); return sql; } finally { try { if (in_stream != null) { in_stream.close(); } } catch (IOException e) { } } }

Target:
public String locate(String name, StatementContext ctx) { final CacheKey cache_key = new CacheKey(name, ctx.getSqlObjectType(), ctx.getSqlObjectMethod()); boolean isSqlObjectMethod = ctx.getSqlObjectType() != null && ctx.getSqlObjectMethod() != null; String cached = found.get(cache_key); if (cached != null) { return cached; } if (looksLikeSql(name)) { if (isSqlObjectMethod) { found.put(cache_key, name); } return name; } final ClassLoader loader = selectClassLoader(); InputStream in_stream = null; try { in_stream = loader.getResourceAsStream(name); if (in_stream == null) { in_stream = loader.getResourceAsStream(name + ".sql"); } if (in_stream == null && ctx.getSqlObjectType() != null) { String filename = '/' + mungify(ctx.getSqlObjectType().getName() + '.' + name) + ".sql"; in_stream = loader.getResourceAsStream(filename); if (in_stream == null) { in_stream = ctx.getSqlObjectType().getResourceAsStream(filename); } } if (in_stream == null) { found.put(cache_key, isSqlObjectMethod ? name : new String(name)); return name; } String sql; try { sql = SQL_SCRIPT_PARSER.parse(new ANTLRInputStream(in_stream)); } catch (IOException e) { throw new UnableToCreateStatementException(e.getMessage(), e, ctx); } found.put(cache_key, sql); return sql; } finally { try { if (in_stream != null) { in_stream.close(); } } catch (IOException e) { } } }
Source:
public void onShow(final Map<String, Object> data) { roleForPlayers.clear(); factionGrid .getChildren() .removeIf( node -> { final Integer row = GridPane.getRowIndex(node); return row != null && row > 0; }); gameData = (GameData) Optional.ofNullable(data.get(SELECTED_MAP_KEY)) .orElseThrow( () -> new IllegalStateException("Missing GameData when calling screen")); final List<String> availablePlayers = List.of(PlayerType.playerTypes()); for (final GamePlayer playerId : gameData.getPlayerList()) { final var name = new Label(playerId.getName()); final ComboBox<String> controllingPlayer = new ComboBox<>(FXCollections.observableArrayList(availablePlayers)); controllingPlayer.getSelectionModel().select(0); if (playerId.getCanBeDisabled()) { controllingPlayer.getItems().add(DISABLE_TEXT); } roleForPlayers.put(playerId, controllingPlayer); final Collection<String> playerAlliances = gameData.getAllianceTracker().getAlliancesPlayerIsIn(playerId); final var faction = new Button(playerAlliances.toString()); faction.setOnAction( e -> { final int targetIndex = controllingPlayer.getSelectionModel().getSelectedIndex(); playerAlliances.stream() .map(gameData.getAllianceTracker()::getPlayersInAlliance) .flatMap(Collection::stream) .map(roleForPlayers::get) .filter(stringComboBox -> stringComboBox.getItems().size() > targetIndex) .map(ComboBox::getSelectionModel) .forEach(selectionModel -> selectionModel.select(targetIndex)); }); final var income = new Spinner<Integer>(0, 100, 100); income.setDisable(true); incomeForPlayers.put(playerId, income); final var pus = new Spinner<Integer>(0, 100, 0); pus.setDisable(true); pusForPlayers.put(playerId, pus); factionGrid.addRow(factionGrid.getRowCount(), name, controllingPlayer, faction, income, pus); } }

Target:
public void onShow(final Map<String, Object> data) { roleForPlayers.clear(); incomeForPlayers.clear(); pusForPlayers.clear(); factionGrid .getChildren() .removeIf( node -> { final Integer row = GridPane.getRowIndex(node); return row != null && row > 0; }); gameData = (GameData) Optional.ofNullable(data.get(SELECTED_MAP_KEY)) .orElseThrow( () -> new IllegalStateException("Missing GameData when calling screen")); final List<String> availablePlayers = List.of(PlayerType.playerTypes()); for (final GamePlayer gamePlayer : gameData.getPlayerList()) { setupPlayerControl(availablePlayers, gamePlayer); } }
Source:
public PrettyPrinterConfiguration setTabWidth(int tabWidth) { if (tabWidth <= 0) { throw new IllegalArgumentException("Tab width must be > 0"); } this.tabWidth = tabWidth; return this; }

Target:
public PrettyPrinterConfiguration setTabWidth(int tabWidth) { this.tabWidth = assertPositive(tabWidth); return this; }
Source:
public void save() { if (driver.getCurrentUrl().contains("configure")) { clickButton("Save"); } else { clickButton("OK"); } assertThat(driver, not(hasContent("This page expects a form submission"))); }

Target:
public void save() { if (this.onDomainConfigurationPage()) { clickButton("Save"); } else { clickButton("OK"); } assertThat(driver, not(hasContent("This page expects a form submission"))); }
Source:
public void onExpandVariable(Variable variable) { Debugger debugger = debuggerManager.getActiveDebugger(); if (debugger != null && debugger.isSuspended()) { Promise<? extends SimpleValue> promise = debugger.getValue(variable, view.getSelectedThreadId(), view.getSelectedFrameIndex()); promise .then( value -> { MutableVariable updatedVariable = new MutableVariableImpl(variable); updatedVariable.setValue(value); view.expandVariable(updatedVariable); }) .catchError( error -> { Log.error(DebuggerPresenter.class, error.getCause()); }); } }

Target:
public void onExpandVariable(Variable variable) { Debugger debugger = debuggerManager.getActiveDebugger(); if (debugger != null && debugger.isSuspended()) { Promise<? extends SimpleValue> promise = debugger.getValue(variable, view.getSelectedThreadId(), view.getSelectedFrameIndex()); promise .then( value -> { MutableVariable updatedVariable = variable instanceof MutableVariable ? ((MutableVariable) variable) : new MutableVariableImpl(variable); updatedVariable.setValue(value); view.expandVariable(updatedVariable); }) .catchError( error -> { Log.error(DebuggerPresenter.class, error.getCause()); }); } }
Source:
public boolean testDouble(double value) { if (Double.isNaN(value)) { return nanAllowed; } for (TupleDomainFilter filter : filters) { if ((nanAllowed && Double.isNaN(value)) || filter.testDouble(value)) { return true; } } return false; }

Target:
public boolean testDouble(double value) { if (Double.isNaN(value)) { return nanAllowed; } for (TupleDomainFilter filter : filters) { if (filter.testDouble(value)) { return true; } } return false; }
Source:
void verifyBlankLinesAroundFunction(FunctionDeclarationContext ctx) { DeclarationContext declCtx = (DeclarationContext) ctx.getParent(); ParseTree left = ParseTreeUtil.getLeftNode(declCtx); if (left != null) { Token start = declCtx.getStart(); List<Token> tokens = tokenStream.getHiddenTokensToLeft(start.getTokenIndex()); long numberOfNewlineChars = 0; if (tokens != null) { numberOfNewlineChars = tokens.stream().filter(token -> token.getText().equals("\n")).count(); } if (numberOfNewlineChars < 2) { printer.error(Messages.FUNCTION + Messages.BLANK_LINE_BEFORE, ListenerUtil.getTokenLocation(start)); } } ParseTree right = ParseTreeUtil.getRightNode(declCtx); if (right != null) { if (right.getText().equals("<EOF>")) { return; } Token end = declCtx.getStop(); long numberOfNewlineChars = 0; List<Token> tokens = tokenStream.getHiddenTokensToRight(end.getTokenIndex()); if (tokens != null) { numberOfNewlineChars = tokens.stream().filter(token -> token.getText().equals("\n")).count(); } if (numberOfNewlineChars < 2) { printer.error(Messages.FUNCTION + Messages.BLANK_LINE_AFTER, ListenerUtil.getTokenEndLocation(end)); } } }

Target:
void verifyBlankLinesAroundFunction(FunctionDeclarationContext ctx) { DeclarationContext declCtx = (DeclarationContext) ctx.getParent(); ParseTree left = ParseTreeUtil.getLeftNode(declCtx); if (left != null) { Token start = declCtx.getStart(); List<Token> tokens = tokenStream.getHiddenTokensToLeft(start.getTokenIndex()); if (getNumberOfBlankLines(tokens) < 1) { printer.error(Messages.FUNCTION + Messages.BLANK_LINE_BEFORE, ListenerUtil.getTokenLocation(start)); } } ParseTree right = ParseTreeUtil.getRightNode(declCtx); if (right != null) { if (right.getText().equals("<EOF>")) { return; } Token end = declCtx.getStop(); List<Token> tokens = tokenStream.getHiddenTokensToRight(end.getTokenIndex()); if (getNumberOfBlankLines(tokens) < 1) { printer.error(Messages.FUNCTION + Messages.BLANK_LINE_AFTER, ListenerUtil.getTokenEndLocation(end)); } } }
Source:
public List<Map<String, Object>> getAlerts() { List<Map<String, Object>> alerts = new ArrayList<>(); try { List<Map<String, Object>> results = persistentStore.get("alerts", activeAlertQuery); if (!results.isEmpty()) { for (Map<String, Object> item : results) { item = PersistentItem.stripSuffixes(item); if (item.get(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY) instanceof String) { item.put( SystemNotice.SYSTEM_NOTICE_DETAILS_KEY, Collections.singleton(item.get(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY))); } escapeStrings(item); alerts.add(item); } } } catch (PersistenceException pe) { LOGGER.debug("Error retrieving system alert.", pe); return Collections.singletonList( new Alert( "solr", NoticePriority.CRITICAL, "Persistent Storage Not Responding. Could Not Retrieve Alerts.", Collections.singleton( "Critical alerts may be present, but not displayed because the persistent storage is not responding.")) .getProperties()); } alerts.sort( (map1, map2) -> new Alert(map1).getPriority().value() >= new Alert(map2).getPriority().value() ? -1 : 1); return alerts; }

Target:
public List<Map<String, Object>> getAlerts() { List<Map<String, Object>> alerts = new ArrayList<>(); try { List<Map<String, Object>> results = persistentStore.get("alerts", activeAlertQuery); if (!results.isEmpty()) { for (Map<String, Object> item : results) { item = PersistentItem.stripSuffixes(item); if (item.get(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY) instanceof String) { item.put( SystemNotice.SYSTEM_NOTICE_DETAILS_KEY, Collections.singleton(item.get(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY))); } escapeStrings(item); alerts.add(item); } } } catch (PersistenceException pe) { LOGGER.debug("Error retrieving system alert.", pe); return Collections.singletonList( new Alert( "unable_to_retrieve_alerts", NoticePriority.CRITICAL, "Persistent Storage Not Responding. Could Not Retrieve Alerts.", Collections.singleton( "Critical alerts may be present, but not displayed because the persistent storage is not responding.")) .getProperties()); } alerts.sort( (map1, map2) -> new Alert(map1).getPriority().value() >= new Alert(map2).getPriority().value() ? -1 : 1); return alerts; }
Source:
public GroupList call() throws Exception { final IdentifiedUser user = identifiedUser.get(); final List<AccountGroup> list; if (user.getCapabilities().canAdministrateServer()) { list = new LinkedList<AccountGroup>(); for (final AccountGroup group : groupCache.all()) { list.add(group); } } else { list = new ArrayList<AccountGroup>(); for(final AccountGroup group : groupCache.all()) { final GroupControl c = groupControlFactory.controlFor(group); if (c.isVisible()) { list.add(c.getAccountGroup()); } } } List<GroupDetail> l = new ArrayList<GroupDetail>(); for(AccountGroup group : list) { l.add(groupDetailFactory.create(group.getId()).call()); } GroupList res = new GroupList(); res.setGroups(l); res.setCanCreateGroup(user.getCapabilities().canCreateGroup()); return res; }

Target:
public GroupList call() throws Exception { final IdentifiedUser user = identifiedUser.get(); final List<AccountGroup> list = new ArrayList<AccountGroup>(); if (user.getCapabilities().canAdministrateServer()) { CollectionUtils.addAll(list, groupCache.all().iterator()); } else { for(final AccountGroup group : groupCache.all()) { final GroupControl c = groupControlFactory.controlFor(group); if (c.isVisible()) { list.add(c.getAccountGroup()); } } } List<GroupDetail> l = new ArrayList<GroupDetail>(); for(AccountGroup group : list) { l.add(groupDetailFactory.create(group.getId()).call()); } return new GroupList(l, user.getCapabilities().canCreateGroup()); }