auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean userExtSourceExists(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { Utils.notNull(userExtSource, "userExtSource"); Utils.notNull(userExtSource.getLogin(), "userExtSource.getLogin"); Utils.notNull(userExtSource.getExtSource(), "userExtSource.getExtSource"); boolean exists = false; try { if (userExtSource.getUserId() >= 0) { exists = 1 == jdbc.queryForInt("select 1 from user_ext_sources where login_ext=? and ext_sources_id=? and user_id=?", userExtSource.getLogin(), userExtSource.getExtSource().getId(), userExtSource.getUserId()); } else { exists = 1 == jdbc.queryForInt("select 1 from user_ext_sources where login_ext=? and ext_sources_id=?", userExtSource.getLogin(), userExtSource.getExtSource().getId()); } } catch(EmptyResultDataAccessException ex) { exists = false; } catch(RuntimeException ex) { throw new InternalErrorException(ex); } try { if (!exists && userExtSource.getId() > 0) { exists = 1 == jdbc.queryForInt("select 1 from user_ext_sources where id=?", userExtSource.getId()); } <START> return exists; <END> } catch(EmptyResultDataAccessException ex) { return false; } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }</code><technical_language>I afraid this specific implementation return "true" if is userExtSources wrong ID (id of user ext source) correct combination of login extSourceId. solution create implementation of this method: checking id of user ext source, checking login other attributes implementation need higher level</technical_language>

Target:
public boolean userExtSourceExists(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { Utils.notNull(userExtSource, "userExtSource"); Utils.notNull(userExtSource.getLogin(), "userExtSource.getLogin"); Utils.notNull(userExtSource.getExtSource(), "userExtSource.getExtSource"); try { if (userExtSource.getUserId() >= 0) { return 1 == jdbc.queryForInt("select 1 from user_ext_sources where login_ext=? and ext_sources_id=? and user_id=?", userExtSource.getLogin(), userExtSource.getExtSource().getId(), userExtSource.getUserId()); } else { return 1 == jdbc.queryForInt("select 1 from user_ext_sources where login_ext=? and ext_sources_id=?", userExtSource.getLogin(), userExtSource.getExtSource().getId()); } } catch(EmptyResultDataAccessException ex) { return false; } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
<code>public String toString() { if (previous != null) { double percentChange = 0.0; <START> boolean isIntersecting = scoresIntersecting(); <END> if (isIntersecting) { regression = 0; } else { percentChange = (score / previous.score - 1) * 100.0; } String changeType = regression == -1 ? "regression" : regression == 0 ? "no change" : "improvement"; if (isIntersecting) { return String.format( "%s: (score:%f error:%f) vrs (score:%f error:%f) (%f%%: %s due to score error intersection)%n", benchmark, score, scoreError, previous.score, previous.scoreError, percentChange, changeType); } return String.format("%s: %f vrs %f (%f%%: %s)%n", benchmark, score, previous.score, percentChange, changeType); } else { return String.format("%s: %f%n", benchmark, score); } }</code><technical_language>This new code is testing benchmarks preferable if logic moved comparison method: java public int compareTo(Benchmark other) { // code compares benchmarks account of score error toString() need change. java public void setPrevious(Benchmark previous) { this.previous = previous; regression = compareTo(previous); } account of error</technical_language>

Target:
public String toString() { if (previous != null) { double percentChange = regression == 0 ? 0.0 : (score / previous.score - 1) * 100.0; String changeType = regression == -1 ? "regression" : regression == 0 ? "no change" : "improvement"; return String.format("%s: %f vrs %f (%f%%: %s)%n", benchmark, score, previous.score, percentChange, changeType); } else { return String.format("%s: %f%n", benchmark, score); } }
Source:
<code><START> protected AggregateEndpointDelivery<I, A, EventEnvelope> getEndpointDelivery( <END> EventEnvelope envelope) { return repository().getEventEndpointDelivery(); }</code><technical_language>Please fix wrapping</technical_language>

Target:
getEndpointDelivery(EventEnvelope envelope) { return repository().getEventEndpointDelivery(); }
Source:
<code>protected void cleanScheduler() throws NotConnectedException, PermissionException, UnknownJobException { scheduler = RestFuncTHelper.getScheduler(); SchedulerState state = scheduler.getState(); System.out.println("Cleaning scheduler."); <START> List<JobState> aliveJobsStates = new ArrayList<>(); <END> aliveJobsStates.addAll(state.getPendingJobs()); aliveJobsStates.addAll(state.getRunningJobs()); List<JobState> finishedJobsStates = new ArrayList<>(); finishedJobsStates.addAll(state.getFinishedJobs()); for (JobState jobState : aliveJobsStates) { JobId jobId = jobState.getId(); try { System.out.println("Killing job " + jobId); scheduler.killJob(jobId); } catch (Exception ignored) { } System.out.println("Removing job " + jobId); scheduler.removeJob(jobId); } for (JobState jobState : finishedJobsStates) { JobId jobId = jobState.getId(); System.out.println("Removing job " + jobId); scheduler.removeJob(jobId); } }</code><technical_language>Initialize capacity</technical_language>

Target:
protected void cleanScheduler() throws NotConnectedException, PermissionException, UnknownJobException { scheduler = RestFuncTHelper.getScheduler(); SchedulerState state = scheduler.getState(); System.out.println("Cleaning scheduler."); List<JobState> aliveJobsStates = new ArrayList<>(state.getPendingJobs().size() + state.getRunningJobs().size()); aliveJobsStates.addAll(state.getPendingJobs()); aliveJobsStates.addAll(state.getRunningJobs()); List<JobState> finishedJobsStates = new ArrayList<>(state.getFinishedJobs().size()); finishedJobsStates.addAll(state.getFinishedJobs()); for (JobState jobState : aliveJobsStates) { JobId jobId = jobState.getId(); try { System.out.println("Killing job " + jobId); scheduler.killJob(jobId); } catch (Exception ignored) { } System.out.println("Removing killed job " + jobId); scheduler.removeJob(jobId); } for (JobState jobState : finishedJobsStates) { JobId jobId = jobState.getId(); System.out.println("Removing finished job " + jobId); scheduler.removeJob(jobId); } }
Source:
<code>protected boolean canDoAction() { <START> if (getVm().getStatus() != VMStatus.Up) { <END> failCanDoAction(VdcBllMessages.VAR__VM_STATUS__UP); } if (getVm().getNumOfCpus() > getVds().getCpuCores() * getVds().getCpuSockets() * getVds().getCpuThreads()) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CPUS); } if (!FeatureSupported.hotPlugCpu(getVm().getVdsGroupCompatibilityVersion(), getVm().getClusterArch())) { failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); } return true; }</code><technical_language>please verify vm is null</technical_language>

Target:
protected boolean canDoAction() { if (getVm() == null) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (getVm().getStatus() != VMStatus.Up) { failCanDoAction(VdcBllMessages.VAR__VM_STATUS__UP); } if (getParameters().getVm().getNumOfCpus() > SlaValidator.getEffectiveCpuCores(getVds())) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CPUS); } if (!FeatureSupported.hotPlugCpu(getVm().getVdsGroupCompatibilityVersion(), getVm().getClusterArch())) { failCanDoAction(VdcBllMessages.HOT_PLUG_IS_NOT_SUPPORTED); } return true; }
Source:
<code>public void copySupplementaryFolder(IFolder destination) { IFolder oldSupplFolder = getTraceSupplementaryFolder(getResourceName()); if (oldSupplFolder.exists()) { try { oldSupplFolder.copy(destination.getFullPath(), true, new NullProgressMonitor()); } catch (CoreException e) { <START> Activator.getDefault().logError("Error copying supplementary folder " + oldSupplFolder, e); END> } } }</code><technical_language>externalize</technical_language>

Target:
public void copySupplementaryFolder(IFolder destination) { IFolder oldSupplFolder = getTraceSupplementaryFolder(getResourceName()); if (oldSupplFolder.exists()) { try { oldSupplFolder.copy(destination.getFullPath(), true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError(Messages.TmfCommonProjectElement_ErrorCopyingSF + oldSupplFolder, e); } } }
Source:
<code>public void implicitLinkWithSymbols() { <START> String[] evilurls = new String[] { <END> "<LINK_6>.", "<LINK_6>.a", "<LINK_3>", "<LINK_4>", "<LINK_4>a", "<LINK_6>,", "<LINK_6>,a", "<LINK_6>;", "<LINK_6>;a", "<LINK_0>", "<LINK_0>a", "<LINK_1>", "<LINK_1>a", }; for (String url : evilurls) { assertEquals("<p><a href=\"" + url + "\">" + url + "</a></p>\n", parseToHtml(url) ); } }</code><technical_language>suggest renaming "evil" else "problematic", "evil" misinterpreted offense</technical_language>

Target:
public void implicitLinkWithSymbols() { String[] problematicUrls = new String[] { "<LINK_6>.", "<LINK_6>.a", "<LINK_3>", "<LINK_4>", "<LINK_4>a", "<LINK_6>,", "<LINK_6>,a", "<LINK_6>;", "<LINK_6>;a", "<LINK_0>", "<LINK_0>a", "<LINK_1>", "<LINK_1>a", }; for (String url : problematicUrls) { assertEquals("<p><a href=\"" + url + "\">" + url + "</a></p>\n", parseToHtml(url)); } }
Source:
<code>public Dialog onCreateDialog(final Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(viewUser.getName()) .setItems(R.array.user_options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { <START> if (which == 0) { <END> if (listener != null) { listener.onEditUser(viewUser); } } else { if (listener != null) { listener.onDeleteUser(viewUser); } } dismiss(); } }); return builder.create(); }</code><technical_language>more clear if a more descriptive name 0 a descriptive constant definition</technical_language>

Target:
public Dialog onCreateDialog(final Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(viewUser.getName()) .setItems(R.array.user_options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int selectedOption) { if (selectedOption == OPTION_EDIT_USER) { if (listener != null) { listener.onEditUser(viewUser); } } else { if (listener != null) { listener.onDeleteUser(viewUser); } } dismiss(); } }); return builder.create(); }
Source:
<code>public SpongeStatisticData() { <START> this(Maps.<Statistic, Long>newLinkedHashMap()); <END> }</code><technical_language>Casting necessary</technical_language>

Target:
public SpongeStatisticData() { this(Maps.newLinkedHashMap()); }
Source:
<code>public int run() throws IOException { Preconditions.checkArgument(hdfs || hbase || zk, "At least one service must be specified."); Preconditions .checkArgument(localBaseFsLocation != null, "Minicluster directory and a valid zookeeper client port are required."); MiniCluster.Builder builder = new MiniCluster.Builder() .localBaseFsLocation(localBaseFsLocation).clean(clean).conf(conf); if (forceBindIP != null) { builder.forceBindIP(forceBindIP); } if (hdfs) { builder.addHdfsService(); } if (zk) { builder.addZookeeperService(zkClientPort); } if (hbase) { builder.addHBaseService(); } final MiniCluster miniCluster = builder.build(); final Object wait = new Object(); Thread exitThread = new Thread() { @Override public void run() { try { miniCluster.stop(); } catch (Throwable e) { console.error("Error stopping mini cluster. Exiting anyways...", e); } <START> wait.notify(); <END> } }; Runtime.getRuntime().addShutdownHook(exitThread); miniCluster.start(); try { synchronized(wait) { wait.wait(); } } catch (InterruptedException e) { throw new IOException(e); } return 0; }</code><technical_language>notify() need called a synchronized block? I rewrite <LINK_0></technical_language>

Target:
public int run() throws IOException { Preconditions.checkArgument(services.size() > 0, "At least one service must be specified."); Preconditions.checkArgument(workDir != null, "A valid work dir is required."); MiniCluster.Builder builder = new MiniCluster.Builder().workDir(workDir) .clean(clean).hadoopConf(conf).bindIP(bindIP) .namenodeRpcPort(namenodeRpcPort).zkPort(zkPort); for (String serviceName : services) { if (simpleServiceNameMap.containsKey(serviceName)) { serviceName = simpleServiceNameMap.get(serviceName); } try { builder.addService((Class<? extends Service>) Class .forName(serviceName)); } catch (ClassNotFoundException e) { console.error("Unknown service class specified: " + serviceName); throw new RuntimeException(e); } } for (Entry<String, String> serviceParam : serviceParams.entrySet()) { builder.setServiceConfig(serviceParam.getKey(), serviceParam.getValue()); } final MiniCluster miniCluster = builder.build(); final CountDownLatch doneSignal = new CountDownLatch(1); Thread exitThread = new Thread() { @Override public void run() { try { miniCluster.stop(); } catch (Throwable e) { console.error("Error stopping mini cluster. Exiting anyways...", e); } doneSignal.countDown(); } }; Runtime.getRuntime().addShutdownHook(exitThread); try { miniCluster.start(); doneSignal.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return 1; } return 0; }
Source:
<code>public void run() { int attempt = 1; AbstractRerunPolicy policy = new ExpBackoffPolicy(); Frequency frequency = new Frequency("minutes(1)"); while (!Thread.currentThread().isInterrupted()) { T message = null; try { try { message = handler.takeFromQueue(); attempt = 1; } catch (FalconException e) { if (ExceptionUtils.getRootCause(e) instanceof InterruptedException){ LOG.info("Rerun handler daemon has been interrupted"); return; } else { LOG.error("Error while reading message from the queue", e); GenericAlert.alertRerunConsumerFailed( "Error while reading message from the queue: ", e); Thread.sleep(policy.getDelay(frequency, attempt)); handler.reconnect(); attempt++; continue; } } CurrentUser.authenticate(message.getWorkflowUser()); AbstractWorkflowEngine wfEngine = handler.getWfEngine(message.getEntityType(), message.getEntityName()); String jobStatus = wfEngine.getWorkflowStatus( message.getClusterName(), message.getWfId()); handleRerun(message.getClusterName(), jobStatus, message, message.getEntityType(), message.getEntityName()); } catch (Throwable e) { if (e instanceof EntityNotRegisteredException) { LOG.warn("Entity of type doesn't exist in config store. Rerun " + "cannot be done for workflow ", message.getEntityName(), message.getEntityType(), message.getWfId()); <START> } <END> LOG.error("Error in rerun consumer", e); } } }</code><technical_language>continue else message get logged. (Error in rerun consumer)</technical_language>

Target:
public void run() { int attempt = 1; AbstractRerunPolicy policy = new ExpBackoffPolicy(); Frequency frequency = new Frequency("minutes(1)"); while (!Thread.currentThread().isInterrupted()) { T message = null; try { try { message = handler.takeFromQueue(); attempt = 1; } catch (FalconException e) { if (ExceptionUtils.getRootCause(e) instanceof InterruptedException){ LOG.info("Rerun handler daemon has been interrupted"); return; } else { LOG.error("Error while reading message from the queue", e); GenericAlert.alertRerunConsumerFailed( "Error while reading message from the queue: ", e); Thread.sleep(policy.getDelay(frequency, attempt)); handler.reconnect(); attempt++; continue; } } CurrentUser.authenticate(message.getWorkflowUser()); AbstractWorkflowEngine wfEngine = handler.getWfEngine(message.getEntityType(), message.getEntityName()); String jobStatus = wfEngine.getWorkflowStatus( message.getClusterName(), message.getWfId()); handleRerun(message.getClusterName(), jobStatus, message, message.getEntityType(), message.getEntityName()); } catch (Throwable e) { if (e instanceof EntityNotRegisteredException) { LOG.warn("Entity of type doesn't exist in config store. Rerun " + "cannot be done for workflow ", message.getEntityName(), message.getEntityType(), message.getWfId()); continue; } LOG.error("Error in rerun consumer", e); } } }
Source:
<code>public DirectConnectionConfig() { <START> this.connectionEndpointRediscoveryEnabled = true; <END> this.connectTimeout = DEFAULT_CONNECT_TIMEOUT; this.idleConnectionTimeout = Duration.ZERO; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_CONNECTION; this.requestTimeout = DEFAULT_REQUEST_TIMEOUT; }</code><technical_language>mention this default in getter setter</technical_language>

Target:
public DirectConnectionConfig() { this.connectionEndpointRediscoveryEnabled = DEFAULT_CONNECTION_ENDPOINT_REDISCOVERY_ENABLED; this.connectTimeout = DEFAULT_CONNECT_TIMEOUT; this.idleConnectionTimeout = Duration.ZERO; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_CONNECTION; this.requestTimeout = DEFAULT_REQUEST_TIMEOUT; }
Source:
<code><START> TraceIdSampler traceIdSampler() { <END> float retain = 1.0f; return TraceIdSampler.create(retain); }</code><technical_language>this correlate <LINK_0></technical_language>

Target:
Sampler traceIdSampler() { return Sampler.create(this.sampleRate); }
Source:
<code>public void testGetConfiguration() throws InterruptedException { <START> Thread.sleep(15000); <END> String result = vpnApi().getConfiguration(currentVpn.id()); assertNotNull(result); }</code><technical_language>Is this needed? Is a more deterministic of waiting</technical_language>

Target:
public void testGetConfiguration() throws InterruptedException { assertVPNAvailable(currentVpn); ZipInputStream result = vpnApi().getConfiguration(currentVpn.id()); assertNotNull(result); }
Source:
<code>private NestedProjectManager() { refreshProjectsList(); ResourcesPlugin.getWorkspace().addResourceChangeListener(new IResourceChangeListener() { @Override public void resourceChanged(IResourceChangeEvent event) { if <START> (event.getDelta().getResource().getType() <END> == IResource.PROJECT || event.getDelta().getResource().getType() == IResource.ROOT) { refreshProjectsList(); } } }, IResourceChangeEvent.POST_CHANGE); }</code><technical_language>getDelta() null</technical_language>

Target:
private NestedProjectManager() { refreshProjectsList(); ResourcesPlugin.getWorkspace().addResourceChangeListener(new IResourceChangeListener() { @Override public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); IResource resource = null; if (delta != null) { resource = delta.getResource(); } if (resource != null && (resource.getType() == IResource.PROJECT || resource.getType() == IResource.ROOT)) { refreshProjectsList(); } } }, IResourceChangeEvent.POST_CHANGE); }
Source:
<code>protected byte[] getAPIPacketSpecificData() { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { os.write(new byte[]{0x00, 0x00, 0x00, 0x00}); os.write(destAddress.getValue()); os.write(transmitOptions); <START> os.write(ByteUtils.stringToByteArray(command)); <END> if (parameter != null) os.write(parameter); } catch (IOException e) { logger.error(e.getMessage(), e); } return os.toByteArray(); }</code><technical_language>os.write(command.getBytes());</technical_language>

Target:
protected byte[] getAPIPacketSpecificData() { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { os.write(new byte[]{0x00, 0x00, 0x00, 0x00}); os.write(destAddress.getValue()); os.write(transmitOptions); os.write(command.getBytes()); if (parameter != null) os.write(parameter); } catch (IOException e) { logger.error(e.getMessage(), e); } return os.toByteArray(); }
Source:
<code><START> private File getInstallDir() { <END> Location installLocation = Platform.getInstallLocation(); if (installLocation == null) { return null; } URL url = installLocation.getURL(); if (url == null) { return null; } try { return new File(url.toURI()); } catch (URISyntaxException e) { return null; } }</code><technical_language>return Optional<File></technical_language>

Target:
private Optional<File> getInstallDir() throws URISyntaxException { Location installLocation = Platform.getInstallLocation(); if (installLocation == null) { return Optional.absent(); } URL url = installLocation.getURL(); if (url == null) { return Optional.absent(); } return Optional.of(new File(url.toURI())); }
Source:
<code>public TemplateService get() { final List<TemplateLoader> templateLoaders = configuration.getConfigList("handlebars.templateLoaders") .stream() .map(loaderConfig -> { final String type = loaderConfig.getString("type"); final String path = loaderConfig.getString("path"); if ("classpath".equals(type)) { return new ClassPathTemplateLoader(path); } else if ("file".equals(type)) { return new FileTemplateLoader(path); } else { <START> throw new RuntimeException("cannot create template loader for " + loaderConfig); <END> } }) .collect(toList()); Logger.debug("Provide HandlebarsTemplateService: " + templateLoaders.stream().map(loader -> loader.getPrefix()).collect(joining(", "))); return HandlebarsTemplateService.of(templateLoaders); }</code><technical_language>do SunriseInitializationException RuntimeException</technical_language>

Target:
public TemplateService get() { final List<TemplateLoader> templateLoaders = configuration.getConfigList("handlebars.templateLoaders") .stream() .map(loaderConfig -> { final String type = loaderConfig.getString("type"); final String path = loaderConfig.getString("path"); if ("classpath".equals(type)) { return new ClassPathTemplateLoader(path); } else if ("file".equals(type)) { return new FileTemplateLoader(path); } else { throw new RuntimeException("cannot build template loader for " + loaderConfig); } }) .collect(toList()); Logger.debug("Provide HandlebarsTemplateService: " + templateLoaders.stream().map(loader -> loader.getPrefix()).collect(joining(", "))); return HandlebarsTemplateService.of(templateLoaders); }
Source:
<code>public int execute(ExecutionContext context) throws IOException, InterruptedException { ImmutableList<String> command = createCommand(); <START> ProcessBuilder processBuilder = new ProcessBuilder(command); <END> Map<String, String> env = processBuilder.environment(); env.clear(); env.putAll(context.getEnvironment()); processBuilder.directory(filesystem.getRootPath().toAbsolutePath().toFile()); int exitCode = -1; try { exitCode = context.getProcessExecutor().execute(processBuilder.start()).getExitCode(); } catch (IOException e) { e.printStackTrace(context.getStdErr()); } return exitCode; }</code><technical_language>things: - This change spurious - adding new of ProcessBuilder in codebase. do this here, letting know. ProcessExecutor ListeningProcessExecutor instead</technical_language>

Target:
public int execute(ExecutionContext context) throws IOException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder(createCommand()); Map<String, String> env = processBuilder.environment(); env.clear(); env.putAll(context.getEnvironment()); processBuilder.directory(filesystem.getRootPath().toAbsolutePath().toFile()); int exitCode = -1; try { exitCode = context.getProcessExecutor().execute(processBuilder.start()).getExitCode(); } catch (IOException e) { e.printStackTrace(context.getStdErr()); } return exitCode; }
Source:
<code>public void testDatastreamUpdate() throws Exception { Datastream datastream = generateDatastream(1200); DatastreamRestClient restClient = createRestClient(); restClient.createDatastream(datastream); try { restClient.updateDatastream(generateDatastream(1201)); Assert.fail("Update should fail for non exist datastream"); } catch (DatastreamRuntimeException e) { } Datastream initializedDatastream = restClient.waitTillDatastreamIsInitialized(datastream.getName(), WAIT_TIMEOUT_MS); initializedDatastream.getMetadata().put("key", "testDatastreamUpdate"); restClient.updateDatastream(initializedDatastream); Assert.assertTrue(PollUtils.poll(() -> restClient.getDatastream(initializedDatastream.getName()) .getMetadata() .get("key") .equals("testDatastreamUpdate"), 100, 10000)); Datastream datastream2 = generateDatastream(1201); restClient.createDatastream(datastream2); Datastream initializedDatastream2 = restClient.waitTillDatastreamIsInitialized(datastream2.getName(), WAIT_TIMEOUT_MS); <START> initializedDatastream2.getMetadata().put("key", "testDatastreamUpdate"); <END> restClient.updateDatastream(Arrays.asList(initializedDatastream, initializedDatastream2)); Assert.assertTrue(PollUtils.poll(() -> restClient.getDatastream(initializedDatastream2.getName()) .getMetadata() .get("key") .equals("testDatastreamUpdate"), 100, 10000)); restClient.shutdown(); }</code><technical_language>I suggest update key "testDatastreamUpdate2" avoid conflict previous value. please update datastream for a time here</technical_language>

Target:
public void testDatastreamUpdate() throws Exception { Datastream datastream = generateDatastream(1200); DatastreamRestClient restClient = createRestClient(); restClient.createDatastream(datastream); try { restClient.updateDatastream(generateDatastream(1201)); Assert.fail("Update should fail for non exist datastream"); } catch (DatastreamRuntimeException e) { } Datastream initializedDatastream = restClient.waitTillDatastreamIsInitialized(datastream.getName(), WAIT_TIMEOUT_MS); initializedDatastream.getMetadata().put("key", "testDatastreamUpdate"); restClient.updateDatastream(initializedDatastream); Assert.assertTrue(PollUtils.poll(() -> restClient.getDatastream(initializedDatastream.getName()) .getMetadata() .get("key") .equals("testDatastreamUpdate"), 100, 10000)); Datastream datastream2 = generateDatastream(1201); restClient.createDatastream(datastream2); Datastream initializedDatastream2 = restClient.waitTillDatastreamIsInitialized(datastream2.getName(), WAIT_TIMEOUT_MS); initializedDatastream2.getMetadata().put("key", "testDatastreamUpdate2"); initializedDatastream.getMetadata().put("key", "testDatastreamUpdate3"); restClient.updateDatastream(Arrays.asList(initializedDatastream, initializedDatastream2)); Assert.assertTrue(PollUtils.poll(() -> restClient.getDatastream(initializedDatastream.getName()) .getMetadata() .get("key") .equals("testDatastreamUpdate3"), 100, 10000)); Assert.assertTrue(PollUtils.poll(() -> restClient.getDatastream(initializedDatastream2.getName()) .getMetadata() .get("key") .equals("testDatastreamUpdate2"), 100, 10000)); restClient.shutdown(); }
Source:
<code><START> private boolean verifyAggregationOrderBy(Optional<OrderingScheme> orderingScheme, Optional<OrderBy> expectedSortOrder) <END> { if (orderingScheme.isPresent() && expectedSortOrder.isPresent()) { return verifyAggregationOrderBy(orderingScheme.get(), expectedSortOrder.get()); } return orderingScheme.isPresent() == expectedSortOrder.isPresent(); }</code><technical_language>static</technical_language>

Target:
private static boolean verifyAggregationOrderBy(Optional<OrderingScheme> orderingScheme, Optional<OrderBy> expectedSortOrder) { if (orderingScheme.isPresent() && expectedSortOrder.isPresent()) { return verifyAggregationOrderBy(orderingScheme.get(), expectedSortOrder.get()); } return orderingScheme.isPresent() == expectedSortOrder.isPresent(); }
Source:
<code>public void execute(JobExecutionContext ctx) throws JobExecutionException { JobDataMap dataMap = ctx.getJobDetail().getJobDataMap(); Boolean allhosts=(Boolean) dataMap.get("allhosts"); List<Host> hosts=(List<Host>) dataMap.get("hosts"); List<Language> langs=(List<Language>) dataMap.get("langs"); Boolean incremental= (dataMap.get("incremental") != null) ? (Boolean) dataMap.get("incremental") : false; try { String date = DateUtil.getCurrentDate(); ActivityLogger.logInfo(getClass(), "Job Started", "User:" + APILocator.getUserAPI().getSystemUser().getUserId() + "; Date: " + date + "; Job Identifier: timemachine" ); AdminLogger.log(getClass(), "Job Started", "User:" + APILocator.getUserAPI().getSystemUser().getUserId()+ "; Date: " + date + "; Job Identifier: timemachine" ); if(allhosts) hosts=APILocator.getHostAPI().findAll(APILocator.getUserAPI().getSystemUser(), false); APILocator.getTimeMachineAPI().startTimeMachine(hosts, langs,incremental); date = DateUtil.getCurrentDate(); ActivityLogger.logInfo(getClass(), "Job Finished", "User:" + APILocator.getUserAPI().getSystemUser().getUserId() + "; Date: " + date + "; Job Identifier: timemachine" ); AdminLogger.log(getClass(), "Job Finished", "User:" + APILocator.getUserAPI().getSystemUser().getUserId()+ "; Date: " + date + "; Job Identifier: timemachine" ); } catch(Exception ex) { throw new JobExecutionException(ex); } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.warn(this, e.getMessage(), e); } <START> } <END> }</code><technical_language>Remove entire wrapper finally block</technical_language>

Target:
public void execute(JobExecutionContext ctx) throws JobExecutionException { JobDataMap dataMap = ctx.getJobDetail().getJobDataMap(); Boolean allhosts=(Boolean) dataMap.get("allhosts"); List<Host> hosts=(List<Host>) dataMap.get("hosts"); List<Language> langs=(List<Language>) dataMap.get("langs"); Boolean incremental= (dataMap.get("incremental") != null) ? (Boolean) dataMap.get("incremental") : false; try { String date = DateUtil.getCurrentDate(); ActivityLogger.logInfo(getClass(), "Job Started", "User:" + APILocator.getUserAPI().getSystemUser().getUserId() + "; Date: " + date + "; Job Identifier: timemachine" ); AdminLogger.log(getClass(), "Job Started", "User:" + APILocator.getUserAPI().getSystemUser().getUserId()+ "; Date: " + date + "; Job Identifier: timemachine" ); if(allhosts) hosts=APILocator.getHostAPI().findAll(APILocator.getUserAPI().getSystemUser(), false); APILocator.getTimeMachineAPI().startTimeMachine(hosts, langs,incremental); date = DateUtil.getCurrentDate(); ActivityLogger.logInfo(getClass(), "Job Finished", "User:" + APILocator.getUserAPI().getSystemUser().getUserId() + "; Date: " + date + "; Job Identifier: timemachine" ); AdminLogger.log(getClass(), "Job Finished", "User:" + APILocator.getUserAPI().getSystemUser().getUserId()+ "; Date: " + date + "; Job Identifier: timemachine" ); } catch(Exception ex) { throw new JobExecutionException(ex); } }
Source:
<code>protected FormValidation doTestConnection(URL ec2endpoint, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey) throws IOException, ServletException { try { AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint); ec2.describeInstances(); if (privateKey == null) return FormValidation.error("Private key is not specified. Click 'Generate Key' to generate one."); if (privateKey.trim().length() > 0) { EC2PrivateKey pk = new EC2PrivateKey(privateKey); if (pk.find(ec2) == null) return FormValidation .warning("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is " <START> + pk.getFingerprint() + ")"); <END> } return FormValidation.ok(Messages.EC2Cloud_Success()); } catch (AmazonClientException e) { LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e); return FormValidation.error(e.getMessage()); } }</code><technical_language>I give a hint reason private key longer required</technical_language>

Target:
protected FormValidation doTestConnection(URL ec2endpoint, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey) throws IOException, ServletException { try { AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint); ec2.describeInstances(); if (privateKey == null) return FormValidation.error("Private key is not specified. Click 'Generate Key' to generate one."); if (privateKey.trim().length() > 0) { EC2PrivateKey pk = new EC2PrivateKey(privateKey); if (pk.find(ec2) == null) return FormValidation .warning("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is " + pk.getFingerprint() + "), this will fail unless your SSH public key is acquired via some other means"); } return FormValidation.ok(Messages.EC2Cloud_Success()); } catch (AmazonClientException e) { LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e); return FormValidation.error(e.getMessage()); } }
Source:
<code>private Category categorize(final String value) { if (value == null) { return Category.UNMATCHED; } <START> final String str = caseSensitive ? value : value.toLowerCase(); <END> for (final String substring : substrings) { final String containedPart = caseSensitive ? substring : substring.toLowerCase(); if (str.contains(containedPart)) { return Category.MATCHED; } } return Category.UNMATCHED; }</code><technical_language>a more descriptive name for this variable abbreviation</technical_language>

Target:
private Category categorize(final String value) { if (value == null) { return Category.UNMATCHED; } final String normalizedValue = caseSensitive ? value : value.toLowerCase(); for (final String substring : substrings) { final String containedPart = caseSensitive ? substring : substring.toLowerCase(); if (normalizedValue.contains(containedPart)) { return Category.MATCHED; } } return Category.UNMATCHED; }
Source:
<code>public void handleChangedThrottledState(boolean isThrottled) { if (!isThrottled) { <START> LOG.info("✅ Unthrottled"); <END> } else { LOG.info("❗Throttled"); } if (!isThrottled && stoppedDueToThrottling.get()) { stoppedDueToThrottling.set(false); LOG.debug("Transport state [{}]", consumerState); switch (consumerState) { case STOPPED: LOG.info("[unthrottled] Throttle state ended restarting consumer"); restartConsumer(); break; case STOPPING: { LOG.info("Kinesis consumer is still stopping. Waiting [{}ms] for the consumer to finish " + "stopping before restarting.", KINESIS_CONSUMER_STOP_WAIT_MS); new Timer().schedule(new TimerTask() { @Override public void run() { if (consumerState == KinesisTransportState.STOPPED) { restartConsumer(); } else { LOG.error("Could not restart Kinesis consumer, because the previously running " + "consumer did not reach a STOPPED state within [{}ms].", KINESIS_CONSUMER_STOP_WAIT_MS); } } }, KINESIS_CONSUMER_STOP_WAIT_MS); } } } }</code><technical_language>Please emoji in log messages. :smile: Also, I guess messages leftovers debugging? If needed change LOG.debug() calls</technical_language>

Target:
public void handleChangedThrottledState(boolean isThrottled) { if (!isThrottled) { LOG.info("Unthrottled"); } else { LOG.info("Throttled"); } if (!isThrottled && stoppedDueToThrottling.get()) { stoppedDueToThrottling.set(false); LOG.debug("Transport state [{}]", consumerState.get()); switch (consumerState.get()) { case STOPPED: LOG.info("[unthrottled] Throttle state ended restarting consumer"); restartConsumer(); break; case STOPPING: { LOG.info("Kinesis consumer is still stopping. Waiting [{}ms] for the consumer to finish " + "stopping before restarting.", KINESIS_CONSUMER_STOP_WAIT_MS); new Timer().schedule(new TimerTask() { @Override public void run() { if (consumerState.get() == KinesisTransportState.STOPPED) { restartConsumer(); } else { LOG.error("Could not restart Kinesis consumer, because the previously running " + "consumer did not reach a STOPPED state within [{}ms].", KINESIS_CONSUMER_STOP_WAIT_MS); } } }, KINESIS_CONSUMER_STOP_WAIT_MS); } } } }
Source:
<code>private Optional<ColumnChunkMetaData> findColumnByPath(BlockMetaData block, String[] path) { for (ColumnChunkMetaData column : block.getColumns()) { <START> if (Arrays.equals(column.getPath().toArray(), (path))) { <END> return Optional.of(column); } } return Optional.empty(); }</code><technical_language>I remove unnecessary brackets path</technical_language>

Target:
private Optional<ColumnChunkMetaData> findColumnByPath(BlockMetaData block, String[] path) { for (ColumnChunkMetaData column : block.getColumns()) { if (Arrays.equals(column.getPath().toArray(), path)) { return Optional.of(column); } } return Optional.empty(); }
Source:
<code>private CompletionStage<RestResponse> removeCache(RestRequest request) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String cacheName = request.variables().get("cacheName"); Cache<?, ?> cache = restCacheManager.getCache(cacheName, request.getSubject()); if (cache == null) { responseBuilder.status(HttpResponseStatus.NOT_FOUND); return CompletableFuture.completedFuture(responseBuilder.build()); } <START> return CompletableFuture.supplyAsync(() -> { <END> restCacheManager.getInstance().administration().removeCache(cacheName); responseBuilder.status(OK); return responseBuilder.build(); }); }</code><technical_language>passing executor here? this missed will's checkstyle PR</technical_language>

Target:
private CompletionStage<RestResponse> removeCache(RestRequest request) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String cacheName = request.variables().get("cacheName"); Cache<?, ?> cache = restCacheManager.getCache(cacheName, request.getSubject()); if (cache == null) { responseBuilder.status(HttpResponseStatus.NOT_FOUND); return CompletableFuture.completedFuture(responseBuilder.build()); } return CompletableFuture.supplyAsync(() -> { restCacheManager.getInstance().administration().removeCache(cacheName); responseBuilder.status(OK); return responseBuilder.build(); }, executor); }
Source:
<code>public void testParseCommodityCodeList() { byte[] content = commodityCodeUpdateService.getFileContent(DATA_FILE_PATH); <START> ArrayList<CommodityCode> someCommodityCodes = (ArrayList<CommodityCode>) commodityCodeUpdateService.parseCommodityCodeList(content); <END> assertNotEquals(content.length, 0); assertEquals(NUMBER_OF_RECORDS_IN_DATA_FILE, someCommodityCodes.size()); }</code><technical_language>I necessary cast returned collection ArrayList, assertions checking collection's total size</technical_language>

Target:
public void testParseCommodityCodeList() { byte[] content = commodityCodeUpdateService.getFileContent(DATA_FILE_PATH); Collection<CommodityCode> someCommodityCodes = commodityCodeUpdateService.parseCommodityCodeList(content); assertNotEquals(content.length, 0); assertEquals(NUMBER_OF_RECORDS_IN_DATA_FILE, someCommodityCodes.size()); }
Source:
<code>public boolean isLockVerbs() { <START> return lockVerbs.get(); <END> }</code><technical_language>this.lockVerbs (like below)</technical_language>

Target:
public boolean isLockVerbs() { return this.lockVerbs.get(); }
Source:
<code>public Optional<InputStream> open(final String assetName, final String type, final boolean minified) throws IOException { <START> return this.<Optional<InputStream>>withLogPrefix(() -> { <END> final Optional<AssetResource> r = getResource(assetName, type, minified); if (!r.isPresent()) { LOG.info("Unable to locate asset resource {}:{}", assetName, type); return Optional.empty(); } final AssetResource resource = r.get(); if (m_filesystemPath != null) { final Path p = Paths.get(m_filesystemPath).resolve(resource.getPath()); LOG.debug("assets path is set, attempting to load {}:{} from {}", assetName, type, p); if (p.toFile().exists()) { return Optional.of(new FileInputStream(p.toFile())); } } final String resourcePath = resource.getPath(); LOG.debug("Opening resource for asset {}", resourcePath, r); final URL url = getClass().getResource(resourcePath); if (url != null) { return Optional.of(url.openStream()); } return Optional.of(new ClassPathResource(resourcePath).getInputStream()); }); }</code><technical_language>this needs fully qualified</technical_language>

Target:
public Optional<InputStream> open(final String assetName, final String type, final boolean minified) throws IOException { return withLogPrefix(() -> { final Optional<AssetResource> r = getResource(assetName, type, minified); if (!r.isPresent()) { LOG.info("Unable to locate asset resource {}:{}", assetName, type); return Optional.empty(); } final AssetResource resource = r.get(); if (m_filesystemPath != null) { final Path p = Paths.get(m_filesystemPath).resolve(resource.getPath()); LOG.debug("assets path is set, attempting to load {}:{} from {}", assetName, type, p); if (p.toFile().exists()) { return Optional.of(new FileInputStream(p.toFile())); } } final String resourcePath = resource.getPath(); LOG.debug("Opening resource for asset {}", resourcePath, r); final URL url = getClass().getResource(resourcePath); if (url != null) { return Optional.of(url.openStream()); } return Optional.of(new ClassPathResource(resourcePath).getInputStream()); }); }
Source:
<code>private void lockAllNodes( KernelStatement state, long[] nodeIds ) { for ( long nodeId : nodeIds ) { <START> state.locks().optimistic().acquireExclusive( state.lockTracer(), ResourceTypes.NODE, nodeId ); <END> } }</code><technical_language>call id argument is a vararg</technical_language>

Target:
private void lockAllNodes( KernelStatement state, long[] nodeIds ) { state.locks().optimistic().acquireExclusive( state.lockTracer(), ResourceTypes.NODE, nodeIds ); }
Source:
<code>public void show() { GQuery tooltip = getTip(); if (getTip().hasClass(style.in())) { return; } assignWidget(); if (!enabled || noContentInTooltip()) { return; } tooltip.detach() .removeClass(style.in(), style.top(), style.bottom(), style.left(), style.right()) .css("top", "0") .css("left", "0") .css("display", "block"); String container = options.getContainer(); if (container == null || "parent".equals(container)) { tooltip.insertAfter($element); } else if ("element".equals(container)) { tooltip.appendTo($element); } else { tooltip.appendTo($(container)); } setContent(); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { <START> doShowTooltip(); <END> } }); }</code><technical_language>problem</technical_language>

Target:
public void show() { GQuery tooltip = getTip(); if (getTip().hasClass(style.in())) { return; } assignWidget(); if (!enabled || noContentInTooltip()) { return; } tooltip.detach() .removeClass(style.in(), style.top(), style.bottom(), style.left(), style.right()) .css("top", "0") .css("left", "0") .css("display", "block"); String container = options.getContainer(); if (container == null || "parent".equals(container)) { tooltip.insertAfter($element); } else if ("element".equals(container)) { tooltip.appendTo($element); } else { tooltip.appendTo($(container)); } setContent(); showTooltip(); }
Source:
<code>private void setJdrUuid() { String jbossConfig = System.getProperty(JBOSS_PROPERTY_DIR); if(jbossConfig == null) { <START> if(!new File(DEFAULT_PROPERTY_DIR).exists()) { <END> FileNotFoundException e = new FileNotFoundException("Could not find JDR properties file"); e.printStackTrace(); return; } jbossConfig = DEFAULT_PROPERTY_DIR + File.separator + DATA_DIR; } String jdrPropertiesFilePath = jbossConfig + File.separator + JdrReportExtension.SUBSYSTEM_NAME + File.separator + JDR_PROPERTY_FILE_NAME; Properties jdrProperties = new Properties(); InputStream jdrIS = getClass().getClassLoader().getResourceAsStream(jdrPropertiesFilePath); if(jdrIS != null) { try { jdrProperties.load(jdrIS); jdrUuid = jdrProperties.getProperty(UUID_NAME); if(jdrUuid == null) { jdrUuid = java.util.UUID.randomUUID().toString(); jdrProperties.setProperty(UUID_NAME, jdrUuid); } } catch (IOException e) { e.printStackTrace(); } } else { jdrUuid = java.util.UUID.randomUUID().toString(); jdrProperties.setProperty(UUID_NAME, java.util.UUID.randomUUID().toString()); FileOutputStream fileOut = null; try { File file = new File(jdrPropertiesFilePath); file.getParentFile().mkdirs(); fileOut = new FileOutputStream(jdrPropertiesFilePath); jdrProperties.store(fileOut, JDR_PROPERTIES_COMMENT); } catch (IOException e) { e.printStackTrace(); } finally { if(fileOut != null) { try { fileOut.close(); } catch(IOException e) { e.printStackTrace(); } } } } }</code><technical_language>work Windows</technical_language>

Target:
private void setJdrUuid() { String jbossConfig = System.getProperty(JBOSS_PROPERTY_DIR); if(jbossConfig == null) { String jbossHome = System.getProperty(JBOSS_HOME_DIR); if(!new File(jbossHome + File.separator + DEFAULT_PROPERTY_DIR).exists()) { ROOT_LOGGER.error(ROOT_LOGGER.couldNotFindJDRPropertiesFile()); } jbossConfig = jbossHome + File.separator + DEFAULT_PROPERTY_DIR + File.separator + DATA_DIR; } String jdrPropertiesFilePath = jbossConfig + File.separator + JdrReportExtension.SUBSYSTEM_NAME + File.separator + JDR_PROPERTY_FILE_NAME; Properties jdrProperties = new Properties(); FileInputStream jdrIS = null; File jdrFile = new File(jdrPropertiesFilePath); if(jdrFile.exists()) { try { jdrIS = new FileInputStream(jdrPropertiesFilePath); jdrProperties.load(jdrIS); jdrUuid = jdrProperties.getProperty(UUID_NAME); if(jdrUuid == null) { jdrUuid = java.util.UUID.randomUUID().toString(); jdrProperties.setProperty(UUID_NAME, jdrUuid); } } catch (IOException e) { e.printStackTrace(); } finally { if(jdrIS != null) { try { jdrIS.close(); } catch(IOException e) { e.printStackTrace(); } } } } else { jdrUuid = java.util.UUID.randomUUID().toString(); jdrProperties.setProperty(UUID_NAME, jdrUuid); FileOutputStream fileOut = null; try { jdrFile.getParentFile().mkdirs(); fileOut = new FileOutputStream(jdrFile); jdrProperties.store(fileOut, JDR_PROPERTIES_COMMENT); } catch (IOException e) { e.printStackTrace(); } finally { if(fileOut != null) { try { fileOut.close(); } catch(IOException e) { e.printStackTrace(); } } } } }
Source:
<code>public boolean isInRelation(T big, T small) { Set<T> bigEqs = equivalentElems.get(big); Set<T> smallEqs = equivalentElems.get(small); if (bigEqs == null) { bigEqs = new HashSet<>(); bigEqs.add(big); } if (smallEqs == null) { smallEqs = new HashSet<>(); smallEqs.add(small); } <START> for (T s1 : bigEqs) { <END> for (T s2 : smallEqs) { boolean rel = relations.contains(new Tuple<>(s1, s2)); if (rel) { return true; } } } return false; }</code><technical_language>This expensive me. precompute some information eliminate this nested loop? For example, representative for equivalent class</technical_language>

Target:
public boolean isInRelation(T big, T small) { Set<T> bigEqs = equivalentElems.get(big); Set<T> smallEqs = equivalentElems.get(small); if (bigEqs == null) { bigEqs = new HashSet<>(); bigEqs.add(big); } if (smallEqs == null) { smallEqs = new HashSet<>(); smallEqs.add(small); } if (smallEqs == bigEqs) { return true; } for (T s1 : bigEqs) { for (T s2 : smallEqs) { boolean rel = relations.contains(new Tuple<>(s1, s2)); if (rel) { return true; } } } return false; }
Source:
<code>protected Set[] getUserGroupsAndRoles(final RoleMappingResource roleMappingResource) { if (roleMappingResource != null) { List<RoleRepresentation> roles; <START> if (useResourceRoleMapping) { <END> roles = roleMappingResource.clientLevel(getClientIdByName(getRealmResource())).listEffective(); } else { roles = roleMappingResource.realmLevel().listEffective(); } if (roles != null && !roles.isEmpty()) { final Set<Group> _groups = new HashSet<Group>(); final Set<Role> _roles = new HashSet<Role>(); final Set<String> registeredRoles = SecurityManagementUtils.getRegisteredRoleNames(); for (RoleRepresentation roleRepresentation : roles) { if (roleRepresentation != null) { String name = roleRepresentation.getName(); SecurityManagementUtils.populateGroupOrRoles(name, registeredRoles, _groups, _roles); } } return new Set[]{_groups, _roles}; } } return null; }</code><technical_language>I this IF Pattern 3 times. do extract part? like: public ACommonInterface getSomething(){ if (useResourceRoleMapping) { return roleMappingResource.clientLevel(getClientIdByName(getRealmResource())) } else { return roleMappingResource.realmLevel() } }</technical_language>

Target:
protected Set[] getUserGroupsAndRoles(final RoleMappingResource roleMappingResource) { if (roleMappingResource != null) { List<RoleRepresentation> roles; roles = getRolesScopeResource(roleMappingResource, getKeyCloakInstance().getUseRoleResourceMappings()).listEffective(); if (roles != null && !roles.isEmpty()) { final Set<Group> _groups = new HashSet<Group>(); final Set<Role> _roles = new HashSet<Role>(); final Set<String> registeredRoles = SecurityManagementUtils.getRegisteredRoleNames(); for (RoleRepresentation roleRepresentation : roles) { if (roleRepresentation != null) { String name = roleRepresentation.getName(); SecurityManagementUtils.populateGroupOrRoles(name, registeredRoles, _groups, _roles); } } return new Set[]{_groups, _roles}; } } return null; }