auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Set<TaskError> validateAction(Task task, Channel channel, TaskActionInformation action) { LOGGER.debug("Validating task action: from task: with ID: {}", action.getName(), task.getName(), task.getId()); Set<TaskError> errors = new HashSet<>(); if (channel == null) { errors.add(new TaskError("task.validation.error.actionChannelNotRegistered")); return errors; } if (channel.getModuleName().equalsIgnoreCase(action.getModuleName())) { errors.addAll(taskValidator.validateAction(action, channel)); TriggerEvent trigger = triggerEventService.getTrigger(task.getTrigger()); Map<Long, TaskDataProvider> providers = getProviders(task); ActionEvent actionEvent = ChannelUtils.getAction(channel, action); if (actionEvent != null) { errors.addAll(taskValidator.validateActionFields(action, actionEvent, trigger, providers)); } } logResultOfValidation("task action", task.getName(), errors); return errors; }

Target:
private Set<TaskError> validateAction(Task task, Channel channel, TaskActionInformation action) { LOGGER.debug("Validating task action: from task: with ID: {}", action.getName(), task.getName(), task.getId()); Set<TaskError> errors = new HashSet<>(); if (channel == null) { errors.add(new TaskError("task.validation.error.actionChannelNotRegistered")); return errors; } if (channel.getModuleName().equalsIgnoreCase(action.getModuleName())) { errors.addAll(taskValidator.validateAction(action, channel)); TriggerEvent trigger = triggerEventService.getTrigger(task.getTrigger()); Map<Long, TaskDataProvider> providers = getProviders(task); ActionEvent actionEvent = channel.getAction(action); if (actionEvent != null) { errors.addAll(taskValidator.validateActionFields(action, actionEvent, trigger, providers)); } } logResultOfValidation("task action", task.getName(), errors); return errors; }
Source:
private void populateCurrentLags(Set<SystemStreamPartition> ssps) { Map<MetricName, ? extends Metric> consumerMetrics = kafkaConsumer.metrics(); if (perPartitionMetrics.isEmpty()) { populateMetricNames(ssps); } for (SystemStreamPartition ssp : ssps) { MetricName mn = perPartitionMetrics.get(ssp); Metric currentLagM = consumerMetrics.get(mn); long currentLag = (currentLagM != null) ? (long) currentLagM.value() : -1L; latestLags.put(ssp, currentLag); sink.setIsAtHighWatermark(ssp, currentLag == 0); } }

Target:
private void populateCurrentLags(Set<SystemStreamPartition> ssps) { Map<MetricName, ? extends Metric> consumerMetrics = kafkaConsumer.metrics(); if (perPartitionMetrics.isEmpty()) { HashMap<String, String> tags = new HashMap<>(); tags.put("client-id", clientId); for (SystemStreamPartition ssp : ssps) { TopicPartition tp = KafkaSystemConsumer.toTopicPartition(ssp); perPartitionMetrics.put(ssp, new MetricName(tp + ".records-lag", "consumer-fetch-manager-metrics", "", tags)); } } for (SystemStreamPartition ssp : ssps) { MetricName mn = perPartitionMetrics.get(ssp); Metric currentLagMetric = consumerMetrics.get(mn); long currentLag = (currentLagMetric != null) ? (long) currentLagMetric.value() : -1L; latestLags.put(ssp, currentLag); sink.setIsAtHighWatermark(ssp, currentLag == 0); } }
Source:
public void testLoadFile() throws Exception { InputStream inputStream = loadResource(); final String PREFIX = "defaults_temp"; final String SUFFIX = "yaml"; File file = File.createTempFile(PREFIX, SUFFIX); file.deleteOnExit(); OutputStream outputStream = new FileOutputStream(file); IOUtils.copy(inputStream, outputStream); outputStream.close(); Map<String, Object> props = ConfigReader.loadFile(file.getAbsolutePath()); testProperty(props); }

Target:
public void testLoadFile() throws Exception { InputStream inputStream = loadResource(); File file = File.createTempFile("defaults_temp", "yaml"); file.deleteOnExit(); OutputStream outputStream = new FileOutputStream(file); IOUtils.copy(inputStream, outputStream); outputStream.close(); Map<String, Object> props = ConfigReader.loadFile(file.getAbsolutePath()); testProperty(props); }
Source:
private void initializeUser() { mUser.loadUserImage(getActivity(), mPhoto); mName.setText(mUser.getName()); mVolunteer.setText(User.VOLUNTEER_SPINNER[mUser.getVolunteerType()]); int hoursRequired = mUser.getUserSemester() == null ? 0 : mUser.getUserSemester().getHoursRequired(); mTotalSemester.setText(String.valueOf(hoursRequired)); String totalHours = mUser.getUserSemester() == null ? String.valueOf(0) : mUser.getUserSemester().getTimeString(); mTotalHours.setText(totalHours); mTotalWeek.setText(String.valueOf(mUser.getVolunteerType() + 1)); String schoolString = mUser.getSchool() == null ? "N/A" : mUser.getSchool().getName(); mSchool.setText(schoolString); int role = mUser.getRole(); if (mUser.getDirectorId() != 0) { role = 3; } mUserType.setVisibility(View.VISIBLE); mUserType.setTypeface(null, Typeface.BOLD); GradientDrawable shape = (GradientDrawable) mUserType.getBackground(); mUserType.setText(ROLES[role]); switch(role) { case 0: mUserType.setVisibility(View.GONE); break; case 1: shape.setColor(getResources().getColor(R.color.orange_admin)); break; case 2: shape.setColor(getResources().getColor(R.color.blue_president)); break; case 3: shape.setColor(getResources().getColor(R.color.turquoise_director)); break; } mToolbarInterface.setTitle("User"); }

Target:
private void initializeUser() { mUser.loadUserImage(getActivity(), mPhoto); mName.setText(mUser.getName()); mVolunteer.setText(User.VOLUNTEER_SPINNER[mUser.getVolunteerType()]); int hoursRequired = mUser.getUserSemester() == null ? 0 : mUser.getUserSemester().getHoursRequired(); mTotalSemester.setText(String.valueOf(hoursRequired)); String totalHours = mUser.getUserSemester() == null ? String.valueOf(0) : mUser.getUserSemester().getTimeString(); mTotalHours.setText(totalHours); mTotalWeek.setText(String.valueOf(mUser.getVolunteerType() + 1)); String schoolString = mUser.getSchool() == null ? "N/A" : mUser.getSchool().getName(); mSchool.setText(schoolString); UserUtils.setType(getActivity(), mUser, mUserType, null, mUser.ROLES_LABEL); mToolbarInterface.setTitle("User"); }
Source:
public ModuleAction save(ModuleAction delegate) { throw new IllegalArgumentException("ModuleAction cannot be saved"); }

Target:
public ModuleAction save(ModuleAction delegate) { throw new UnsupportedOperationException("ModuleAction cannot be saved"); }
Source:
public static void main(String[] args) throws Exception { Logging.initialize(); DistributedQueryRunner queryRunner = createQueryRunner(ImmutableMap.of("http-server.http.port", "8080")); Thread.sleep(10); Logger log = Logger.get(GeoQueryRunner.class); log.info("======== SERVER STARTED ========"); log.info("\n====\n%s\n====", queryRunner.getCoordinator().getBaseUrl()); }

Target:
public static void main(String[] args) throws Exception { Logging.initialize(); DistributedQueryRunner queryRunner = createQueryRunner(ImmutableMap.of("http-server.http.port", "8080")); Logger log = Logger.get(GeoQueryRunner.class); log.info("======== SERVER STARTED ========"); log.info("\n====\n%s\n====", queryRunner.getCoordinator().getBaseUrl()); }
Source:
public @ResponseBody BoxDto removeMultipleItems(@PathVariable long boxId, @RequestBody List<String> positions) throws IOException { Box box = getBox(boxId); for (String position : positions) { box.getBoxPositions().remove(position); } boxService.save(box); return getBoxDtoWithBoxables(boxId); }

Target:
public @ResponseBody BoxDto removeMultipleItems(@PathVariable long boxId, @RequestBody List<String> positions) throws IOException { Box box = getBox(boxId); for (String position : positions) { if (box.getBoxPositions().containsKey(position)) { box.getBoxPositions().remove(position); } } boxService.save(box); return getBoxDtoWithBoxables(boxId); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_activity); ButterKnife.bind(this); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); String listName = getIntent().getStringExtra(MainActivity.LIST_NAME_KEY); setTitle(listName); boolean startFormEditPage = getIntent().getBooleanExtra(LIST_TYPE,false); preferencesManager = new PreferencesManager(this); ListTabsAdapter listTabsAdapter = new ListTabsAdapter( getSupportFragmentManager(), listName, listTabTitles); nameListPager.setAdapter(listTabsAdapter); if (startFormEditPage){ nameListPager.setCurrentItem(EDIT_NAME_LIST_FRAGMENT); } nameListTabs.setupWithViewPager(nameListPager); shakeDetector = new ShakeDetector(this); if (preferencesManager.shouldShowShake()) { new MaterialDialog.Builder(this) .title(R.string.shake_it) .content(R.string.shake_now_supported) .positiveText(android.R.string.yes) .cancelable(false) .show(); } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_activity); ButterKnife.bind(this); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); String listName = getIntent().getStringExtra(MainActivity.LIST_NAME_KEY); setTitle(listName); preferencesManager = new PreferencesManager(this); ListTabsAdapter listTabsAdapter = new ListTabsAdapter( getSupportFragmentManager(), listName, listTabTitles); nameListPager.setAdapter(listTabsAdapter); if (getIntent().getBooleanExtra(START_ON_EDIT_PAGE, false)) { nameListPager.setCurrentItem(EDIT_NAME_LIST_PAGE_POSITION); } nameListTabs.setupWithViewPager(nameListPager); shakeDetector = new ShakeDetector(this); if (preferencesManager.shouldShowShake()) { new MaterialDialog.Builder(this) .title(R.string.shake_it) .content(R.string.shake_now_supported) .positiveText(android.R.string.yes) .cancelable(false) .show(); } }
Source:
private void createTableReplLogTask() throws SemanticException { ReplStateLogWork replLogWork = new ReplStateLogWork(replLogger, tableDesc.getTableName(), tableDesc.tableType()); Task<ReplStateLogWork> replLogTask = TaskFactory.get(replLogWork, context.hiveConf); if (tracker.tasks().isEmpty()) { tracker.addTask(replLogTask); } else { ReplLoadTask.dependency(tracker.tasks(), replLogTask); } }

Target:
private void createTableReplLogTask() throws SemanticException { ReplStateLogWork replLogWork = new ReplStateLogWork(replLogger, tableDesc.getTableName(), tableDesc.tableType()); Task<ReplStateLogWork> replLogTask = TaskFactory.get(replLogWork, context.hiveConf); if (tracker.tasks().isEmpty()) { tracker.addTask(replLogTask); } else { ReplLoadTask.dependency(tracker.tasks(), replLogTask); List<Task<? extends Serializable>> visited = new ArrayList<>(); tracker.updateTaskCount(replLogTask, visited); } }
Source:
public void onConnectionStateChange(String newConnectionState, String reason) { if (newConnectionState.equals(NOT_AUTHENTICATED) || newConnectionState.equals(CONNECTION_LOST)) { switch (reason) { case WRONG_APP_TOKEN: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "User defined Applicationtoken is wrong."); break; case WRONG_USER_OR_PASSWORD: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The set username or password is wrong."); break; case NO_USER_PASSWORD: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "no username or password is set to genarate appicationtoken. Please set user name and password or applicationtoken."); break; case CONNECTON_TIMEOUT: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Connection lost because connection timeout to Server."); break; case HOST_NOT_FOUND: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Server not found! Please check this points:\n" + " - DigitalSTROM-Server turned on?\n" + " - hostadress correct?\n" + " - ethernet cable connection established?"); break; case UNKNOWN_HOST: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Unkown host name, pleas check the set host name!"); break; case INVALID_URL: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Invalide URL is set."); break; default: } } }

Target:
public void onConnectionStateChange(String newConnectionState, String reason) { if (newConnectionState.equals(NOT_AUTHENTICATED) || newConnectionState.equals(CONNECTION_LOST)) { switch (reason) { case WRONG_APP_TOKEN: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "User defined Application-Token is wrong."); break; case WRONG_USER_OR_PASSWORD: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The set username or password is wrong."); break; case NO_USER_PASSWORD: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No username or password is set to generate Application-Token. Please set user name and password or Application-Token."); break; case CONNECTON_TIMEOUT: if (connectionTimeoutCounter++ > 0) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Connection lost because connection timeout to Server."); } return; case HOST_NOT_FOUND: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Server not found! Please check these points:\n" + " - Is digitalSTROM-Server turned on?\n" + " - Is the host address correct?\n" + " - Is the ethernet cable connection established?"); break; case UNKNOWN_HOST: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Unkown host name, please check the set host name!"); break; case INVALID_URL: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Invalid URL is set."); break; default: } connectionTimeoutCounter = 0; devStatMan.stop(); } }
Source:
public void execute() throws Exception { ConfigActionType actionType = parser.getConfigAction(); log.debug("execute: beginning execution of action " + actionType + "."); switch (actionType) { case ACTION_ALL: printAllValues(); break; case ACTION_LIST: printAvailableKeys(); break; case ACTION_GET: printKey(); break; case ACTION_SET: persistValue(); break; case ACTION_RELOAD: reloadConfigurations(); break; default: log.debug("execute: unable to recognize action: " + actionType + "."); throw new UnsupportedOperationException("Please tell me what to do: list? get? set? get-all?"); } }

Target:
public void execute() throws Exception { ConfigActionType actionType = parser.getConfigAction(); log.debug("execute: beginning execution of action " + actionType + "."); switch (actionType) { case ACTION_ALL: printAllValues(); break; case ACTION_LIST: printAvailableKeys(); break; case ACTION_GET: printKey(); break; case ACTION_SET: persistValue(); break; case ACTION_RELOAD: reloadConfigurations(); break; default: log.debug("execute: unable to recognize action: " + actionType + "."); throw new UnsupportedOperationException("Please tell me what to do: list? get? set? get-all? reload?"); } }
Source:
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) { try { String sha = getCommitShaSource().get(run, listener); List<GHRepository> repos = getReposSource().repos(run, listener); String contextName = getContextSource().context(run, listener); String backref = run.getAbsoluteUrl(); GitHubStatusResultSource.StatusResult result = getStatusResultSource().get(run, listener); String message = result.getMsg(); GHCommitState state = result.getState(); listener.getLogger().printf( "[GitHub Commit Status Setter] Going to set status %s on repos %s (sha:%7.7s) with context:%s%n", state, repos, sha, contextName ); for (GHRepository repo : repos) { listener.getLogger().println( GitHubCommitNotifier_SettingCommitStatus(repo.getHtmlUrl() + "/commit/" + sha) ); repo.createCommitStatus(sha, state, backref, message, contextName); } } catch (Exception e) { CombineErrorHandler.errorHandling().withHandlers(getErrorHandlers()).handle(e, run, listener); } }

Target:
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) { try { String sha = getCommitShaSource().get(run, listener); List<GHRepository> repos = getReposSource().repos(run, listener); String contextName = getContextSource().context(run, listener); String backref = getStatusBackrefSource().get(run, listener); GitHubStatusResultSource.StatusResult result = getStatusResultSource().get(run, listener); String message = result.getMsg(); GHCommitState state = result.getState(); listener.getLogger().printf( "[%s] %s on repos %s (sha:%7.7s) with context:%s%n", getDescriptor().getDisplayName(), state, repos, sha, contextName ); for (GHRepository repo : repos) { listener.getLogger().println( GitHubCommitNotifier_SettingCommitStatus(repo.getHtmlUrl() + "/commit/" + sha) ); repo.createCommitStatus(sha, state, backref, message, contextName); } } catch (Exception e) { CombineErrorHandler.errorHandling().withHandlers(getErrorHandlers()).handle(e, run, listener); } }
Source:
private void registerFabUploadListeners() { getFabUpload().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent action = new Intent(getActivity(), UploadFilesActivity.class); action.putExtra( UploadFilesActivity.EXTRA_ACCOUNT, ((FileActivity)getActivity()).getAccount() ); getActivity().startActivityForResult( action, FileDisplayActivity.ACTION_SELECT_MULTIPLE_FILES ); getFabMain().collapse(); recordMiniFabClick(); } }); getFabUpload().setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getActivity(), R.string.actionbar_upload, Toast.LENGTH_SHORT).show(); return true; } }); }

Target:
private void registerFabUploadListeners() { getFabUpload().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UploadFilesActivity.startUploadActivityForResult(getActivity(), ((FileActivity)getActivity()) .getAccount(), FileDisplayActivity.ACTION_SELECT_MULTIPLE_FILES); getFabMain().collapse(); recordMiniFabClick(); } }); getFabUpload().setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getActivity(), R.string.actionbar_upload, Toast.LENGTH_SHORT).show(); return true; } }); }
Source:
public void should_display_members_page() { String orgKey = createOrganization(); String userFoo = createUser("foo"); String userBar = createUser("bar"); createUser(); adminClient.organizations().addMember(orgKey, userFoo); adminClient.organizations().addMember(orgKey, userBar); MembersPage page = nav.openOrganizationMembers(orgKey); page .canNotAddMember() .shouldHaveTotal(3); page.getMembersByIdx(0).shouldBeNamed("admin", "Administrator"); page.getMembersByIdx(1).shouldBeNamed(userBar, userBar); page.getMembersByIdx(2) .shouldBeNamed(userFoo, userFoo) .shouldNotHaveActions(); }

Target:
public void should_display_members_page() { String orgKey = createOrganization(); String userFoo = createUser("foo"); adminClient.organizations().addMember(orgKey, userFoo); String userBar = createUser("bar"); adminClient.organizations().addMember(orgKey, userBar); createUser(); MembersPage page = nav.openOrganizationMembers(orgKey); page .canNotAddMember() .shouldHaveTotal(3); page.getMembersByIdx(0).shouldBeNamed("admin", "Administrator"); page.getMembersByIdx(1).shouldBeNamed(userBar, userBar); page.getMembersByIdx(2) .shouldBeNamed(userFoo, userFoo) .shouldNotHaveActions(); }
Source:
public void set(String replState, String dbName, String tableName, Map <String, String> partSpec) { updateMetaDataList.add(new UpdateMetaData(replState, dbName, tableName, partSpec)); String key = getKey(normalizeIdentifier(dbName), normalizeIdentifier(tableName)); updateMetaDataMap.put(key, updateMetaDataList.size() - 1); }

Target:
public void set(String replState, String dbName, String tableName, Map <String, String> partSpec) throws SemanticException { if (dbName == null) { throw new SemanticException("db name can not be null"); } String key = getKey(normalizeIdentifier(dbName), normalizeIdentifier(tableName)); Integer idx = updateMetaDataMap.get(key); if (idx == null) { updateMetaDataList.add(new UpdateMetaData(replState, dbName, tableName, partSpec)); updateMetaDataMap.put(key, updateMetaDataList.size() - 1); } else { updateMetaDataList.get(idx).addPartition(partSpec); } }
Source:
public void shouldRetrieveRepresentationRevision() throws MCSException { RecordServiceClient instance = new RecordServiceClient("http://localhost:8080/mcs", "metis_test", "1RkZBuVf"); List<Representation> representations = instance.getRepresentationsByRevision("Z6DX3RWCEFUUSGRUWP6QZWRIZKY7HI5Y7H4UD3OQVB3SRPAUVZHA", "REPRESENTATION1", "Revision_2", "Revision_Provider", "2018-08-28T07:13:34.658"); assertNotNull(representations); assertTrue(representations.size() == 1); assertEquals("REPRESENTATION1", representations.get(0).getRepresentationName()); assertEquals("68b4cc30-aa8d-11e8-8289-1c6f653f9042", representations.get(0).getVersion()); }

Target:
public void shouldRetrieveRepresentationRevision() throws MCSException { RecordServiceClient instance = new RecordServiceClient("http://localhost:8080/mcs", "admin", "admin"); List<Representation> representations = instance.getRepresentationsByRevision("Z6DX3RWCEFUUSGRUWP6QZWRIZKY7HI5Y7H4UD3OQVB3SRPAUVZHA", "REPRESENTATION1", "Revision_2", "Revision_Provider", "2018-08-28T07:13:34.658"); assertNotNull(representations); assertTrue(representations.size() == 1); assertEquals("REPRESENTATION1", representations.get(0).getRepresentationName()); assertEquals("68b4cc30-aa8d-11e8-8289-1c6f653f9042", representations.get(0).getVersion()); }
Source:
public void testCreateNodeWithCustomHardwareUsingMins() throws Exception { Template template = buildTemplate(templateBuilder() .minCores(2).minRam(2048).minDisk(10)); try { NodeMetadata node = getOnlyElement(client.createNodesInGroup(group + "custom", 1, template)); assertThat(node.getHardware().getRam()).isEqualTo(2048); assertThat(node.getHardware().getProcessors().get(0).getCores()).isEqualTo(2); assertThat(node.getHardware().getVolumes().get(0).getSize()).isEqualTo(10); } finally { client.destroyNodesMatching(inGroup(group + "custom")); } }

Target:
public void testCreateNodeWithCustomHardwareUsingMins() throws Exception { Template template = buildTemplate(templateBuilder() .minCores(2).minRam(2048).minDisk(10)); try { NodeMetadata node = getOnlyElement(client.createNodesInGroup(group + "custom", 1, template)); assertThat(node.getHardware().getRam()).isEqualTo(2048); assertThat(node.getHardware().getProcessors().get(0).getCores()).isEqualTo(2); assertThat(node.getHardware().getVolumes().get(0).getSize()).isEqualTo(10); assertThat(node.getHardware().getId()).isEqualTo("cpu=2,ram=2048,disk=10"); } finally { client.destroyNodesMatching(inGroup(group + "custom")); } }
Source:
private void doTestJavaProfile(String javaSpecVersion, String expectedEEName, String releaseName) throws FileNotFoundException, IOException { if (releaseName != null) { File release = getContext().getDataFile("jre/release"); release.getParentFile().mkdirs(); Properties props = new Properties(); props.put("JAVA_PROFILE", releaseName); props.store(new FileOutputStream(release), null); System.setProperty("java.home", release.getParentFile().getAbsolutePath()); } System.setProperty("java.specification.version", javaSpecVersion); File config = OSGiTestsActivator.getContext().getDataFile(getName() + javaSpecVersion); Map<String, Object> configuration = new HashMap<String, Object>(); configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath()); Equinox equinox = new Equinox(configuration); try { equinox.init(); } catch (BundleException e) { fail("Unexpected exception in init()", e); } @SuppressWarnings("deprecation") String osgiEE = equinox.getBundleContext().getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); try { equinox.stop(); } catch (BundleException e) { fail("Unexpected error stopping framework", e); } try { equinox.waitForStop(10000); } catch (InterruptedException e) { fail("Unexpected interrupted exception", e); } assertEquals("Wrong state for SystemBundle", Bundle.RESOLVED, equinox.getState()); assertTrue("Wrong osgi EE: expected: " + expectedEEName + " but was: " + osgiEE, osgiEE.endsWith(expectedEEName)); }

Target:
private void doTestJavaProfile(String javaSpecVersion, String expectedEEName, String releaseName) throws FileNotFoundException, IOException { if (releaseName != null) { File release = getContext().getDataFile("jre/release"); release.getParentFile().mkdirs(); Properties props = new Properties(); props.put("JAVA_PROFILE", releaseName); FileOutputStream propStream = new FileOutputStream(release); try { props.store(propStream, null); } finally { propStream.close(); } System.setProperty("java.home", release.getParentFile().getAbsolutePath()); } System.setProperty("java.specification.version", javaSpecVersion); File config = OSGiTestsActivator.getContext().getDataFile(getName() + javaSpecVersion); Map<String, Object> configuration = new HashMap<String, Object>(); configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath()); Equinox equinox = new Equinox(configuration); try { equinox.init(); } catch (BundleException e) { fail("Unexpected exception in init()", e); } @SuppressWarnings("deprecation") String osgiEE = equinox.getBundleContext().getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); try { equinox.stop(); } catch (BundleException e) { fail("Unexpected error stopping framework", e); } try { equinox.waitForStop(10000); } catch (InterruptedException e) { fail("Unexpected interrupted exception", e); } assertEquals("Wrong state for SystemBundle", Bundle.RESOLVED, equinox.getState()); assertTrue("Wrong osgi EE: expected: " + expectedEEName + " but was: " + osgiEE, osgiEE.endsWith(expectedEEName)); }
Source:
public static void updateMaxMemorySize(VmBase vmBase, Version effectiveCompatibilityVersion) { if (vmBase.getMaxMemorySizeMb() == 0) { final int maxMemorySize = VmCommonUtils.maxMemorySizeWithHotplugInMb(vmBase.getOsId(), effectiveCompatibilityVersion); vmBase.setMaxMemorySizeMb(maxMemorySize); } }

Target:
public static void updateMaxMemorySize(VmBase vmBase, Version effectiveCompatibilityVersion) { final int maxMaxMemorySize = VmCommonUtils.maxMemorySizeWithHotplugInMb(vmBase.getOsId(), effectiveCompatibilityVersion); if (vmBase.getMaxMemorySizeMb() == 0 || vmBase.getMaxMemorySizeMb() > maxMaxMemorySize) { vmBase.setMaxMemorySizeMb(maxMaxMemorySize); } }
Source:
public QueryInterruptedException(Throwable e, String host) { super(e); this.host = host; causeMessage = null; }

Target:
public QueryInterruptedException(Throwable e, String host) { super(e); this.host = host; causeMessage = e.getMessage(); }
Source:
protected boolean sendDataOut(SimpleBinaryItemData data) { logger.warn("{} - Generic device cant send data", this.toString()); return false; }

Target:
protected boolean sendDataOut(SimpleBinaryItemData data) { logger.warn("{} - Generic device can't send data", this.toString()); return false; }
Source:
public Object instantiateItem(ViewGroup container, int position) { layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(layouts[position], container, false); Button btnGrantStoragePerm = (Button) view.findViewById(R.id.btnGrantStoragePerm); if (btnGrantStoragePerm != null) { btnGrantStoragePerm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestStoragePermission(); } }); } Button btnGrantLocationPerm = (Button) view.findViewById(R.id.btnGrantLocationPerm); if (btnGrantLocationPerm != null) { btnGrantLocationPerm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestLocationPermission(); } }); } container.addView(view); return view; }

Target:
public Object instantiateItem(ViewGroup container, int position) { layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(mLayouts[position], container, false); Button btnGrantStoragePerm = (Button) view.findViewById(R.id.btnGrantStoragePerm); if (btnGrantStoragePerm != null) { btnGrantStoragePerm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestStoragePermission(); } }); } Button btnGrantLocationPerm = (Button) view.findViewById(R.id.btnGrantLocationPerm); if (btnGrantLocationPerm != null) { btnGrantLocationPerm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestLocationPermission(); } }); } container.addView(view); return view; }
Source:
private void createServer(Module module, boolean queryParamsAsFormParams) throws Exception { server = Guice.createInjector( new ApplicationNameModule("test-application"), new TestingNodeModule(), explicitJaxrsModule(), new JsonModule(), new ReportingModule(), new TestingHttpServerModule(), new ConfigurationModule(new ConfigurationFactory(ImmutableMap.of("jaxrs.query-params-as-form-params", String.valueOf(queryParamsAsFormParams)))), module) .getInstance(TestingHttpServer.class); server.start(); }

Target:
private void createServer(Module module, boolean queryParamsAsFormParams) throws Exception { Injector injector = bootstrapTest() .withModules( new TestingNodeModule(), explicitJaxrsModule(), new JsonModule(), new ReportingModule(), new TestingHttpServerModule(), module) .setRequiredConfigurationProperty("jaxrs.query-params-as-form-params", String.valueOf(queryParamsAsFormParams)) .initialize(); lifeCycleManager = injector.getInstance(LifeCycleManager.class); server = injector.getInstance(TestingHttpServer.class); }
Source:
public MetaSyntax(String commentStartSyntax, String commentEndSyntax) { this.commentStartRegex = SPACES + commentStartSyntax + SPACES; this.commentEndRegex = SPACES + commentEndSyntax + SPACES; this.beginSolutionRegex = commentStartRegex + BEGIN_SOLUTION + commentEndRegex; this.endSolutionRegex = commentStartRegex + END_SOLUTION + commentEndRegex; this.solutionFileRegex = commentStartRegex + SOLUTION_FILE + commentEndRegex; this.stubRegex = commentStartRegex + STUB + "(.*)" + commentEndRegex; this.stubMarker = commentStartSyntax + STUB; }

Target:
public MetaSyntax(String commentStartSyntax, String commentEndSyntax) { this.commentStartRegex = "^" + SPACES + commentStartSyntax + SPACES; this.commentEndRegex = SPACES + commentEndSyntax + SPACES + "$"; this.beginSolutionRegex = commentStartRegex + BEGIN_SOLUTION + commentEndRegex; this.endSolutionRegex = commentStartRegex + END_SOLUTION + commentEndRegex; this.solutionFileRegex = commentStartRegex + SOLUTION_FILE + commentEndRegex; this.stubMarker = commentStartSyntax + SPACES + STUB + SPACES; this.stubBeginsRegex = commentStartRegex + STUB + "(.*)"; }
Source:
public void evaluateUnaryOperators() { evaluate("+1",1); evaluate("+1.0",1.0); evaluate("+1*2",2); evaluate("+1.0*2.0",2.0); evaluate("2*(+1)",2); evaluate("2.0*(+1.0)",2.0); evaluate("-1",-1); evaluate("-1.0",-1.0); evaluate("-1*2",-2); evaluate("-1.0*2.0",-2.0); evaluate("2*(-1)",-2); evaluate("2.0*(-1.0)",-2.0); try { evaluate("*1",1); throw new AssertionError("Input \"*1\" expected to cause ExprSyntaxException"); } catch (ExprSyntaxException excp) { } try { evaluate("*1.0",1.0); throw new AssertionError("Input \"*1.0\" expected to cause ExprSyntaxException"); } catch (ExprSyntaxException excp) { } try { evaluate("1*",1); throw new AssertionError("Input \"1*\" expected to cause ExprSyntaxException"); } catch (ExprSyntaxException excp) { } try { evaluate("1.0*",1.0); throw new AssertionError("Input \"1.0*\" expected to cause ExprSyntaxException"); } catch (ExprSyntaxException excp) { } try { evaluate("/1",1); throw new AssertionError("Input \"/1\" expected to cause ExprSyntaxException"); } catch (ExprSyntaxException excp) { } try { evaluate("/1.0",1.0); throw new AssertionError("Input \"/1.0\" expected to cause ExprSyntaxException"); } catch (ExprSyntaxException excp) { } try { evaluate("1/",1); throw new AssertionError("Input \"1/\" expected to cause ExprSyntaxException"); } catch (ExprSyntaxException excp) { } try { evaluate("1.0/",1.0); throw new AssertionError("Input \"1.0/\" expected to cause ExprSyntaxException"); } catch (ExprSyntaxException excp) { } }

Target:
public void evaluateUnaryOperators() { evaluate("+1",1); evaluate("+1.0",1.0); evaluate("+1*2",2); evaluate("+1.0*2.0",2.0); evaluate("2*(+1)",2); evaluate("2.0*(+1.0)",2.0); evaluate("-1",-1); evaluate("-1.0",-1.0); evaluate("-1*2",-2); evaluate("-1.0*2.0",-2.0); evaluate("2*(-1)",-2); evaluate("2.0*(-1.0)",-2.0); evaluateAndExpectSyntaxException("*1"); evaluateAndExpectSyntaxException("*1.0"); evaluateAndExpectSyntaxException("1*"); evaluateAndExpectSyntaxException("1.0*"); evaluateAndExpectSyntaxException("/1"); evaluateAndExpectSyntaxException("/1.0"); evaluateAndExpectSyntaxException("1/"); evaluateAndExpectSyntaxException("1.0/"); }
Source:
protected void doPut(Event event) throws InterruptedException { type = TransactionType.PUT; if (!serializedEvents.isPresent()) { serializedEvents = Optional.of(new LinkedList<byte[]>()); } try { if (!tempOutStream.isPresent()) { tempOutStream = Optional.of(new ByteArrayOutputStream()); } if (!writer.isPresent()) { writer = Optional .of(new SpecificDatumWriter<AvroFlumeEvent>( AvroFlumeEvent.class)); } tempOutStream.get().reset(); AvroFlumeEvent e = new AvroFlumeEvent( toCharSeqMap(event.getHeaders()), ByteBuffer.wrap(event .getBody())); encoder = EncoderFactory.get().directBinaryEncoder( tempOutStream.get(), encoder); writer.get().write(e, encoder); serializedEvents.get().add(tempOutStream.get().toByteArray()); } catch (Exception e) { throw new ChannelException("Error while serializing event", e); } }

Target:
protected void doPut(Event event) throws InterruptedException { type = TransactionType.PUT; try { tempOutStream.reset(); AvroFlumeEvent e = new AvroFlumeEvent(toCharSeqMap(event.getHeaders()), ByteBuffer.wrap(event.getBody())); encoder = EncoderFactory.get().directBinaryEncoder(tempOutStream, encoder); writer.write(e, encoder); serializedEvents.add(tempOutStream.toByteArray()); } catch (Exception e) { throw new ChannelException("Error while serializing event", e); } }
Source:
public WorkflowScheme findScheme(String id) throws DotDataException, DotSecurityException { if (!SYSTEM_WORKFLOW_ID.equals(id)) { if (!hasValidLicense() && !this.getFriendClass().isFriend()) { throw new DotSecurityException("You must have a valid license to gain access to schemes."); } } return workFlowFactory.findScheme(id); }

Target:
public WorkflowScheme findScheme(String id) throws DotDataException, DotSecurityException { if (!SYSTEM_WORKFLOW_ID.equals(id)) { if (!hasValidLicense() && !this.getFriendClass().isFriend()) { throw new DotSecurityException("Workflow-Schemes-License-required"); } } return workFlowFactory.findScheme(id); }
Source:
public static Map<String, String> validateCategory(InputStream inputStream) { XSDParser parse = new XSDParser(null); parse.parse(inputStream); XSDSchema schema = parse.getSchema(); return validateCategory(schema); }

Target:
public static Map<String, String> validateCategory(InputStream inputStream) { XSDParser parser = new XSDParser(null); parser.parse(inputStream); XSDSchema schema = parser.getSchema(); return validateCategory(schema); }
Source:
@Override public Object evaluate(List args) throws XPathFunctionException { String result = ""; if (args.size() == 2 && args.get(0) instanceof ArrayList && args.get(1) instanceof String) { ArrayList nodeList = (ArrayList) args.get(0); String delimiter = (String) args.get(1); int length = nodeList.size(); for (int i = 0; i < length; i++) { try { String item = ((Element) nodeList.get(i)).getTextContent(); result = result.concat(item); if (i != length - 1) { result = result.concat(delimiter); } } catch (DOMException e) { throw new HumanTaskRuntimeException( "Invalid arguments:" + args.get(0) + ", for function concatWithDelimiter()", e); } catch (ClassCastException e) { throw new HumanTaskRuntimeException( "Invalid arguments:" + args.get(0) + " , for function concatWithDelimiter()"); } } } else { throw new HumanTaskRuntimeException( "Invalid arguments: " + args + ", for function concatWithDelimiter()"); } return result; }

Target:
public Object evaluate(List args) throws XPathFunctionException { String result = ""; if (args.size() == 2 && args.get(0) instanceof ArrayList && args.get(1) instanceof String) { ArrayList nodeList = (ArrayList) args.get(0); String delimiter = (String) args.get(1); int length = nodeList.size(); for (int i = 0; i < length; i++) { try { String item = ((Element) nodeList.get(i)).getTextContent(); result = result.concat(item); if (i != length - 1) { result = result.concat(delimiter); } } catch (DOMException e) { throw new HumanTaskRuntimeException( "Invalid arguments:" + args.get(0) + ", for function concatWithDelimiter()", e); } catch (ClassCastException e) { throw new HumanTaskRuntimeException( "Invalid arguments:" + args.get(0) + " , for function concatWithDelimiter()",e); } } } else { throw new HumanTaskRuntimeException( "Invalid arguments: " + args + ", for function concatWithDelimiter()"); } return result; }
Source:
protected Result verifyConnectivity(Map<String, Object> parameters) { ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY); try { DdbConfiguration configuration = setProperties(new DdbConfiguration(), parameters); AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(), configuration.getSecretKey()); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withCredentials(credentialsProvider).withRegion(Regions.valueOf(configuration.getRegion())).build(); client.listTables(); } catch (SdkClientException e) { ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage()) .detail("aws_ddb_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName()) .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e); builder.error(errorBuilder.build()); } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception e) { builder.error(ResultErrorBuilder.withException(e).build()); } return builder.build(); }

Target:
protected Result verifyConnectivity(Map<String, Object> parameters) { ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY); try { DdbConfiguration configuration = setProperties(new DdbConfiguration(), parameters); AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(), configuration.getSecretKey()); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withCredentials(credentialsProvider).withRegion(Regions.valueOf(configuration.getRegion())).build(); client.listTables(); } catch (SdkClientException e) { ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage()) .detail("aws_ddb_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName()) .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e); builder.error(errorBuilder.build()); } catch (Exception e) { builder.error(ResultErrorBuilder.withException(e).build()); } return builder.build(); }
Source:
private void transposeLimitExchange(RelOptRuleCall call) { VoltPhysicalLimit coordinatorLimit = (VoltPhysicalLimit) call.rels[0]; Exchange exchange = (Exchange) call.rels[1]; RelNode child = call.rels[2]; VoltRelUtil.buildFragmentLimit(coordinatorLimit, exchange.getDistribution(), child) .ifPresent(fragmentLimit -> { Exchange newExchange = exchange.copy(exchange.getTraitSet(), fragmentLimit, exchange.getDistribution()); VoltPhysicalLimit newCoordinatorLimit = new VoltPhysicalLimit( coordinatorLimit.getCluster(), coordinatorLimit.getTraitSet(), newExchange, coordinatorLimit.getOffset(), coordinatorLimit.getLimit(), true); call.transformTo(newCoordinatorLimit); }); }

Target:
private void transposeLimitExchange(RelOptRuleCall call) { VoltPhysicalLimit coordinatorLimit = (VoltPhysicalLimit) call.rels[0]; Exchange exchange = (Exchange) call.rels[1]; RelNode child = call.rels[2]; VoltRelUtil.buildFragmentLimit(coordinatorLimit, exchange.getDistribution(), child) .ifPresent(fragmentLimit -> { Exchange newExchange = exchange.copy(exchange.getTraitSet(), fragmentLimit, exchange.getDistribution()); VoltPhysicalLimit newCoordinatorLimit = coordinatorLimit.copy( coordinatorLimit.getTraitSet(), newExchange, coordinatorLimit.getOffset(), coordinatorLimit.getLimit(), true); call.transformTo(newCoordinatorLimit); }); }
Source:
public void exec( String name, String containerName, int timeoutMin, String[] command, BiConsumer<String, String> outputConsumer) throws InfrastructureException { final String podName = getPodName(name); final ExecWatchdog watchdog = new ExecWatchdog(); final ByteArrayOutputStream errStream = new ByteArrayOutputStream(ERROR_BUFF_INITIAL_CAP); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(ERROR_BUFF_INITIAL_CAP); try (ExecWatch watch = clientFactory .create(workspaceId) .pods() .inNamespace(namespace) .withName(podName) .inContainer(containerName) .writingOutput(outputStream) .writingError(errStream) .usingListener(watchdog) .exec(encode(command))) { try { watchdog.wait(timeoutMin, TimeUnit.MINUTES); final byte[] output = outputStream.toByteArray(); if (output.length > 0) { final String cmd = Arrays.stream(command).collect(Collectors.joining(" ", "", "\n")); final String err = new String(output, UTF_8); outputConsumer.accept(STDOUT, cmd); outputConsumer.accept(STDERR, err); } final byte[] error = errStream.toByteArray(); if (error.length > 0) { final String cmd = Arrays.stream(command).collect(Collectors.joining(" ", "", "\n")); final String err = new String(error, UTF_8); outputConsumer.accept(STDOUT, cmd); outputConsumer.accept(STDERR, err); throw new InfrastructureException(err); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new InfrastructureException(ex.getMessage(), ex); } } catch (KubernetesClientException ex) { throw new KubernetesInfrastructureException(ex); } }

Target:
public void exec( String name, String containerName, int timeoutMin, String[] command, BiConsumer<String, String> outputConsumer) throws InfrastructureException { final String podName = getPodName(name); final ExecWatchdog watchdog = new ExecWatchdog(); final ByteArrayOutputStream errStream = new ByteArrayOutputStream(ERROR_BUFF_INITIAL_CAP); try (ExecWatch watch = clientFactory .create(workspaceId) .pods() .inNamespace(namespace) .withName(podName) .inContainer(containerName) .writingError(errStream) .usingListener(watchdog) .exec(encode(command))) { try { watchdog.wait(timeoutMin, TimeUnit.MINUTES); final byte[] error = errStream.toByteArray(); if (error.length > 0) { final String cmd = Arrays.stream(command).collect(Collectors.joining(" ", "", "\n")); final String err = new String(error, UTF_8); outputConsumer.accept(STDOUT, cmd); outputConsumer.accept(STDERR, err); throw new InfrastructureException(err); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new InfrastructureException(ex.getMessage(), ex); } } catch (KubernetesClientException ex) { throw new KubernetesInfrastructureException(ex); } }
Source:
private void setupMessageHandlers() { bridge.addListener("requestSection", new CommunicationBridge.JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { try { int index = messagePayload.optInt("index"); if (index >= page.getSections().size()) { bridge.sendMessage("noMoreSections", new JSONObject()); } else { JSONObject wrapper = new JSONObject(); wrapper.put("section", page.getSections().get(index).toJSON()); wrapper.put("index", index); wrapper.put("isLast", index == page.getSections().size() - 1); wrapper.put("fragment", page.getTitle().getFragment()); bridge.sendMessage("displaySection", wrapper); if (section != null && index == page.getSections().size() - 1) { JSONObject payload = new JSONObject(); try { payload.put("anchor", section.isLead() ? "heading_" + section.getId() : section.getAnchor()); } catch (JSONException e) { throw new RuntimeException(e); } bridge.sendMessage("scrollToSection", payload); section = null; } } } catch (JSONException e) { throw new RuntimeException(e); } } }); boolean isAnonEditingDisabled = app.getRemoteConfig().getConfig().has("disableAnonEditing") && app.getRemoteConfig().getConfig().optBoolean("disableAnonEditing") && !app.getUserInfoStorage().isLoggedIn(); if (isAnonEditingDisabled || title.isFilePage()) { bridge.sendMessage("hideEditButtons", new JSONObject()); } }

Target:
private void setupMessageHandlers() { bridge.addListener("requestSection", new CommunicationBridge.JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { try { int index = messagePayload.optInt("index"); if (index >= page.getSections().size()) { bridge.sendMessage("noMoreSections", new JSONObject()); } else { JSONObject wrapper = new JSONObject(); wrapper.put("section", page.getSections().get(index).toJSON()); wrapper.put("index", index); wrapper.put("isLast", index == page.getSections().size() - 1); wrapper.put("fragment", page.getTitle().getFragment()); bridge.sendMessage("displaySection", wrapper); if (scrollSectionId != -1 && index == page.getSections().size() - 1 && tocHandler != null) { Section scrollSection = page.getSections().get(scrollSectionId); tocHandler.scrollToSection(scrollSection); scrollSectionId = -1; } } } catch (JSONException e) { throw new RuntimeException(e); } } }); boolean isAnonEditingDisabled = app.getRemoteConfig().getConfig().has("disableAnonEditing") && app.getRemoteConfig().getConfig().optBoolean("disableAnonEditing") && !app.getUserInfoStorage().isLoggedIn(); if (isAnonEditingDisabled || title.isFilePage()) { bridge.sendMessage("hideEditButtons", new JSONObject()); } }
Source:
public AuthenticationProvider oidcAuthenticationProvider() { SimpleGrantedAuthority ROLE_ADMIN = new SimpleGrantedAuthority("ROLE_ADMIN"); SimpleGrantedAuthority ROLE_COMMITTEE = new SimpleGrantedAuthority("ROLE_COMMITTEE"); SimpleGrantedAuthority ROLE_USER = new SimpleGrantedAuthority("ROLE_USER"); OIDCAuthenticationProvider authenticationProvider = new OIDCAuthenticationProvider(); authenticationProvider.setUserInfoFetcher(new CHUserInfoFetcher()); authenticationProvider.setAuthoritiesMapper((idToken, userInfo) -> { if (userInfo instanceof CHUserInfo) { CHUserInfo info = (CHUserInfo) userInfo; if (properties.getAdminGroups().stream().anyMatch(info.getLdapGroups()::contains)) { return ImmutableSet.of(ROLE_ADMIN, ROLE_USER, ROLE_COMMITTEE); } else if (info.getLdapGroups().stream().filter(group -> group.equals("users")).count() > 0) { return ImmutableSet.of(ROLE_USER, ROLE_COMMITTEE); } else { return ImmutableSet.of(ROLE_USER); } } throw new AccessDeniedException("Invalid user info!"); }); return authenticationProvider; }

Target:
public AuthenticationProvider oidcAuthenticationProvider() { final SimpleGrantedAuthority roleAdmin = new SimpleGrantedAuthority("ROLE_ADMIN"); final SimpleGrantedAuthority roleCommittee = new SimpleGrantedAuthority("ROLE_COMMITTEE"); final SimpleGrantedAuthority roleUser = new SimpleGrantedAuthority("ROLE_USER"); OIDCAuthenticationProvider authenticationProvider = new OIDCAuthenticationProvider(); authenticationProvider.setUserInfoFetcher(new CHUserInfoFetcher()); authenticationProvider.setAuthoritiesMapper((idToken, userInfo) -> { if (userInfo instanceof CHUserInfo) { CHUserInfo info = (CHUserInfo) userInfo; if (properties.getAdminGroups().stream().anyMatch(info.getLdapGroups()::contains)) { return ImmutableSet.of(roleAdmin, roleUser, roleCommittee); } else if (info.getLdapGroups().stream().filter(group -> !group.equals("users")).count() > 0) { return ImmutableSet.of(roleUser, roleCommittee); } else { return ImmutableSet.of(roleUser); } } throw new AccessDeniedException("Invalid user info!"); }); return authenticationProvider; }
Source:
public void onResume() { super.onResume(); ActivityId.trackLastActivity(ActivityId.COMMENT_DETAIL); AnalyticsUtils.trackCommentActionWithSiteDetails( Stat.COMMENT_VIEWED, mCommentSource.toAnalyticsCommentActionSource(), mSite); if (!TextUtils.isEmpty(mRestoredNoteId)) { setNote(mRestoredNoteId); mRestoredNoteId = null; } }

Target:
public void onResume() { super.onResume(); ActivityId.trackLastActivity(ActivityId.COMMENT_DETAIL); if (!TextUtils.isEmpty(mRestoredNoteId)) { setNote(mRestoredNoteId); mRestoredNoteId = null; } }