auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onClick(View view) { Intent intent = new Intent(); switch (view.getId()) { case R.id.nav_item_today: ((PageActivity)getActivity()).displayMainPage(); break; case R.id.nav_item_history: ((PageActivity)getActivity()).pushFragment(new HistoryFragment()); break; case R.id.nav_item_saved_pages: ((PageActivity)getActivity()).pushFragment(new SavedPagesFragment()); break; case R.id.nav_item_nearby: ((PageActivity)getActivity()).pushFragment(new NearbyFragment()); break; case R.id.nav_item_more: intent.setClass(this.getActivity(), SettingsActivity.class); startActivityForResult(intent, SettingsActivity.ACTIVITY_REQUEST_SHOW_SETTINGS); break; case R.id.nav_item_login: intent.setClass(this.getActivity(), LoginActivity.class); intent.putExtra(LoginActivity.LOGIN_REQUEST_SOURCE, LoginFunnel.SOURCE_NAV); startActivity(intent); break; case R.id.nav_item_random: if (app.getReleaseType() == WikipediaApp.RELEASE_BETA){ ((PageActivity)getActivity()).pushFragment(new RandomFragment()); } else { randomHandler.doVisitRandomArticle(); } break; default: throw new RuntimeException("Unknown ID clicked!"); } }

Target:
public void onClick(View view) { Intent intent = new Intent(); switch (view.getId()) { case R.id.nav_item_today: ((PageActivity)getActivity()).displayMainPage(); break; case R.id.nav_item_history: ((PageActivity)getActivity()).pushFragment(new HistoryFragment()); break; case R.id.nav_item_saved_pages: ((PageActivity)getActivity()).pushFragment(new SavedPagesFragment()); break; case R.id.nav_item_nearby: ((PageActivity)getActivity()).pushFragment(new NearbyFragment()); break; case R.id.nav_item_more: intent.setClass(this.getActivity(), SettingsActivity.class); startActivityForResult(intent, SettingsActivity.ACTIVITY_REQUEST_SHOW_SETTINGS); break; case R.id.nav_item_login: intent.setClass(this.getActivity(), LoginActivity.class); intent.putExtra(LoginActivity.LOGIN_REQUEST_SOURCE, LoginFunnel.SOURCE_NAV); startActivity(intent); break; case R.id.nav_item_random: if (app.getReleaseType() != WikipediaApp.RELEASE_PROD){ ((PageActivity)getActivity()).pushFragment(new RandomFragment()); } else { randomHandler.doVisitRandomArticle(); } break; default: throw new RuntimeException("Unknown ID clicked!"); } }
Source:
public void onChildRemoved(Object parentElement, Object childElement) { Integer parentNodeId = mObjectIdMapper.getIdForObject(parentElement); Integer childNodeId = mObjectIdMapper.getIdForObject(childElement); if (parentNodeId == null || childNodeId == null) { LogUtil.w( "DOM.onChildRemoved() called for a non-mapped node: " + "parentElement=(nodeId=%s, %s), childElement=(nodeId=%s, %s)", parentNodeId, parentElement, childNodeId, childElement); } else { ChildNodeRemovedEvent message = new ChildNodeRemovedEvent(); message.parentNodeId = parentNodeId; message.nodeId = childNodeId; mPeerManager.sendNotificationToPeers("DOM.childNodeRemoved", message); } removeElementTree(childElement); }

Target:
public void onChildRemoved(Object parentElement, Object childElement) { Integer parentNodeId = mObjectIdMapper.getIdForObject(parentElement); Integer childNodeId = mObjectIdMapper.getIdForObject(childElement); if (parentNodeId == null || childNodeId == null) { LogUtil.d( "DOM.onChildRemoved() called for a non-mapped node: " + "parentElement=(nodeId=%s, %s), childElement=(nodeId=%s, %s)", parentNodeId, parentElement, childNodeId, childElement); } else { ChildNodeRemovedEvent message = new ChildNodeRemovedEvent(); message.parentNodeId = parentNodeId; message.nodeId = childNodeId; mPeerManager.sendNotificationToPeers("DOM.childNodeRemoved", message); } removeElementTree(childElement); }
Source:
public OzoneAcl(ACLIdentityType type, String name, BitSet acls) { Objects.requireNonNull(type); Objects.requireNonNull(acls); if(acls.cardinality() > ACLType.getNoOfAcls()) { throw new IllegalArgumentException("Acl bitset passed has unexpected " + "size. bitset size:" + acls.cardinality() + ", bitset:" + acls.toString()); } this.aclBitSet = new BitSet(); acls.stream().forEach(a -> aclBitSet.set(a)); this.name = name; this.type = type; if (type == ACLIdentityType.WORLD && name.length() != 0) { throw new IllegalArgumentException("Unexpected name part in world type"); } if (((type == ACLIdentityType.USER) || (type == ACLIdentityType.GROUP)) && (name.length() == 0)) { throw new IllegalArgumentException("User or group name is required"); } }

Target:
public OzoneAcl(ACLIdentityType type, String name, BitSet acls) { Objects.requireNonNull(type); Objects.requireNonNull(acls); if(acls.cardinality() > ACLType.getNoOfAcls()) { throw new IllegalArgumentException("Acl bitset passed has unexpected " + "size. bitset size:" + acls.cardinality() + ", bitset:" + acls.toString()); } this.aclBitSet = (BitSet) acls.clone(); acls.stream().forEach(a -> aclBitSet.set(a)); this.name = name; this.type = type; if (type == ACLIdentityType.WORLD && name.length() != 0) { throw new IllegalArgumentException("Unexpected name part in world type"); } if (((type == ACLIdentityType.USER) || (type == ACLIdentityType.GROUP)) && (name.length() == 0)) { throw new IllegalArgumentException("User or group name is required"); } }
Source:
private static TopologyDef loadYaml(Yaml yaml, InputStream in, Properties properties, boolean envSubstitution) { LOG.info("loading YAML from input stream..."); StringBuilder bos = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); reader.lines().forEach(line -> { Matcher m = propertyPattern.matcher(line); if (m.find()) { String target = "${" + m.group("var") + "}"; Optional<String> replacement = getPropertyReplacement(properties, m, envSubstitution); replacement.ifPresent(propValue -> bos.append(line.replace(target, propValue))); if (!replacement.isPresent()) { LOG.warn("Could not found replacement for property: " + m.group("var")); bos.append(line); } } else { bos.append(line); } bos.append(System.lineSeparator()); }); return (TopologyDef) yaml.load(bos.toString()); }

Target:
private static TopologyDef loadYaml(Yaml yaml, InputStream in, Properties properties, boolean envSubstitution) throws IOException { LOG.info("loading YAML from input stream..."); try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { String conf = reader.lines().map(line -> { Matcher m = propertyPattern.matcher(line); return m.find() ? getPropertyReplacement(properties, m, envSubstitution) .map(propValue -> line.replace("${" + m.group("var") + "}", propValue)) .orElseGet(() -> { LOG.warn("Could not find replacement for property: " + m.group("var")); return line; }) : line; }).collect(Collectors.joining(System.lineSeparator())); return (TopologyDef) yaml.load(conf); } }
Source:
public HelixRestServer(String zkAddr, int port, String urlPrefix) { this(zkAddr, port, urlPrefix, Collections.emptyList()); }

Target:
public HelixRestServer(String zkAddr, int port, String urlPrefix) { this(zkAddr, port, urlPrefix, Collections.<AuditLogger>emptyList()); }
Source:
public void close() throws IOException { if (watchService != null) { watchService.close(); } watchers.clear(); }

Target:
public void close() throws IOException { for (WatchKey key : watchers.keySet()) { key.cancel(); } watchers.clear(); watchService.close(); }
Source:
public static void assertEqualsByteArray(byte[] expected,byte[] current){ for(int k = 0; k < expected.length; k++){ assertEquals(expected[k], current[k]); } }

Target:
public static void assertEqualsByteArray(byte[] expected,byte[] current){ assertEquals("Byte arrays' lengths not the same", expected.length , current.length); for(int k = 0; k < expected.length; k++){ assertEquals(k + "th index not equal" , expected[k] , current[k]); } }
Source:
public boolean exec() throws CliException { String path = args[1]; String aclStr = args[2]; List<ACL> acl = AclParser.parse(aclStr); int version; if (cl.hasOption("v")) { version = Integer.parseInt(cl.getOptionValue("v")); } else { version = -1; } try { if (cl.hasOption("R")) { ZKUtil.visitSubTreeDFS(zk, path, false, new StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { try { zk.setACL(path, acl, version); } catch (KeeperException | InterruptedException e) { out.print(e.getMessage()); } } }); } else { Stat stat = zk.setACL(path, acl, version); if (cl.hasOption("s")) { new StatPrinter(out).print(stat); } } } catch (IllegalArgumentException ex) { throw new MalformedPathException(ex.getMessage()); } catch (KeeperException|InterruptedException ex) { throw new CliWrapperException(ex); } return false; }

Target:
public boolean exec() throws CliException { String path = args[1]; String aclStr = args[2]; List<ACL> acl = AclParser.parse(aclStr); int version; if (cl.hasOption("v")) { version = Integer.parseInt(cl.getOptionValue("v")); } else { version = -1; } try { if (cl.hasOption("R")) { ZKUtil.visitSubTreeDFS(zk, path, false, new StringCallback() { @Override public void processResult(int rc, String p, Object ctx, String name) { try { zk.setACL(p, acl, version); } catch (KeeperException | InterruptedException e) { out.print(e.getMessage()); } } }); } else { Stat stat = zk.setACL(path, acl, version); if (cl.hasOption("s")) { new StatPrinter(out).print(stat); } } } catch (IllegalArgumentException ex) { throw new MalformedPathException(ex.getMessage()); } catch (KeeperException|InterruptedException ex) { throw new CliWrapperException(ex); } return false; }
Source:
public void requestNewAccessToken() { AccessTokenDTO newToken = callConcurEndpoint( this::callRequestAccessTokenEndpoint, AccessTokenDTO.class); setWebserivceCredentialValues(newToken.getToken(), newToken.getExpirationDate(), newToken.getRefreshToken()); }

Target:
public void requestNewAccessToken() { AccessTokenDTO newToken = callConcurEndpoint( this::buildRequestAccessTokenClientRequest, AccessTokenDTO.class); setWebserivceCredentialValues(newToken.getToken(), newToken.getExpirationDate(), newToken.getRefreshToken()); }
Source:
private LifecycleInjector createInjector(List<Module> modules, List<Module> overrides) { return InjectorBuilder.fromModules(modules).overrideWith(overrides).createInjector(); }

Target:
protected LifecycleInjector createInjector(List<Module> modules, List<Module> overrides) { return InjectorBuilder.fromModules(modules).overrideWith(overrides).createInjector(); }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_browse_image, container, false); ButterKnife.bind(this, rootView); if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { depictionsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); } else { depictionsRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2)); } ArrayList<DepictedItem> items = new ArrayList<>(); depictionsAdapter = adapterFactory.create(items); depictionsRecyclerView.setAdapter(depictionsAdapter); depictionsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (!recyclerView.canScrollVertically(1)) { addDepictionsToList(query); } } }); return rootView; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_browse_image, container, false); ButterKnife.bind(this, rootView); if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { layoutManager = new LinearLayoutManager(getContext()); } else { layoutManager = new GridLayoutManager(getContext(), 2); } depictionsRecyclerView.setLayoutManager(layoutManager); depictionsAdapter = adapterFactory.create(); depictionsRecyclerView.setAdapter(depictionsAdapter); depictionsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int visibleItemCount = layoutManager.getChildCount(); int totalItemCount = layoutManager.getItemCount(); int firstVisibleItemPosition=0; if(layoutManager instanceof GridLayoutManager){ firstVisibleItemPosition=((GridLayoutManager) layoutManager).findFirstVisibleItemPosition(); } else { firstVisibleItemPosition=((LinearLayoutManager)layoutManager).findFirstVisibleItemPosition(); } if (!isLoading && !isLastPage) { if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0 && totalItemCount >= PAGE_SIZE) { loadMoreItems(false); } } } }); return rootView; }
Source:
public void testRemoveValueUnequalStoreEntryEqualCacheWriterEntry() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(realStore); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "value")); final Ehcache<String, String> ehcache = this.getEhcache(realCache); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(realStore.getMap().get("key"), is(equalTo("unequalValue"))); assertThat(realCache.getEntries().get("key"), is(equalTo("value"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }

Target:
public void testRemoveValueUnequalStoreEntryEqualCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(fakeStore); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "value")); final Ehcache<String, String> ehcache = this.getEhcache(fakeWriter); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }
Source:
public Task<Void> delete(@NonNull Activity activity) { FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (firebaseUser == null) { return Tasks.forException(new Exception("No currently signed in user.")); } Task<Void> deleteUserTask = firebaseUser.delete(); GoogleApiClientTaskHelper gacHelper = GoogleApiClientTaskHelper.getInstance(activity); gacHelper.getBuilder().addApi(Auth.CREDENTIALS_API); OldCredentialsApiHelper credentialHelper = OldCredentialsApiHelper.getInstance(gacHelper); List<Credential> credentials = SmartLockBase.credentialsFromFirebaseUser(firebaseUser); List<Task<?>> credentialTasks = new ArrayList<>(); for (Credential credential : credentials) { credentialTasks.add(credentialHelper.delete(credential)); } final Task<Void> combinedCredentialTask = Tasks.whenAll(credentialTasks); return deleteUserTask.continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(@NonNull Task<Void> task) throws Exception { task.getResult(Exception.class); return combinedCredentialTask; } }); }

Target:
public Task<Void> delete(@NonNull Activity activity) { GoogleApiClientTaskHelper gacHelper = GoogleApiClientTaskHelper.getInstance(activity); gacHelper.getBuilder().addApi(Auth.CREDENTIALS_API); CredentialTaskApi credentialHelper = CredentialsApiHelper.getInstance(gacHelper); return getDeleteTask(credentialHelper); }
Source:
public String toString() { return "ListOffsetsResultInfo [offset=" + offset + ", timestamp=" + timestamp + ", leaderEpoch=" + leaderEpoch + "]"; }

Target:
public String toString() { return "ListOffsetsResultInfo(offset=" + offset + ", timestamp=" + timestamp + ", leaderEpoch=" + leaderEpoch + ")"; }
Source:
public void putInt(int length, int value) throws CTFReaderException { final long curPos = this.pos; if (!canRead(length)) { throw new CTFReaderException("Cannot write to bitbuffer, insufficient space. Requested: " + length); } if (length == 0) { return; } if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { putIntLE(curPos, length, value); } else { putIntBE(curPos, length, value); } this.pos += length; }

Target:
public void putInt(int length, int value) throws CTFReaderException { final long curPos = this.pos; if (!canRead(length)) { throw new CTFReaderException("Cannot write to bitbuffer, " + "insufficient space. Requested: " + length); } if (length == 0) { return; } if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { putIntLE(curPos, length, value); } else { putIntBE(curPos, length, value); } this.pos += length; }
Source:
public AttributeTree(StateSystem ss, FileInputStream fis) throws IOException { this(ss); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fis)); int res = ois.readInt(); if (res != ATTRIB_TREE_MAGIC_NUMBER) { throw new IOException("The attribute tree file section is either invalid or corrupted."); } ArrayList<String[]> attribList; try { @SuppressWarnings("unchecked") ArrayList<String[]> list = (ArrayList<String[]>) ois.readObject(); attribList = list; } catch (ClassNotFoundException e) { throw new IOException("Unrecognizable attribute list"); } String[] prevFullAttribute = null, currFullAttribute = null; for (String[] attrib : attribList) { currFullAttribute = (prevFullAttribute == null) ? attrib : decodeFullAttribute(prevFullAttribute, attrib); this.getQuarkAndAdd(ROOT_ATTRIBUTE, currFullAttribute); prevFullAttribute = currFullAttribute; } }

Target:
public AttributeTree(StateSystem ss, FileInputStream fis) throws IOException { this(ss); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fis)); int res = ois.readInt(); if (res != ATTRIB_TREE_MAGIC_NUMBER) { throw new IOException("The attribute tree file section is either invalid or corrupted."); } ArrayList<@NonNull String @NonNull []> attribList; try { @SuppressWarnings("unchecked") ArrayList<@NonNull String @NonNull []> list = (ArrayList<@NonNull String @NonNull []>) ois.readObject(); attribList = list; } catch (ClassNotFoundException e) { throw new IOException("Unrecognizable attribute list"); } String[] prevFullAttribute = null, curFullAttribute = null; for (String[] attrib : attribList) { curFullAttribute = (prevFullAttribute == null) ? attrib : decodeFullAttribute(prevFullAttribute, attrib); this.getQuarkAndAdd(ROOT_ATTRIBUTE, curFullAttribute); prevFullAttribute = curFullAttribute; } }
Source:
private void checkException(Exception e, String expected) { System.out.println("Expecting: " + expected + ", got: " + e); assertTrue(e.getMessage().contains(expected)); }

Target:
private void checkException(Exception e, String expected) { assertTrue(e.getMessage().contains(expected)); }
Source:
public void convert() { JudgmentSeriesCriteria criteria = judgmentSeriesFilterConverter.convert(filter1); assertNotNull(filter1); assertCriteria(filter1, criteria); }

Target:
public void convert() { JudgmentSeriesCriteria criteria = judgmentSeriesFilterConverter.convert(filter1); assertNotNull(criteria); assertCriteria(filter1, criteria); }
Source:
public void stop() { if (!isStopping() && !isStopped()) { try { super.stop(); } catch (Exception e) { throw wrapRuntimeCamelException(e); } } else { LOG.trace("Ignoring maybeStop() as Apache Camel is already stopped"); } }

Target:
public void stop() { if (!isStopping() && !isStopped()) { try { super.stop(); } catch (Exception e) { throw wrapRuntimeCamelException(e); } } else { LOG.trace("Ignoring stop() as Camel is already stopped"); } }
Source:
private void initReplLoad(ASTNode ast) throws HiveException { path = PlanUtils.stripQuotes(ast.getChild(0).getText()); int numChildren = ast.getChildCount(); for (int i = 1; i < numChildren; i++) { ASTNode childNode = (ASTNode) ast.getChild(i); switch (childNode.getToken().getType()) { case TOK_DBNAME: dbNameOrPattern = PlanUtils.stripQuotes(childNode.getChild(0).getText()); for (String dbName : Utils.matchesDb(db, dbNameOrPattern)) { Database database = db.getDatabase(dbName); if (database != null) { if (ReplChangeManager.isSourceOfReplication(database)) { LOG.error("Cannot load database " + dbName + " as it is a source of replication"); throw new SemanticException(ErrorMsg.REPL_TARGET_IS_THE_SOURCE_OF_REPLICATION.getMsg()); } } } break; case TOK_TABNAME: tblNameOrPattern = PlanUtils.stripQuotes(childNode.getChild(0).getText()); break; case TOK_REPL_CONFIG: Map<String, String> replConfigs = DDLSemanticAnalyzer.getProps((ASTNode) childNode.getChild(0)); if (null != replConfigs) { for (Map.Entry<String, String> config : replConfigs.entrySet()) { conf.set(config.getKey(), config.getValue()); } try { db = Hive.get(conf); } catch (HiveException e) { throw new SemanticException(e); } } break; default: throw new SemanticException("Unrecognized token in REPL LOAD statement"); } } }

Target:
private void initReplLoad(ASTNode ast) throws SemanticException { path = PlanUtils.stripQuotes(ast.getChild(0).getText()); int numChildren = ast.getChildCount(); for (int i = 1; i < numChildren; i++) { ASTNode childNode = (ASTNode) ast.getChild(i); switch (childNode.getToken().getType()) { case TOK_DBNAME: dbNameOrPattern = PlanUtils.stripQuotes(childNode.getChild(0).getText()); break; case TOK_TABNAME: tblNameOrPattern = PlanUtils.stripQuotes(childNode.getChild(0).getText()); break; case TOK_REPL_CONFIG: Map<String, String> replConfigs = DDLSemanticAnalyzer.getProps((ASTNode) childNode.getChild(0)); if (null != replConfigs) { for (Map.Entry<String, String> config : replConfigs.entrySet()) { conf.set(config.getKey(), config.getValue()); } try { db = Hive.get(conf); } catch (HiveException e) { throw new SemanticException(e); } } break; default: throw new SemanticException("Unrecognized token in REPL LOAD statement"); } } }
Source:
public void clear() { CacheDescriptor proposedCacheDescriptor = createNamespaceAndConstructCacheProposal(persistentTimestampStore); CacheDescriptor previous = cacheDescriptor.getAndUpdate(prev -> proposedCacheDescriptor); if (previous != null) { persistentTimestampStore.dropNamespace(previous.storeNamespace()); } taggedMetricRegistry.gauge(CACHE_SIZE, cacheSizeGauge); }

Target:
public void clear() { CacheDescriptor proposedCacheDescriptor = createNamespaceAndConstructCacheProposal(persistentTimestampStore); CacheDescriptor previous = cacheDescriptor.getAndUpdate(prev -> proposedCacheDescriptor); if (previous != null) { persistentTimestampStore.dropNamespace(previous.storeNamespace()); } }
Source:
protected List<MeasurementVariable> moveSelectedVariableInTheFirstColumn(List<MeasurementVariable> columns, final int variableId) { int trialInstanceIndex = 0; for(MeasurementVariable column: columns) { if(variableId == column.getTermId()) { final MeasurementVariable trialInstanceMeasurementVariable = columns.remove(trialInstanceIndex); columns.add(0, trialInstanceMeasurementVariable); break; } trialInstanceIndex++; } return columns; }

Target:
List<MeasurementVariable> moveSelectedVariableInTheFirstColumn(List<MeasurementVariable> columns, final int variableId) { int trialInstanceIndex = 0; for(final MeasurementVariable column: columns) { if(variableId == column.getTermId()) { final MeasurementVariable trialInstanceMeasurementVariable = columns.remove(trialInstanceIndex); columns.add(0, trialInstanceMeasurementVariable); break; } trialInstanceIndex++; } return columns; }
Source:
private void bind(Show show) { collapsingToolbar.setTitle(show.getTitle()); status.setText(show.getShowStatus().getStringId()); CharSequence descriptionText = processDescription(show.getDescription()); if (descriptionText.length() == 0) { description.setVisibility(View.GONE); divider.setVisibility(View.GONE); } else { description.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE); description.setText(descriptionText); } duration.setText(getString(R.string.duration, show.getRuntime())); rating.setText(getString(R.string.rating, show.getRating())); Glide.with(this) .load(show) .centerCrop() .into(showImage); }

Target:
private void bind(Show show) { collapsingToolbar.setTitle(show.getTitle()); status.setText(show.getShowStatus().getStringId()); CharSequence descriptionText = processDescription(show.getDescription()); if (TextUtils.isEmpty(descriptionText)) { description.setVisibility(View.GONE); divider.setVisibility(View.GONE); } else { description.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE); description.setText(descriptionText); } duration.setText(getString(R.string.duration, show.getRuntime())); rating.setText(getString(R.string.rating, show.getRating())); Glide.with(this) .load(show) .centerCrop() .into(showImage); }
Source:
public List<IModule> getModules() { List<IModule> result = new ArrayList<IModule>(size()); for (ModuleListEntry entry : this) { result.add(entry.getModule()); } return result; }

Target:
List<IModule> getModules() { List<IModule> result = new ArrayList<IModule>(size()); for (ModuleListEntry entry : this) { result.add(entry.getModule()); } return result; }
Source:
private Socket generateIdlePersistentConnection() throws IOException { Socket socket = new Socket("localhost", dynamicPort.getNumber()); assertThat(socket.isConnected(), is(true)); sendRequest(socket, "/path"); assertResponse(getResponse(socket), true); sendRequest(socket, "/path"); assertResponse(getResponse(socket), true); return socket; }

Target:
private Socket generateIdlePersistentConnection() throws IOException { Socket socket = new Socket("localhost", dynamicPort.getNumber()); assertThat(socket.isConnected(), is(true)); sendRequest(socket, FAST_PROCESSING_ENDPOINT); assertResponse(getResponse(socket), true); sendRequest(socket, FAST_PROCESSING_ENDPOINT); assertResponse(getResponse(socket), true); return socket; }
Source:
public void doSpecificWork() { StopWatch sw = new StopWatch().start(); LOGGER.info("Start calculating landmarks, default active lms: {}, weighting: {}, {}", lms.getLandmarkCount(), defaultActiveLandmarks, lms.getLmSelectionWeighting(), Helper.getMemInfo()); lms.createLandmarks(); lms.flush(); LOGGER.info("Calculating landmarks for " + (lms.getSubnetworksWithLandmarks() - 1) + " subnetworks took:" + sw.stop().getSeconds() + " => " + lms.getLandmarksAsGeoJSON() + ", stored weights:" + lms.getLandmarkCount() + ", nodes:" + graph.getNodes() + ", " + Helper.getMemInfo()); }

Target:
public void doSpecificWork() { StopWatch sw = new StopWatch().start(); LOGGER.info("Start calculating " + lms.getLandmarkCount() + " landmarks, default active lms:" + defaultActiveLandmarks + ", weighting:" + lms.getLmSelectionWeighting() + ", " + Helper.getMemInfo()); lms.createLandmarks(); lms.flush(); LOGGER.info("Calculating landmarks for " + (lms.getSubnetworksWithLandmarks() - 1) + " subnetworks took:" + sw.stop().getSeconds() + " => " + lms.getLandmarksAsGeoJSON() + ", stored weights:" + lms.getLandmarkCount() + ", nodes:" + graph.getNodes() + ", " + Helper.getMemInfo()); }
Source:
public void testToString() { LoginCredentials toTest = LoginCredentials.builder().user("myuser").password("password").privateKey("key").build(); String str = toTest.toString(); assertTrue(str.contains("myuser"), "str="+toTest); assertTrue(str.contains("passwordPresent=true"), "str="+toTest); assertTrue(str.contains("privateKeyPresent=true"), "str="+toTest); }

Target:
public void testToString() { LoginCredentials toTest = LoginCredentials.builder().user("myuser").password("password").privateKey("key").build(); assertNotNull(toTest.toString()); }
Source:
public synchronized void stop() throws Exception { if (started) { isLeader = false; server.stop(); serverThread.join(); if (gcTsTracker != null) { gcTsTracker.stop(); } started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderLatch.close(); execService.shutdown(); execService.awaitTermination(10, TimeUnit.SECONDS); curatorFramework.getConnectionStateListenable().removeListener(cnxnListener); Thread.sleep(250); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }

Target:
public synchronized void stop() throws Exception { if (started) { isLeader = false; server.stop(); serverThread.join(); if (gcTsTracker != null) { gcTsTracker.stop(); } started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderLatch.close(); execService.shutdown(); execService.awaitTermination(10, TimeUnit.SECONDS); curatorFramework.getConnectionStateListenable().removeListener(cnxnListener); Uninterruptibles.sleepUninterruptibly(250, TimeUnit.MILLISECONDS); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }
Source:
public void start() { expiryEntryQueue = new LinkedBlockingQueue<ExpiryEntry>(configuration.expiryQueueSize()); try { db = openDatabase(getQualifiedLocation(), dataDbOptions()); expiredDb = openDatabase(getQualifiedExpiredLocation(), expiredDbOptions()); semaphore.release(Integer.MAX_VALUE); } catch (IOException e) { throw new CacheConfigurationException("Unable to open database", e); } }

Target:
public void start() { expiryEntryQueue = new LinkedBlockingQueue<ExpiryEntry>(configuration.expiryQueueSize()); try { db = openDatabase(getQualifiedLocation(), dataDbOptions()); expiredDb = openDatabase(getQualifiedExpiredLocation(), expiredDbOptions()); stopped = false; } catch (IOException e) { throw new CacheConfigurationException("Unable to open database", e); } }
Source:
public Iterable<Ticket> getTicketsIncrementally(Date startTime, Date endTime) { return new PagedIterable<Ticket>( tmpl("/incremental/tickets.json{?start_time,end_time}") .set("start_time", (int) (startTime.getTime() / 1000)) .set("end_time", (int) (endTime.getTime() / 1000)), handleIncrementalList(Ticket.class, "tickets")); }

Target:
public Iterable<Ticket> getTicketsIncrementally(Date startTime, Date endTime) { return new PagedIterable<Ticket>( tmpl("/incremental/tickets.json{?start_time,end_time}") .set("start_time", msToSeconds(startTime.getTime())) .set("end_time", msToSeconds(endTime.getTime())), handleIncrementalList(Ticket.class, "tickets")); }
Source:
protected int run() throws Exception { Jenkins jenkins = Jenkins.get(); jenkins.checkPermission(Jenkins.ADMINISTER); PluginManager manager = jenkins.getPluginManager(); int result = 0; boolean somePluginDisabled = false; for (String pluginName : pluginNames) { switch (disablePlugin(manager, pluginName)) { case DISABLED: if(!somePluginDisabled) somePluginDisabled = true; break; case NOT_DISABLED_DEPENDANTS: if(result != 16) result = 16; } } if (restart && somePluginDisabled) { jenkins.safeRestart(); } return result; }

Target:
protected int run() throws Exception { Jenkins jenkins = Jenkins.get(); jenkins.checkPermission(Jenkins.ADMINISTER); PluginWrapper.PluginDisableStrategy strategyToUse; try { strategyToUse = PluginWrapper.PluginDisableStrategy.valueOf(strategy.toUpperCase()); } catch (IllegalArgumentException iae) { throw new IllegalArgumentException(hudson.cli.Messages.DisablePluginCommand_NoSuchStrategy(strategy, String.format("%s, %s, %s", PluginWrapper.PluginDisableStrategy.NONE, PluginWrapper.PluginDisableStrategy.MANDATORY, PluginWrapper.PluginDisableStrategy.ALL))); } List<PluginWrapper.PluginDisableResult> results = jenkins.pluginManager.disablePlugins(strategyToUse, pluginNames); printResults(results); restartIfNecessary(results); return getResultCode(results); }
Source:
public int length() { if (sizeCached) { return size; } size = 0; for (String s : bufferList) { size += s.length(); } return size; }

Target:
public int length() { if (sizeCached) { return size; } size = 0; for (String s : bufferList) { size += s.length(); } sizeCached = true; return size; }
Source:
protected VDSReturnValue performImageVdsmOperation() { setDestinationImageId(Guid.NewGuid()); mNewCreatedDiskImage = CloneDiskImage(getDestinationImageId()); Guid storagePoolID = mNewCreatedDiskImage.getstorage_pool_id() != null ? mNewCreatedDiskImage .getstorage_pool_id().getValue() : Guid.Empty; VDSReturnValue vdsReturnValue = null; try { vdsReturnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CopyImage, new CopyImageVDSCommandParameters(storagePoolID, getDiskImage().getstorage_id().getValue(), getVmTemplateId(), getDiskImage().getimage_group_id().getValue(), getImage() .getId(), getImageGroupId(), getDestinationImageId(), CalculateImageDescription(), getDestinationStorageDomainId(), CopyVolumeType.LeafVol, mNewCreatedDiskImage.getvolume_format(), mNewCreatedDiskImage.getvolume_type(), getDiskImage().getwipe_after_delete(), false, getStoragePool().getcompatibility_version().toString())); if (vdsReturnValue.getSucceeded()) { getReturnValue().getInternalTaskIdList().add( CreateTask(vdsReturnValue.getCreationInfo(), VdcActionType.AddVmFromTemplate)); } else { return vdsReturnValue; } } catch (java.lang.Exception e) { log.errorFormat( "CreateCloneOfTemplateCommand::CreateSnapshotInIrsServer::Failed creating snapshot from image id -'{0}'", getImage().getId()); throw new VdcBLLException(VdcBllErrors.VolumeCreationError); } return vdsReturnValue; }

Target:
protected VDSReturnValue performImageVdsmOperation() { setDestinationImageId(Guid.NewGuid()); mNewCreatedDiskImage = CloneDiskImage(getDestinationImageId()); Guid storagePoolID = mNewCreatedDiskImage.getstorage_pool_id() != null ? mNewCreatedDiskImage .getstorage_pool_id().getValue() : Guid.Empty; VDSReturnValue vdsReturnValue = null; try { vdsReturnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CopyImage, new CopyImageVDSCommandParameters(storagePoolID, getDiskImage().getstorage_id().getValue(), getVmTemplateId(), getDiskImage().getimage_group_id().getValue(), getImage() .getId(), getImageGroupId(), getDestinationImageId(), CalculateImageDescription(), getDestinationStorageDomainId(), CopyVolumeType.LeafVol, mNewCreatedDiskImage.getvolume_format(), mNewCreatedDiskImage.getvolume_type(), getDiskImage().getwipe_after_delete(), false, getStoragePool().getcompatibility_version().toString())); if (vdsReturnValue.getSucceeded()) { getReturnValue().getInternalTaskIdList().add( CreateTask(vdsReturnValue.getCreationInfo(), VdcActionType.AddVmFromTemplate)); } } catch (java.lang.Exception e) { log.errorFormat( "CreateCloneOfTemplateCommand::CreateSnapshotInIrsServer::Failed creating snapshot from image id -'{0}'", getImage().getId()); throw new VdcBLLException(VdcBllErrors.VolumeCreationError); } return vdsReturnValue; }
Source:
public void getSelectedRecord() { getRecordById(Helper.getRequestParameter(ID_PARAMETER_NAME)); Ajax.update(FORM_CLIENTID); if (this.createProcessForm.getProcesses().size() > 1 && Objects.isNull(this.createProcessForm.getProcesses().get(1).getMetadataNodes())) { this.createProcessForm.setEditActiveTabIndex(TITLE_RECORD_LINK_TAB_INDEX); Process parentProcess = this.createProcessForm.getProcesses().get(1).getProcess(); ArrayList<SelectItem> parentCandidates = new ArrayList<>(); parentCandidates.add(new SelectItem(parentProcess.getId().toString(), parentProcess.getTitle())); this.createProcessForm.getTitleRecordLinkTab().setPossibleParentProcesses(parentCandidates); this.createProcessForm.getTitleRecordLinkTab().setChosenParentProcess((String)parentCandidates.get(0).getValue()); this.createProcessForm.getTitleRecordLinkTab().chooseParentProcess(); String summary = Helper.getTranslation("newProcess.catalogueSearch.linkedToExistingProcessSummary"); String detail = Helper.getTranslation("newProcess.catalogueSearch.linkedToExistingProcessDetail", Collections.singletonList(parentProcess.getTitle())); showGrowMessage(summary, detail); Ajax.update(INSERTION_TREE); } else { this.createProcessForm.setEditActiveTabIndex(ADDITIONAL_FIELDS_TAB_INDEX); } if (ServiceManager.getImportService().getExemplarRecords().size() > 0) { PrimeFaces.current().executeScript("PF('exemplarRecordsDialog').show();"); } }

Target:
public void getSelectedRecord() { getRecordById(Helper.getRequestParameter(ID_PARAMETER_NAME)); Ajax.update(FORM_CLIENTID); int numberOfProcesses = this.createProcessForm.getProcesses().size(); if (numberOfProcesses < 1) { Helper.setErrorMessage("Error: list of processes is empty!"); return; } if (numberOfProcesses < this.importDepth) { TempProcess parentTempProcess = ServiceManager.getImportService().getParentTempProcess(); if (Objects.nonNull(parentTempProcess)) { Process parentProcess = parentTempProcess.getProcess(); if (numberOfProcesses == 1) { this.createProcessForm.setEditActiveTabIndex(TITLE_RECORD_LINK_TAB_INDEX); ArrayList<SelectItem> parentCandidates = new ArrayList<>(); parentCandidates.add(new SelectItem(parentProcess.getId().toString(), parentProcess.getTitle())); this.createProcessForm.getTitleRecordLinkTab().setPossibleParentProcesses(parentCandidates); this.createProcessForm.getTitleRecordLinkTab().setChosenParentProcess((String)parentCandidates.get(0).getValue()); this.createProcessForm.getTitleRecordLinkTab().chooseParentProcess(); Ajax.update(INSERTION_TREE); } else { this.createProcessForm.getProcesses().add(parentTempProcess); this.createProcessForm.setEditActiveTabIndex(ADDITIONAL_FIELDS_TAB_INDEX); } } else { this.createProcessForm.setEditActiveTabIndex(ADDITIONAL_FIELDS_TAB_INDEX); } } else { this.createProcessForm.setEditActiveTabIndex(ADDITIONAL_FIELDS_TAB_INDEX); } if (ServiceManager.getImportService().getExemplarRecords().size() > 0) { PrimeFaces.current().executeScript("PF('exemplarRecordsDialog').show();"); } }
Source:
public Optional<JavaBeanField> findDeclaredField(Class<?> declaringClass, String property) { Contracts.assertNotNull( declaringClass, MESSAGES.classCannotBeNull() ); Field field = run( GetDeclaredField.action( declaringClass, property ) ); String resolvedName = propertyNodeNameProvider.getName( javaBeanPropertyFrom( declaringClass, property ) ); return Optional.ofNullable( field ).map( f -> new JavaBeanField( f, resolvedName ) ); }

Target:
public Optional<JavaBeanField> findDeclaredField(Class<?> declaringClass, String property) { Contracts.assertNotNull( declaringClass, MESSAGES.classCannotBeNull() ); Field field = run( GetDeclaredField.action( declaringClass, property ) ); return Optional.ofNullable( field ).map( this::field ); }
Source:
public void damage(double amount, Entity source, DamageCause cause) { super.damage(amount, source, cause); if (DamageCause.LIGHTNING.equals(cause)) { CreeperPowerEvent event = EventFactory.getInstance() .callEvent(new CreeperPowerEvent( this, (LightningStrike) source, CreeperPowerEvent.PowerCause.LIGHTNING)); if (!event.isCancelled()) { setPowered(true); } } }

Target:
public void damage(double amount, Entity source, DamageCause cause) { super.damage(amount, source, cause); if (DamageCause.LIGHTNING.equals(cause) && !isPowered()) { CreeperPowerEvent event = EventFactory.getInstance() .callEvent(new CreeperPowerEvent( this, (LightningStrike) source, CreeperPowerEvent.PowerCause.LIGHTNING)); if (!event.isCancelled()) { setPowered(true); } } }
Source:
private void addCount(StyledString styled, int count) { String formatted = MessageFormat.format(" ({0})", count); styled.append(formatted, StyledString.COUNTER_STYLER); }

Target:
private void addCount(StyledString styled, int count) { String formatted = MessageFormat.format(COUNTER_PATTERN, count); styled.append(formatted, StyledString.COUNTER_STYLER); }
Source:
public void removeFolder(String id) { removeFolderInternal(id); mCompletion.removeFolder(id); sendConfig(); PreferenceManager.getDefaultSharedPreferences(mContext).edit() .remove(ShareActivity.PREF_FOLDER_SAVED_SUBDIRECTORY+id) .apply(); }

Target:
public void removeFolder(String id) { removeFolderInternal(id); sendConfig(); PreferenceManager.getDefaultSharedPreferences(mContext).edit() .remove(ShareActivity.PREF_FOLDER_SAVED_SUBDIRECTORY+id) .apply(); }
Source:
public void dispose() { super.dispose(); synchronized (fBuildJobMap) { fBuildJobMap.values().forEach(Job::cancel); } if (fZoomThread != null) { fZoomThread.cancel(); } deactivateContextService(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); IWorkbenchPartSite site = getSite(); if (site != null) { IWorkbenchPage page = site.getPage(); if (page != null) { page.removePartListener(fPartListener); page.removePartListener(fPartListener2); } } }

Target:
public void dispose() { super.dispose(); synchronized (fBuildJobMap) { fBuildJobMap.values().forEach(Job::cancel); } if (fZoomThread != null) { fZoomThread.cancel(); } deactivateContextService(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); IWorkbenchPartSite site = getSite(); if (site != null) { IWorkbenchPage page = site.getPage(); if (fPartListener != null) { page.removePartListener(fPartListener); } if (fPartListener2 != null) { page.removePartListener(fPartListener2); } } }
Source:
private void prepareEventObject(EventRecord eventRecord) throws JSONException { final JSONObject defaultEventProperties = systemInformation.getDefaultEventProperties(); final JSONObject eventProperties = new JSONObject(eventRecord.getJsonString()); if (eventProperties != null) { for (final Iterator<?> iter = defaultEventProperties.keys(); iter.hasNext();) { final String key = (String) iter.next(); eventProperties.put(key, defaultEventProperties.get(key)); } eventRecord.setJsonString(eventProperties.toString()); } }

Target:
private void prepareEventObject(EventRecord eventRecord) throws JSONException { JSONObject defaultEventProperties = systemInformation.getDefaultEventProperties(); JSONObject eventProperties = new JSONObject(eventRecord.getJsonString()); for (final Iterator<?> iter = defaultEventProperties.keys(); iter.hasNext();) { final String key = (String) iter.next(); eventProperties.put(key, defaultEventProperties.get(key)); eventRecord.setJsonString(eventProperties.toString()); } }
Source:
List<VariantEntity> queryByCoordinatesAndAlleles(String chromosome, int start, String reference, String alternate) { if (alternate != null) { return variantEntityRepository.findByChromosomeAndStartAndReferenceAndAlternate(chromosome, start, reference, alternate); } else { return variantEntityRepository.findByChromosomeAndStartAndReference(chromosome, start, reference); } }

Target:
private List<VariantEntity> queryByCoordinatesAndAlleles(String chromosome, int start, String reference, String alternate) { if (alternate != null) { return variantEntityRepository.findByChromosomeAndStartAndReferenceAndAlternate(chromosome, start, reference, alternate); } else { return variantEntityRepository.findByChromosomeAndStartAndReference(chromosome, start, reference); } }
Source:
public void descriptionHonorsShowRawYaml() { PodTemplate pt = new PodTemplate(); ContainerTemplate ct1 = new ContainerTemplate("foo", "image"); pt.setContainers(Collections.singletonList(ct1)); String yaml = new StringBuilder() .append("metadata:").append("\n") .append(" annotations:").append("\n") .append(" foo: bar").append("\n") .toString(); pt.setYamls(Collections.singletonList(yaml)); String description = pt.getDescriptionForLogging(); assertThat(description, containsString("[foo] image")); assertThat(description, containsString("yaml:\n"+yaml)); pt.setShowRawYaml(false); description = pt.getDescriptionForLogging(); assertThat(description, not(containsString("yaml:\n"))); assertThat(description, not(containsString(yaml))); }

Target:
public void descriptionHonorsShowRawYaml() { PodTemplate pt = new PodTemplate(); ContainerTemplate ct1 = new ContainerTemplate("foo", "image"); pt.setContainers(Collections.singletonList(ct1)); String yaml = "metadata:\n" + " annotations:\n" + " foo: bar\n"; pt.setYamls(Collections.singletonList(yaml)); String description = pt.getDescriptionForLogging(); assertThat(description, containsString("[foo] image")); assertThat(description, containsString("yaml:\n"+yaml)); pt.setShowRawYaml(false); description = pt.getDescriptionForLogging(); assertThat(description, not(containsString("yaml:\n"))); assertThat(description, not(containsString(yaml))); }
Source:
public TokenResponse(ByteBuf buf) { respType = TokenType.values()[ICorfuPayload.fromBuffer(buf, Byte.class)]; conflictKey = ICorfuPayload.fromBuffer(buf, byte[].class); conflistStream = ICorfuPayload.fromBuffer(buf, UUID.class); offendingTx = ICorfuPayload.fromBuffer(buf, UUID.class); Long epoch = ICorfuPayload.fromBuffer(buf, Long.class); Long sequence = ICorfuPayload.fromBuffer(buf, Long.class); token = new Token(epoch, sequence); backpointerMap = ICorfuPayload.mapFromBuffer(buf, UUID.class, Long.class); streamTails = ICorfuPayload.listFromBuffer(buf, Long.class); }

Target:
public TokenResponse(ByteBuf buf) { respType = TokenType.values()[ICorfuPayload.fromBuffer(buf, Byte.class)]; conflictKey = ICorfuPayload.fromBuffer(buf, byte[].class); conflictStream = ICorfuPayload.fromBuffer(buf, UUID.class); Long epoch = ICorfuPayload.fromBuffer(buf, Long.class); Long sequence = ICorfuPayload.fromBuffer(buf, Long.class); token = new Token(epoch, sequence); backpointerMap = ICorfuPayload.mapFromBuffer(buf, UUID.class, Long.class); streamTails = ICorfuPayload.listFromBuffer(buf, Long.class); }
Source:
protected static Configuration getModuleConfig(String moduleName, String moduleId) { final Configuration result; final List<Configuration> configs = getModuleConfigs(moduleName); if (configs.size() == 1) { result = configs.get(0); } else if (configs.isEmpty()) { throw new IllegalStateException("no instances of the Module was found: " + moduleName); } else if (moduleId == null) { throw new IllegalStateException("multiple instances of the same Module are detected"); } else { result = configs.stream().filter(conf -> { try { return conf.getAttribute("id").equals(moduleId); } catch (CheckstyleException ex) { throw new IllegalStateException("problem to get ID attribute from " + conf, ex); } }) .findFirst().orElseGet(null); } return result; }

Target:
protected static Configuration getModuleConfig(String moduleName, String moduleId) { final Configuration result; final List<Configuration> configs = getModuleConfigs(moduleName); if (configs.size() == 1) { result = configs.get(0); } else if (configs.isEmpty()) { throw new IllegalStateException("no instances of the Module was found: " + moduleName); } else if (moduleId == null) { throw new IllegalStateException("multiple instances of the same Module are detected"); } else { result = configs.stream().filter(conf -> { try { return conf.getAttribute("id").equals(moduleId); } catch (CheckstyleException ex) { throw new IllegalStateException("problem to get ID attribute from " + conf, ex); } }) .findFirst() .orElseThrow(() -> new IllegalStateException("problem with module config")); } return result; }