auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void removeClassFromJaxbContextClassList( List<Class> classList, IllegalAnnotationsException iae, String deploymentId, ClassLoader projectClassLoader) throws IllegalAnnotationException { Set<Class> removedClasses = new HashSet<Class>(); for( IllegalAnnotationException error : iae.getErrors() ) { List<Location> classLocs = error.getSourcePos().get(0); if( classLocs != null && ! classLocs.isEmpty() ) { String className = classLocs.listIterator(classLocs.size()).previous().toString(); Class removeClass = null; try { <START> removeClass = projectClassLoader.loadClass(className); <END> if( ! removedClasses.add(removeClass) ) { continue; } } catch( ClassNotFoundException cnfe ) { throw new KieRemoteServicesInternalError("Class [" + className + "] could not be found when creating JAXB context: " + cnfe.getMessage(), cnfe); } if( classList.remove(removeClass) ) { logger.warn("Removing class '{}' from serialization context for deployment '{}'", className, deploymentId); continue; } } throw error; } }</code><technical_language>out of curiosity I - is used: classLoader.loadClass(className) Class.forName(className, init, classLoader)</technical_language>

Target:
private void removeClassFromJaxbContextClassList( List<Class> classList, IllegalAnnotationsException iae, String deploymentId, ClassLoader projectClassLoader) throws IllegalAnnotationException { Set<Class> removedClasses = new HashSet<Class>(); for( IllegalAnnotationException error : iae.getErrors() ) { List<Location> classLocs = error.getSourcePos().get(0); if( classLocs != null && ! classLocs.isEmpty() ) { String className = classLocs.listIterator(classLocs.size()).previous().toString(); Class removeClass = null; try { removeClass = Class.forName(className, true, projectClassLoader); if( ! removedClasses.add(removeClass) ) { continue; } } catch( ClassNotFoundException cnfe ) { throw new KieRemoteServicesInternalError("Class [" + className + "] could not be found when creating JAXB context: " + cnfe.getMessage(), cnfe); } if( classList.remove(removeClass) ) { logger.warn("Removing class '{}' from serialization context for deployment '{}'", className, deploymentId); continue; } } throw error; } }
Source:
<code>public void contextDestroyed(ServletContextEvent event) { try { <START> ACL.impersonate(ACL.SYSTEM); <END> terminated = true; Jenkins instance = Jenkins.getInstanceOrNull(); if(instance!=null) instance.cleanUp(); Thread t = initThread; if (t != null && t.isAlive()) { LOGGER.log(Level.INFO, "Shutting down a Jenkins instance that was still starting up", new Throwable("reason")); t.interrupt(); } Logger.getLogger("").removeHandler(handler); } finally { JenkinsJVMAccess._setJenkinsJVM(false); } }</code><technical_language>put this in Jenkins.cleanUp as: ACL.impersonate(ACL.SYSTEM, new Runnable() { // body of method });</technical_language>

Target:
public void contextDestroyed(ServletContextEvent event) { ACL.impersonate(ACL.SYSTEM, new Runnable() { @Override public void run() { try { terminated = true; Jenkins instance = Jenkins.getInstanceOrNull(); if(instance!=null) instance.cleanUp(); Thread t = initThread; if (t != null && t.isAlive()) { LOGGER.log(Level.INFO, "Shutting down a Jenkins instance that was still starting up", new Throwable("reason")); t.interrupt(); } Logger.getLogger("").removeHandler(handler); } finally { JenkinsJVMAccess._setJenkinsJVM(false); } } }); }
Source:
<code>public void clickLineInCodeReviewForComment(int lineNumber) throws PermissionsDeniedException, ValidationException { <START> info("Clicking a line to leave comment"); <END> try { codeReviewLines.get(lineNumber - 1).click(); } catch (IndexOutOfBoundsException e) { info("The line doesn't exist"); throw new ValidationException("The commented line number exceeds the code review lines number"); } info("The line was clicked"); try { codeReviewCommentBodyField.clear(); } catch (NoSuchElementException e) { info("Clicking the line does nothing, looks like the permissions are not granted"); throw new PermissionsDeniedException("User does not have permissions to leave comments in branch"); } }</code><technical_language>line is clicked</technical_language>

Target:
public void clickLineInCodeReviewForComment(int lineNumber) throws PermissionsDeniedException, ValidationException { info("Clicking a line #" + lineNumber + " to leave comment"); try { codeReviewLines.get(lineNumber - 1).click(); info("The line was clicked"); } catch (IndexOutOfBoundsException e) { info("The line doesn't exist"); throw new ValidationException("The commented line number exceeds the code review lines number"); } try { codeReviewCommentBodyField.clear(); } catch (NoSuchElementException e) { info("Clicking the line does nothing, looks like the permissions are not granted"); throw new PermissionsDeniedException("User does not have permissions to leave comments in branch"); } }
Source:
<code>public final String buildFreeTextConditionSql(String tableName, String relations, String value, boolean caseSensitive) { StringBuilder sb = new StringBuilder(" ( "); String val; if (!StringHelper.isNullOrEmpty(value) && !"''".equals(value)) { val= StringFormat.format(getI18NPrefix() + "'%%%1$s%%'", StringHelper.trim(value, '\'')); } else { val = value; } String rel; switch (relations) { case "d": rel = getLikeSyntax(caseSensitive); break; case "!=": rel = "NOT " + getLikeSyntax(caseSensitive); break; default: rel = relations; } sb.append(columnNameDict.entrySet().stream().sorted(Map.Entry.comparingByValue()) .filter(e -> typeDict.get(e.getKey()) == String.class && !notFreeTextSearchableFieldsList.contains(e.getKey())) .map(e -> StringFormat.format(" %1$s.%2$s %3$s %4$s", tableName, e.getValue(), rel, val)) .distinct() <START> .collect(Collectors.joining(" OR "))); <END> sb.append(" ) "); return sb.toString(); }</code><technical_language>This implicitly creates another hidden StringBuilder, converts string, appends sb, memory needs allocated twice. retain original code's performance implementing collector append sb: Collector.of(() -> sb, (stringBuilder, str) -> stringBuilder.append(str).append(", "), StringBuilder::append))</technical_language>

Target:
public final String buildFreeTextConditionSql(String tableName, String relations, String value, boolean caseSensitive) { String val; if (!StringHelper.isNullOrEmpty(value) && !"''".equals(value)) { val= StringFormat.format(getI18NPrefix() + "'%%%1$s%%'", StringHelper.trim(value, '\'')); } else { val = value; } String rel; switch (relations) { case "d": rel = getLikeSyntax(caseSensitive); break; case "!=": rel = "NOT " + getLikeSyntax(caseSensitive); break; default: rel = relations; } return columnNameDict.entrySet().stream().sorted(Map.Entry.comparingByValue()) .filter(e -> typeDict.get(e.getKey()) == String.class && !notFreeTextSearchableFieldsList.contains(e.getKey())) .map(e -> StringFormat.format(" %1$s.%2$s %3$s %4$s", tableName, e.getValue(), rel, val)) .distinct() .collect(Collectors.joining(" OR ", " ( ", " ) ")); }
Source:
<code>private List<AccountInfo> GET(String endpoint) throws IOException { <START> RestResponse r = session.get(endpoint); <END> return (new Gson()).fromJson(r.getReader(), new TypeToken<List<AccountInfo>>() {}.getType()); }</code><technical_language>[optional] assert response status is OK</technical_language>

Target:
private List<AccountInfo> GET(String endpoint) throws IOException { RestResponse r = session.get(endpoint); assertEquals(HttpStatus.SC_OK, r.getStatusCode()); return (new Gson()).fromJson(r.getReader(), new TypeToken<List<AccountInfo>>() {}.getType()); }
Source:
<code><START> public String toString() { <END> if (getPerson() != null) return getPerson().getPersonName().getFullName(); else return getName(); }</code><technical_language>This toString needs mimic in PersonName.toString(). This a machine readable string is helpful in debugging, somethign end user sees. This method return toStrings person name</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(providerId); sb.append((person != null) ? person.getNames() : ""); return "[Provider: providerId: " + sb.toString() + " ]"; }
Source:
<code>private Cluster getCluster(String clusterName, Map<Tuple2<Integer, String>, Node> nodeNameNodeConfigMap) { validateProvidedConfiguration(nodeNameNodeConfigMap, allServers); Map<Integer, Node> oneConfigPerStripe = new HashMap<>(); for (Map.Entry<Tuple2<Integer, String>, Node> entry : nodeNameNodeConfigMap.entrySet()) { if (!oneConfigPerStripe.containsKey(entry.getKey().t1)) { oneConfigPerStripe.put(entry.getKey().t1, entry.getValue()); } } List<Cluster> stripes = new ArrayList<>(); for (Map.Entry<Integer, Node> entry : oneConfigPerStripe.entrySet()) { Node doc = entry.getValue(); try { String xml = XmlUtility.getPrettyPrintableXmlString(doc); <START> Cluster stripe = getStripe(xml); <END> stripe.setName("stripe[" + stripes.size() + "]"); stripe.getSingleStripe().get().setName("stripe[" + stripes.size() + "]"); stripes.add(stripe); } catch (TransformerException e) { throw new RuntimeException(e); } } return stripes.stream().reduce((result, stripe) -> result .addStripe(stripe.getSingleStripe().get().clone())) .orElseThrow(() -> new RuntimeException("No server specified.")) .setName(clusterName); }</code><technical_language>stripe -> cluster</technical_language>

Target:
private Cluster getCluster(String clusterName, Map<Tuple2<Integer, String>, Node> nodeNameNodeConfigMap) { validateProvidedConfiguration(nodeNameNodeConfigMap, allServers); Map<Integer, Node> oneConfigPerStripe = new HashMap<>(); for (Map.Entry<Tuple2<Integer, String>, Node> entry : nodeNameNodeConfigMap.entrySet()) { if (!oneConfigPerStripe.containsKey(entry.getKey().t1)) { oneConfigPerStripe.put(entry.getKey().t1, entry.getValue()); } } List<Cluster> stripes = new ArrayList<>(); for (Map.Entry<Integer, Node> entry : oneConfigPerStripe.entrySet()) { Node doc = entry.getValue(); try { String xml = XmlUtility.getPrettyPrintableXmlString(doc); Cluster stripe = getStripe(xml); stripe.getSingleStripe().get().setName("stripe[" + stripes.size() + "]"); stripes.add(stripe); } catch (TransformerException e) { throw new RuntimeException(e); } } return stripes.stream().reduce((result, stripe) -> result .addStripe(stripe.getSingleStripe().get().clone())) .orElseThrow(() -> new RuntimeException("No server specified.")) .setName(clusterName); }
Source:
<code>public Firehose connect() throws IOException { wrapperTupac.start(); return new Firehose() { Map<String, Object> map = null; @Override public boolean hasMore() { map = wrapperTupac.takeFromQueue(waitTime, unit); return map != null; } @Override public InputRow nextRow() { try { DateTime date = new DateTime(map.get("time")); <START> return new MapBasedInputRow(date.getMillis(), new ArrayList(map.keySet()), map); <END> } catch (NullPointerException e) { throw Throwables.propagate(e); } finally { map = null; } } @Override public Runnable commit() { return Runnables.getNoopRunnable(); } @Override public void close() throws IOException { } }; }</code><technical_language>want get a good habit of guava builders (Lists.newArrayList)</technical_language>

Target:
public Firehose connect() throws IOException { final BlockingQueue<Map<String, Object>> queue = Queues.newArrayBlockingQueue((int) waitTime); final Conjurer conjurer = builder.withPrinter(Conjurer.queuePrinter(queue)).build(); conjurer.start(); return new Firehose() { Map<String, Object> map; @Override public boolean hasMore() { try { map = queue.poll(waitTime, unit); } catch (InterruptedException e) { e.printStackTrace(); } return map != null; } @Override public InputRow nextRow() { try { DateTime date = new DateTime(map.get("time")); System.out.println(map); return new MapBasedInputRow(date.getMillis(), Lists.newArrayList(map.keySet()), map); } catch (NullPointerException e) { throw Throwables.propagate(e); } finally { map = null; } } @Override public Runnable commit() { return Runnables.getNoopRunnable(); } @Override public void close() throws IOException { conjurer.stop(); } }; }
Source:
<code>public static String parse(String uriHost, String partToExtract) { Matcher m = uriHostProjectPattern.matcher(uriHost); <START> if (m.find( )) { <END> if(partToExtract.toLowerCase().equals("project")) return m.group(5); else if(partToExtract.toLowerCase().equals("qualifier")) return m.group(3); else return null; } else { return null; } }</code><technical_language>I understand this line is do</technical_language>

Target:
public static String parse(String uriHost, String partToExtract) { String param = partToExtract.toLowerCase(); Matcher m = uriHostProjectPattern.matcher(uriHost); if (m.matches()) { if (param.equals("project")) return m.group(6); else if (param.equals("variant")) return m.group(3); else if (param.equals("mobile_qualifier")) return m.group(5); else return null; } else { return null; } }
Source:
<code>private void invokeTestWatchers(JupiterEngineExecutionContext context, Consumer<TestWatcher> callback, boolean reverseOrder) { ExtensionRegistry registry = context.getExtensionRegistry(); List<? extends TestWatcher> watchers = reverseOrder ? registry.getReversedExtensions(TestWatcher.class) : registry.getExtensions(TestWatcher.class); watchers.forEach(watcher -> { try { callback.accept(watcher); } catch (Exception e) { logger.warn(() -> { <START> return String.format("Error invoking TestWatcher %s for test %s : %s", watcher.getClass().getName(), <END> e); }); } }); }</code><technical_language>This is broken. 3 occurrences of %s. Please pass exception argument warn() method, include "test" in message</technical_language>

Target:
private void invokeTestWatchers(JupiterEngineExecutionContext context, Consumer<TestWatcher> callback, boolean reverseOrder) { ExtensionRegistry registry = context.getExtensionRegistry(); List<? extends TestWatcher> watchers = reverseOrder ? registry.getReversedExtensions(TestWatcher.class) : registry.getExtensions(TestWatcher.class); watchers.forEach(watcher -> { try { callback.accept(watcher); } catch (Throwable throwable) { ExtensionContext extensionContext = context.getExtensionContext(); BlacklistedExceptions.rethrowIfBlacklisted(throwable); logger.warn(throwable, () -> String.format("Failed to invoke TestWatcher %s for test %s", watcher.getClass().getName(), ReflectionUtils.getFullyQualifiedMethodName(extensionContext.getRequiredTestClass(), extensionContext.getRequiredTestMethod().getName(), extensionContext.getRequiredTestMethod().getParameterTypes()))); } }); }
Source:
<code>public void setEventListener(ServerStoreEventListener listener) { this.listener = listener; OffHeapChainMap.ChainMapEvictionListener<Long> chainMapEvictionListener = listener::onEviction; for (OffHeapChainMap<Long> segment : segments) { <START> segment.setEvictionListener(chainMapEvictionListener); <END> } }</code><technical_language>want put some token protection in this called twice</technical_language>

Target:
public void setEventListener(ServerStoreEventListener listener) { if (this.listener != null) { throw new IllegalStateException("ServerStoreEventListener instance already set"); } this.listener = listener; OffHeapChainMap.ChainMapEvictionListener<Long> chainMapEvictionListener = listener::onEviction; for (OffHeapChainMap<Long> segment : segments) { segment.setEvictionListener(chainMapEvictionListener); } }
Source:
<code><START> public int read(byte[] b, int off, int len) throws IOException <END> { if (readOffset == readLength) { if (writePending) flushForced(); fillReadBuffer(); if (readOffset == readLength) { return -1; } } int remains = len; int transferLength = Math.min(readLength - readOffset, remains); System.arraycopy(readBuffer, readOffset, b, off, transferLength); readOffset += transferLength; off += transferLength; remains -= transferLength; return len - remains; }</code><technical_language>I this readFully...BUT, a worried this bring out other bizarre bugs buried of SageTV this read requested amount if buffer data left in it; implementations is replacing end (based other discussion had). feel safer if this read returning</technical_language>

Target:
public int read(byte[] b, int off, int len) throws IOException { long remaining = length() - position(); if (remaining == 0) return -1; else if (len > remaining) len = (int)remaining; readFully(b, off, len); return len; }
Source:
<code>protected void dumpState(StateDumpCollector stateDumpCollector) { stateDumpCollector.addState("cacheName", cache.getName()); <START> stateDumpCollector.addState("cacheSie", String.valueOf(cache.size())); <END> }</code><technical_language>cacheSie again</technical_language>

Target:
protected void dumpState(StateDumpCollector stateDumpCollector) { stateDumpCollector.addState("cacheName", cache.getName()); stateDumpCollector.addState("cacheSize", String.valueOf(cache.size())); }
Source:
<code>T build(ServiceLocator serviceLocator) { try { serviceLocator.startAllServices(new HashMap<Service, ServiceConfiguration<?>>()); } catch (Exception e) { <START> logger.error("StandaloneCacheBuilder failed due to {}.", e.getMessage());; <END> } Store.Provider storeProvider = serviceLocator.findService(Store.Provider.class); final StoreConfigurationImpl<K, V> storeConfig = new StoreConfigurationImpl<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, expiry); final Store<K, V> store = storeProvider.createStore(storeConfig); CacheConfiguration<K, V> cacheConfig = new BaseCacheConfiguration<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, expiry, persistent); final Ehcache<K, V> ehcache = new Ehcache<K, V>(cacheConfig, store, cacheLoaderWriter, cacheEventNotificationService, statisticsExecutor,logger); return cast(ehcache); }</code><technical_language>exception logged such, message (ie: logger.error("some message", exception) instead of logger.error("some message: ", exception.getMessage) ) logger print full stack trace</technical_language>

Target:
T build(ServiceLocator serviceLocator) throws IllegalStateException { try { serviceLocator.startAllServices(new HashMap<Service, ServiceConfiguration<?>>()); } catch (Exception e) { throw new IllegalStateException("StandaloneCacheBuilder failed to build.", e); } Store.Provider storeProvider = serviceLocator.findService(Store.Provider.class); final StoreConfigurationImpl<K, V> storeConfig = new StoreConfigurationImpl<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, expiry); final Store<K, V> store = storeProvider.createStore(storeConfig); CacheConfiguration<K, V> cacheConfig = new BaseCacheConfiguration<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, expiry, persistent); final Ehcache<K, V> ehcache = new Ehcache<K, V>(cacheConfig, store, cacheLoaderWriter, cacheEventNotificationService, statisticsExecutor,logger); return cast(ehcache); }
Source:
<code>private String extractProjectName(URIish u) { String path = u.getPath().substring(1); if <START> (path.endsWith(".git")) <END> { return path.substring(0, path.length() - 4); } else { return path; } }</code><technical_language>existing constant</technical_language>

Target:
private String extractProjectName(URIish u) { String path = u.getPath().substring(1); if (path.endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT)) { return path.substring(0, path.length() - 4); } else { return path; } }
Source:
<code>public static void storeRetrievedAvailableApps(Vector<AppAvailableForInstall> availableAppsRetrieved) { if (availableAppsRetrieved != null && availableAppsRetrieved.size() > 0) { <START> ByteArrayOutputStream baos = new ByteArrayOutputStream(); <END> DataOutputStream serializedStream = new DataOutputStream(baos); try { ExtUtil.write(serializedStream, new ExtWrapList(availableAppsRetrieved)); String serializedAppsList = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT); getGlobalPrivilegesRecord().edit() .putString(RETRIEVED_AVAILABLE_APPS, serializedAppsList).commit(); serializedStream.close(); } catch (IOException e) { } } }</code><technical_language>wrap this in a try close in a finally</technical_language>

Target:
public static void storeRetrievedAvailableApps(Vector<AppAvailableForInstall> availableAppsRetrieved) { if (availableAppsRetrieved != null && availableAppsRetrieved.size() > 0) { ByteArrayOutputStream baos = null; DataOutputStream serializedStream = null; try { baos = new ByteArrayOutputStream(); serializedStream = new DataOutputStream(baos); try { ExtUtil.write(serializedStream, new ExtWrapList(availableAppsRetrieved)); String serializedAppsList = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT); getGlobalPrivilegesRecord().edit() .putString(RETRIEVED_AVAILABLE_APPS, serializedAppsList).commit(); baos.close(); serializedStream.close(); } catch (IOException e) { System.out.println("IO error encountered while serializing retrieved available apps"); clearPreviouslyRetrivedApps(); } } finally { try { if (baos != null) { baos.close(); } if (serializedStream != null) { serializedStream.close(); } } catch (IOException e) { } } } }
Source:
<code>private CoverageProvider getCoverageProvider(Run<?, ?> build, FilePath workspace, TaskListener listener, Set<String> includeFileNames) { Result buildResult = null; if (build.getResult() == null) { buildResult = Result.SUCCESS; } else { buildResult = build.getResult(); } if (!buildResult.isBetterOrEqualTo(Result.UNSTABLE)) { return null; } Logger logger = new Logger(listener.getLogger()); InstanceProvider<CoverageProvider> provider = new InstanceProvider<CoverageProvider>( Jenkins.getInstance(), COBERTURA_PLUGIN_NAME, COBERTURA_CLASS_NAME, logger ); CoverageProvider coberturaCoverage = provider.getInstance(); InstanceProvider<CoverageProvider> jacocoProvider = new InstanceProvider<CoverageProvider>( Jenkins.getInstance(), JACOCO_PLUGIN_NAME, JACOCO_CLASS_NAME, logger ); CoverageProvider jacocoCoverage = jacocoProvider.getInstance(); if (coberturaCoverage == null && jacocoCoverage == null) { return null; } <START> CoverageProvider coverage = Objects.firstNonNull(coberturaCoverage, jacocoCoverage); <END> coverage.setBuild(build); coverage.setWorkspace(workspace); coverage.setIncludeFileNames(includeFileNames); coverage.setCoverageReportPattern(coverageReportPattern); if (coverage.hasCoverage()) { return coverage; } else { logger.info(UBERALLS_TAG, "No coverage results found"); return null; } }</code><technical_language>Im this logic is sound. Cobertura plugin jacoco report generated. want select provider based coverage available. Ideally support a hybrid coverage provider aggregate coverage results providers. This a follow up/enhancement</technical_language>

Target:
private CoverageProvider getCoverageProvider(Run<?, ?> build, FilePath workspace, TaskListener listener, Set<String> includeFileNames) { Result buildResult = null; if (build.getResult() == null) { buildResult = Result.SUCCESS; } else { buildResult = build.getResult(); } if (!buildResult.isBetterOrEqualTo(Result.UNSTABLE)) { return null; } Logger logger = new Logger(listener.getLogger()); List<CoverageProvider> coverageProviders = new ArrayList<CoverageProvider>(); CoverageProvider coberturaCoverage = makeProvider(COBERTURA_PLUGIN_NAME, COBERTURA_CLASS_NAME, logger); if (coberturaCoverage != null) { coverageProviders.add(coberturaCoverage); } CoverageProvider jacocoCoverage = makeProvider(JACOCO_PLUGIN_NAME, JACOCO_CLASS_NAME, logger); if (jacocoCoverage != null) { coverageProviders.add(jacocoCoverage); } for (Iterator<CoverageProvider> i = coverageProviders.iterator(); i.hasNext(); ) { CoverageProvider coverageProvider = i.next(); coverageProvider.setBuild(build); coverageProvider.setWorkspace(workspace); coverageProvider.setIncludeFileNames(includeFileNames); coverageProvider.setCoverageReportPattern(coverageReportPattern); if (!coverageProvider.hasCoverage()) { i.remove(); } } if (!coverageProviders.isEmpty()) { CoverageProvider provider = coverageProviders.get(0); logger.info(UBERALLS_TAG, "Selected Coverage Provider: " + provider); return provider; } logger.info(UBERALLS_TAG, "No coverage results found"); return null; }
Source:
<code>private TablePanel buildConvergenceTable(final MixedTreatmentComparison mtc, ValueHolder<Boolean> modelConstructed) { ConvergenceDiagnosticTableModel tableModel = convergenceTable(mtc, modelConstructed); EnhancedTable convergenceTable = EnhancedTable.createBare(tableModel); TablePanel pane = new TablePanel(convergenceTable); convergenceTable.autoSizeColumns(); convergenceTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 1) { JTable table = (JTable)e.getComponent(); int row = table.convertRowIndexToModel(table.rowAtPoint(e.getPoint())); <START> Parameter p = mtc.getResults().getParameters()[row]; <END> showConvergencePlots(mtc, p); } } }); return pane; }</code><technical_language>Is bounds checking row needed here</technical_language>

Target:
private TablePanel buildConvergenceTable(final MixedTreatmentComparison mtc, ValueHolder<Boolean> modelConstructed) { ConvergenceDiagnosticTableModel tableModel = convergenceTable(mtc, modelConstructed); EnhancedTable convergenceTable = EnhancedTable.createBare(tableModel); TablePanel pane = new TablePanel(convergenceTable); convergenceTable.autoSizeColumns(); convergenceTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 1) { JTable table = (JTable)e.getComponent(); int row = table.convertRowIndexToModel(table.rowAtPoint(e.getPoint())); Parameter[] parameters = mtc.getResults().getParameters(); if (row <= parameters.length) { Parameter p = parameters[row]; showConvergencePlots(mtc, p); } } } }); return pane; }
Source:
<code>public SettingsDto getProperties(SettingsDto dto, SettingsFacade settingsFacade) { dto.setTaskPossibleErrors(settingsFacade.getProperty(TASK_POSSIBLE_ERRORS)); try { InputStream retries = settingsFacade.getRawConfig(TASK_PROPERTIES_FILE_NAME); Properties props = new Properties(); props.load(retries); if (props != null) { for (Map.Entry<Object, Object> entry : props.entrySet()) { dto.taskRetries.put((String) entry.getKey(), (String) entry.getValue()); } } } catch (IOException e) { throw new MotechException("Error loading raw file config to properties", e); <START> } catch (NullPointerException e) { <END> dto.setTaskRetries(new HashMap<String, String>()); } return dto; }</code><technical_language>catch NPE</technical_language>

Target:
public SettingsDto getProperties(SettingsDto dto, SettingsFacade settingsFacade) { dto.setTaskPossibleErrors(settingsFacade.getProperty(TASK_POSSIBLE_ERRORS)); try (InputStream retries = settingsFacade.getRawConfig(TASK_PROPERTIES_FILE_NAME)){ if(retries != null) { Properties props = new Properties(); props.load(retries); for (Map.Entry<Object, Object> entry : props.entrySet()) { dto.taskRetries.put((String) entry.getKey(), (String) entry.getValue()); } } else { dto.taskRetries = new HashMap<String, String>(); } } catch (IOException e) { throw new MotechException("Error loading raw file config to properties", e); } return dto; }
Source:
<code>public void remove(Group group, <START> Map out) { <END> String homePerspectiveKey = GROUP + "." + group.getName() + "." + HOME; String priorityKey = GROUP + "." + group.getName() + "." + PRIORITY; out.remove(priorityKey); out.remove(homePerspectiveKey); }</code><technical_language>suggestion Map out) {</technical_language>

Target:
private void remove(Group group, Map out) { String homePerspectiveKey = GROUP + "." + group.getName() + "." + HOME; String priorityKey = GROUP + "." + group.getName() + "." + PRIORITY; out.remove(priorityKey); out.remove(homePerspectiveKey); }
Source:
<code>public ServerBootstrap childHandler(ChannelHandler childHandler) { ObjectUtil.checkNotNull(childHandler, "childHandler"); <START> this.childHandler = childHandler; <END> return this; }</code><technical_language>nit: merge lines</technical_language>

Target:
public ServerBootstrap childHandler(ChannelHandler childHandler) { this.childHandler = ObjectUtil.checkNotNull(childHandler, "childHandler"); return this; }
Source:
<code>public void testParseEditInfo() throws Exception { JsonElement jsonElement = getJsonElement("edit.json"); List<EditInfo> editInfos = editInfoParser.parseEditInfos(jsonElement); Truth.assertThat(editInfos).hasSize(1); <START> System.out.println(editInfos.get(0)); <END> Truth.assertThat(editInfos.get(0).baseRevision.equals("184ebe53805e102605d11f6b143486d15c23a09c")); Truth.assertThat(editInfos.get(0).fetch.get("git").url.equals("git://localhost/gerrit")); Truth.assertThat(editInfos.get(0).files.size() == 2); }</code><technical_language>Please remove this line</technical_language>

Target:
public void testParseEditInfo() throws Exception { JsonElement jsonElement = getJsonElement("edit.json"); List<EditInfo> editInfos = editInfoParser.parseEditInfos(jsonElement); Truth.assertThat(editInfos).hasSize(1); Truth.assertThat(editInfos.get(0).baseRevision.equals("184ebe53805e102605d11f6b143486d15c23a09c")); Truth.assertThat(editInfos.get(0).fetch.get("git").url.equals("git://localhost/gerrit")); Truth.assertThat(editInfos.get(0).files.size() == 2); }
Source:
<code>protected boolean shouldNotFilter(final HttpServletRequest request) throws ServletException { SiteContext siteContext = SiteContext.getCurrent(); HierarchicalConfiguration config = siteContext.getConfig(); try { HierarchicalConfiguration corsConfig = config.configurationAt(CONFIG_KEY); if (corsConfig != null) { <START> boolean enable = corsConfig.getBoolean(ENABLE_KEY, false); <END> return !enable; } } catch (Exception e) { logger.debug("Site '{}' has no CORS configuration", siteContext.getSiteName()); } return true; }</code><technical_language>return result of corsConfig.getBoolean, instead of a variable immediately returning it. variable is necessary I Codacy wil complain</technical_language>

Target:
protected boolean shouldNotFilter(final HttpServletRequest request) throws ServletException { SiteContext siteContext = SiteContext.getCurrent(); HierarchicalConfiguration config = siteContext.getConfig(); try { HierarchicalConfiguration corsConfig = config.configurationAt(CONFIG_KEY); if (corsConfig != null) { return !corsConfig.getBoolean(ENABLE_KEY, false); } } catch (Exception e) { logger.debug("Site '{}' has no CORS configuration", siteContext.getSiteName()); } return true; }
Source:
<code>public boolean approveRequest(IEditCommandRequest request) { if (request instanceof CreateElementRequest) { EObject container = ((CreateElementRequest) request).getContainer(); <START> System.out.println("container: " + container); <END> if (container instanceof Interface) { IElementType messageSetType = ElementTypeRegistry.getInstance().getType(IUMLRTElementTypes.RT_MESSAGE_SET_ID); if (messageSetType instanceof ISpecializationType) { if (!((ISpecializationType) messageSetType).getMatcher().matches(container)) { return false; } if (RTMessageKind.OUT == MessageSetUtils.getMessageKind(container)) { return true; } } } else if (container instanceof Operation) { return true; } return false; } return super.approveRequest(request); }</code><technical_language>please remove system.out</technical_language>

Target:
public boolean approveRequest(IEditCommandRequest request) { if (request instanceof CreateElementRequest) { EObject container = ((CreateElementRequest) request).getContainer(); if (container instanceof Interface) { IElementType messageSetType = ElementTypeRegistry.getInstance().getType(IUMLRTElementTypes.RT_MESSAGE_SET_ID); if (messageSetType instanceof ISpecializationType) { if (!((ISpecializationType) messageSetType).getMatcher().matches(container)) { return false; } if (RTMessageKind.OUT == MessageSetUtils.getMessageKind(container)) { return true; } } } else if (container instanceof Operation) { return true; } return false; } return super.approveRequest(request); }
Source:
<code>public synchronized SubscriptionContext getSubscriptionContext(Entity entity) { if (!this.entity.equals(entity)) throw new IllegalStateException("Non-deployment context "+this+" can only use a single Entity: has "+this.entity+", but passed "+entity); <START> if (mode==NonDeploymentManagementContextMode.MANAGEMENT_STOPPED) return null; <END> return subscriptionContext; }</code><technical_language>I prefer return a NonDeploymentSubscriptionContext. throw exceptions attempt subscribe etc, return false for unsubscribe. I lots of null checks in calling code</technical_language>

Target:
public synchronized SubscriptionContext getSubscriptionContext(Entity entity) { if (!this.entity.equals(entity)) throw new IllegalStateException("Non-deployment context "+this+" can only use a single Entity: has "+this.entity+", but passed "+entity); if (mode==NonDeploymentManagementContextMode.MANAGEMENT_STOPPED) return new NonDeploymentSubscriptionContext(initialManagementContext, entity); return subscriptionContext; }
Source:
<code>public static String setState(final Connection conn, final String userId, final String classification, final String itemId, final State state) throws DatabaseAccessException { String result; final String query = "SELECT * FROM State WHERE UserID=? AND SchoolItemType=? AND SchoolItemID=?;"; try (PreparedStatement stmt = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { stmt.setString(1, userId); stmt.setString(2, classification); stmt.setString(3, itemId); try (final ResultSet rst = stmt.executeQuery()) { if (rst.next()) { <START> rst.updateBoolean("Completed", state.getCompleted()); <END> rst.updateBoolean("Started", state.getStarted()); rst.updateBoolean("Graded", state.getGraded()); rst.updateRow(); result = "SET"; } else { rst.moveToInsertRow(); rst.updateString("UserID", userId); rst.updateString("SchoolItemType", classification); rst.updateString("SchoolItemID", itemId); rst.updateBoolean("Completed", state.getCompleted()); rst.updateBoolean("Started", state.getStarted()); rst.updateBoolean("Graded", state.getGraded()); rst.insertRow(); rst.moveToCurrentRow(); result = "INSERT"; } } catch (SQLException e) { throw new DatabaseAccessException(e, false); } } catch (SQLException e) { throw new DatabaseAccessException(e, false); } return result; }</code><technical_language>database string constants instead of values</technical_language>

Target:
public static String setState(final Connection conn, final String userId, final String classification, final String itemId, final State state) throws DatabaseAccessException { String result; final String query = "SELECT * FROM State WHERE UserID=? AND SchoolItemType=? AND SchoolItemID=?;"; try (PreparedStatement stmt = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { stmt.setString(1, userId); stmt.setString(2, classification); stmt.setString(3, itemId); try (final ResultSet rst = stmt.executeQuery()) { if (rst.next()) { rst.updateBoolean(DatabaseStringConstants.STATE_COMPLETED, state.getCompleted()); rst.updateBoolean(DatabaseStringConstants.STATE_STARTED, state.getStarted()); rst.updateBoolean(DatabaseStringConstants.STATE_GRADED, state.getGraded()); rst.updateRow(); result = "SET"; } else { rst.moveToInsertRow(); rst.updateString(DatabaseStringConstants.USER_ID, userId); rst.updateString(DatabaseStringConstants.SCHOOLITEMTYPE, classification); rst.updateString(DatabaseStringConstants.SCHOOLITEMID, itemId); rst.updateBoolean(DatabaseStringConstants.STATE_COMPLETED, state.getCompleted()); rst.updateBoolean(DatabaseStringConstants.STATE_STARTED, state.getStarted()); rst.updateBoolean(DatabaseStringConstants.STATE_GRADED, state.getGraded()); rst.insertRow(); rst.moveToCurrentRow(); result = "INSERT"; } } catch (SQLException e) { throw new DatabaseAccessException(e, false); } } catch (SQLException e) { throw new DatabaseAccessException(e, false); } return result; }
Source:
<code>public void convertsToJsonWhenAllPresent() { final String success = "Everything is awesome"; MatcherAssert.assertThat( new Statuses.StatusCreate(Status.State.SUCCESS) .withTargetUrl(Optional.of(URL)) .withDescription(success) .withContext(Optional.of(CONTEXT)) .json().toString(), <START> Matchers.equalTo("{\"state\":\"success\",\"description\":\"Everything is awesome\",\"context\":\"jcabi/github/test\",\"target_url\":\"<LINK_0>\"}") <END> ); }</code><technical_language>@cvrebert This is a hard read; JsonObjectBuilder for this rest of this class</technical_language>

Target:
public void convertsToJsonWhenAllPresent() { final String success = "Everything is not so awesome"; MatcherAssert.assertThat( new Statuses.StatusCreate(Status.State.ERROR) .withTargetUrl(Optional.of(StatusesTest.URL)) .withDescription(success) .withContext(Optional.of(StatusesTest.CONTEXT)) .json().toString(), Matchers.equalTo( Json.createObjectBuilder() .add(StatusesTest.STATE_PROP, "error") .add(StatusesTest.DESCRIPTION_PROP, success) .add(StatusesTest.CONTEXT_PROP, StatusesTest.CONTEXT) .add(StatusesTest.TARGET_PROP, StatusesTest.URL) .build().toString() ) ); }
Source:
<code>protected String generateDomainXml() { VmNic nic = getParameters().getNic(); VmDevice vmDevice = getParameters().getVmDevice(); LibvirtVmXmlBuilder builder = new LibvirtVmXmlBuilder( getParameters().getVm(), getVds().getId(), nic, vmDevice, vmInfoBuildUtils, nic.isPassthrough() ? Collections.singletonMap(nic.getId(), vmDevice.getHostDevice()) : Collections.emptyMap()); String libvirtXml = <START> builder.buildHotplugNic(false); <END> String prettyLibvirtXml = XmlUtils.prettify(libvirtXml); if (prettyLibvirtXml != null) { log.info("NIC hot-plug: {}", prettyLibvirtXml); } return libvirtXml; }</code><technical_language>this is false here? (I check deep)</technical_language>

Target:
protected String generateDomainXml() { VmNic nic = getParameters().getNic(); VmDevice vmDevice = getParameters().getVmDevice(); LibvirtVmXmlBuilder builder = new LibvirtVmXmlBuilder( getParameters().getVm(), getVds().getId(), nic, vmDevice, vmInfoBuildUtils, nic.isPassthrough() ? Collections.singletonMap(nic.getId(), vmDevice.getHostDevice()) : Collections.emptyMap()); String libvirtXml = builder.buildHotplugNic(); String prettyLibvirtXml = XmlUtils.prettify(libvirtXml); if (prettyLibvirtXml != null) { log.info("NIC hot-plug: {}", prettyLibvirtXml); } return libvirtXml; }
Source:
<code>void maybeDeleteRecordedAutoDeleteExchange(String exchange) { synchronized (this.consumers) { synchronized (this.recordedExchanges) { if(!hasMoreDestinationsBoundToExchange(Utility.copy(this.recordedBindings), exchange)) { RecordedExchange x = this.recordedExchanges.get(exchange); if((x != null) && x.isAutoDelete()) { <START> deleteRecordedExchange(exchange); <END> } } } } }</code><technical_language>This related issue fix here. address this in a separate PR? for versioning, changelog, etc. Thanks :)</technical_language>

Target:
void maybeDeleteRecordedAutoDeleteExchange(String exchange) { synchronized (this.consumers) { synchronized (this.recordedExchanges) { if(!hasMoreDestinationsBoundToExchange(Utility.copy(this.recordedBindings), exchange)) { RecordedExchange x = this.recordedExchanges.get(exchange); if((x != null) && x.isAutoDelete()) { this.recordedExchanges.remove(exchange); } } } } }
Source:
<code>public void setCounterValue(String sequence, long nextValue, boolean force) { try { if (oma.select(SequenceCounter.class).eq(SequenceCounter.NAME, sequence).exists()) { if (force) { int updatedRows = oma.getDatabase() .createQuery("UPDATE sequencecounter " + "SET nextValue = ${value} " + "WHERE name = ${name}") .set("name", sequence) .set("value", nextValue) .executeUpdate(); if (updatedRows == 1) { return; } } else { int updatedRows = oma.getDatabase() .createQuery("UPDATE sequencecounter " + "SET nextValue = ${value} " + "WHERE name = ${name} " <START> + " AND nextValue <= ${value}") <END> .set("name", sequence) .set("value", nextValue) .executeUpdate(); if (updatedRows == 1) { return; } } } else { try { SequenceCounter counter = new SequenceCounter(); counter.setName(sequence); counter.setNextValue(nextValue); oma.update(counter); return; } catch (HandledException e) { Exceptions.ignore(e); } } throw Exceptions.handle() .to(LOG) .withSystemErrorMessage("Failed to specify the next value for sequence %s", sequence) .handle(); } catch (SQLException e) { throw Exceptions.handle() .to(LOG) .error(e) .withSystemErrorMessage( "Failed to specify the next value for sequence %s due to a database error: %s", sequence) .handle(); } }</code><technical_language>couldnt this line bei added query string if force is false if else is a lot sleeker</technical_language>

Target:
public void setCounterValue(String sequence, long nextValue, boolean force) { try { if (oma.select(SequenceCounter.class).eq(SequenceCounter.NAME, sequence).exists()) { String sql = "UPDATE sequencecounter " + "SET nextValue = ${value} " + "WHERE name = ${name}"; if (!force) { sql += " AND nextValue <= ${value}"; } int updatedRows = oma.getDatabase() .createQuery(sql) .set("name", sequence) .set("value", nextValue) .executeUpdate(); if (updatedRows == 1) { return; } } else { try { SequenceCounter counter = new SequenceCounter(); counter.setName(sequence); counter.setNextValue(nextValue); oma.update(counter); return; } catch (HandledException e) { Exceptions.ignore(e); } } throw Exceptions.handle() .to(LOG) .withSystemErrorMessage("Failed to specify the next value for sequence %s", sequence) .handle(); } catch (SQLException e) { throw Exceptions.handle() .to(LOG) .error(e) .withSystemErrorMessage( "Failed to specify the next value for sequence %s due to a database error: %s", sequence) .handle(); } }
Source:
<code>public void duplicateNameTest() { clickMenu("Boards", "Save as"); type("board 1"); click("OK"); assertEquals(1, panelControl.getPanelCount()); clickMenu("Panels", "Create"); clickMenu("Boards", "Save as"); type("board 1"); click("OK"); <START> assertNodeExists(hasText("A board by the name 'board 1' already exists.")); <END> click("Yes"); clickMenu("Boards", "Open", "board 1"); assertEquals(2, panelControl.getPanelCount()); clickMenu("Panels", "Create"); clickMenu("Boards", "Save as"); type("board 1"); click("OK"); click("No"); click("Cancel"); clickMenu("Boards", "Open", "board 1"); assertEquals(2, panelControl.getPanelCount()); }</code><technical_language>waitUntilNodeAppears if is lag in window appearing, fail immediately. This line Travis fail right now</technical_language>

Target:
public void duplicateNameTest() { clickMenu("Boards", "Save as"); click("OK"); assertEquals(1, panelControl.getPanelCount()); clickMenu("Panels", "Create"); clickMenu("Boards", "Save as"); click("OK"); waitUntilNodeAppears(hasText("A board by the name 'New Board' already exists.")); click("Yes"); clickMenu("Boards", "Open", "New Board"); assertEquals(2, panelControl.getPanelCount()); clickMenu("Panels", "Create"); assertEquals(3, panelControl.getPanelCount()); clickMenu("Boards", "Save as"); click("OK"); click("No"); click("Cancel"); clickMenu("Boards", "Open", "New Board"); assertEquals(2, panelControl.getPanelCount()); }
Source:
<code>public AddMemberBox() { addPanel = new FlowPanel(); addMember = new Button(Util.C.buttonAddGroupMember()); nameTxtBox = new HintTextBox(); nameTxt = new SuggestBox(new AccountSuggestOracle(), nameTxtBox); nameTxtBox.setVisibleLength(50); nameTxtBox.setHintText(Util.C.defaultAccountName()); <START> nameTxtBox.setHintStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint()); <END> nameTxtBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { submitOnSelection = false; if (event.getCharCode() == KeyCodes.KEY_ENTER) { if (nameTxt.isSuggestionListShowing()) { submitOnSelection = true; } else { doAdd(); } } } }); nameTxt.addSelectionHandler(new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { if (submitOnSelection) { submitOnSelection = false; doAdd(); } } }); addPanel.add(nameTxt); addPanel.add(addMember); initWidget(addPanel); }</code><technical_language>Assume it</technical_language>

Target:
public AddMemberBox() { addPanel = new FlowPanel(); addMember = new Button(Util.C.buttonAddGroupMember()); nameTxtBox = new HintTextBox(); nameTxt = new SuggestBox(new AccountSuggestOracle(), nameTxtBox); nameTxtBox.setVisibleLength(50); nameTxtBox.setHintText(Util.C.defaultAccountName()); nameTxtBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { submitOnSelection = false; if (event.getCharCode() == KeyCodes.KEY_ENTER) { if (nameTxt.isSuggestionListShowing()) { submitOnSelection = true; } else { doAdd(); } } } }); nameTxt.addSelectionHandler(new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { if (submitOnSelection) { submitOnSelection = false; doAdd(); } } }); addPanel.add(nameTxt); addPanel.add(addMember); initWidget(addPanel); }
Source:
<code>public void testIncludedAndExcludedGroups() { XmlSuite suite = new XmlSuite(); suite.addIncludedGroup("foo"); suite.addExcludedGroup("bar"); <START> assertThat(suite.getIncludedGroups()).hasSameElementsAs(Collections.singletonList("foo")); <END> assertThat(suite.getExcludedGroups()).hasSameElementsAs(Collections.singletonList("bar")); }</code><technical_language>avoid singleton list assertj provides methods check elements</technical_language>

Target:
public void testIncludedAndExcludedGroups() { XmlSuite suite = new XmlSuite(); suite.addIncludedGroup("foo"); suite.addExcludedGroup("bar"); assertThat(suite.getIncludedGroups()).containsExactly("foo"); assertThat(suite.getExcludedGroups()).containsExactly("bar"); }
Source:
<code>private void internalExtractResult(long startTs, byte[] row, byte[] col, byte[] val, long ts) { if (ts < startTs) { Cell cell = Cell.create(row, col); if (!collector.containsKey(row)) { collector.put(row, new LinkedHashMap<>()); collector.get(row).put(cell, Value.create(val, ts)); } else if (!collector.get(row).containsKey(cell)) { collector.get(row).put(cell, Value.create(val, ts)); <START> } <END> } else { getPostFilteredCellsMeter().mark(); } }</code><technical_language>i need another else block in update meter</technical_language>

Target:
private void internalExtractResult(long startTs, byte[] row, byte[] col, byte[] val, long ts) { if (ts < startTs) { Cell cell = Cell.create(row, col); if (!collector.containsKey(row)) { collector.put(row, new LinkedHashMap<>()); collector.get(row).put(cell, Value.create(val, ts)); } else if (!collector.get(row).containsKey(cell)) { collector.get(row).put(cell, Value.create(val, ts)); } else { notLatestVisibleValueCellFilterMeter.mark(); } } else { notLatestVisibleValueCellFilterMeter.mark(); } }
Source:
<code>public RepositoryGroup getSelectedRepositoryGroup(ExecutionEvent event) throws ExecutionException { Object singleSelection = null; if (HandlerUtil .getActivePartChecked(event) instanceof RepositoriesView) { List<?> selected = getSelectedNodes(event); if (selected.size() == 1 <START> && selected.get(0) instanceof RepositoryTreeNode) { <END> singleSelection = selected.get(0); } } else { RepositoriesView view = getRepositoriesView(); if (view != null) { IStructuredSelection selection = view.getCommonViewer() .getStructuredSelection(); if (selection != null && selection.size() == 1) { singleSelection = selection.getFirstElement(); } } } if (!(singleSelection instanceof RepositoryGroupNode)) { return null; } return ((RepositoryGroupNode) singleSelection).getObject(); }</code><technical_language>superfluous, type check in line 96 deal non-fitting objects</technical_language>

Target:
public RepositoryGroup getSelectedRepositoryGroup(ExecutionEvent event) throws ExecutionException { Object singleSelection = null; if (HandlerUtil .getActivePartChecked(event) instanceof RepositoriesView) { List<?> selected = getSelectedNodes(event); if (selected.size() == 1) { singleSelection = selected.get(0); } } else { RepositoriesView view = getRepositoriesView(); if (view != null) { IStructuredSelection selection = view.getCommonViewer() .getStructuredSelection(); if (selection != null && selection.size() == 1) { singleSelection = selection.getFirstElement(); } } } if (!(singleSelection instanceof RepositoryGroupNode)) { return null; } return ((RepositoryGroupNode) singleSelection).getObject(); }