auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static ClusteringServiceConfigurationBuilder seededFrom(ClusteringServiceConfiguration configuration) { ServerSideConfiguration serverSideConfiguration = configuration.getServerConfiguration(); if (serverSideConfiguration == null) { return new ClusteringServiceConfigurationBuilder(configuration.getConnectionSource(), configuration.getTimeouts(), configuration.isAutoCreate(), null, configuration.getProperties()); } else { ServerSideConfigurationBuilder serverSideBuilder = new ServerSideConfigurationBuilder().defaultServerResource(serverSideConfiguration.getDefaultServerResource()); for (Map.Entry<String, ServerSideConfiguration.Pool> poolEntry : serverSideConfiguration.getResourcePools().entrySet()) { serverSideBuilder = serverSideBuilder.resourcePool(poolEntry.getKey(), poolEntry.getValue()); } return new ClusteringServiceConfigurationBuilder(configuration.getConnectionSource(), configuration.getTimeouts(), configuration.isAutoCreate(), serverSideBuilder, configuration.getProperties()); } }

Target:
public static ClusteringServiceConfigurationBuilder seededFrom(ClusteringServiceConfiguration configuration) { ServerSideConfiguration serverSideConfiguration = configuration.getServerConfiguration(); if (serverSideConfiguration == null) { return new ClusteringServiceConfigurationBuilder(configuration.getConnectionSource(), configuration.getTimeouts(), configuration.isAutoCreate(), null, configuration.getProperties()); } else { return new ClusteringServiceConfigurationBuilder(configuration.getConnectionSource(), configuration.getTimeouts(), configuration.isAutoCreate(), new ServerSideConfigurationBuilder(serverSideConfiguration), configuration.getProperties()); } }
Source:
private void checkVdsSwapThreshold(VdsStatistics stat) { Integer minAvailableThreshold = Config.GetValue(ConfigValues.LogPhysicalMemoryThresholdInMB); Integer maxUsedPercentageThreshold = Config.GetValue(ConfigValues.LogMaxPhysicalMemoryUsedThresholdInPercentage); Long swapUsedPercent = (stat.getswap_total() - stat.getswap_free()) / stat.getswap_total(); if (stat.getswap_free() < minAvailableThreshold || swapUsedPercent > maxUsedPercentageThreshold) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsId(stat.getId()); logable.AddCustomValue("HostName", _vds.getvds_name()); logable.AddCustomValue("UsedSwap", swapUsedPercent.toString()); logable.AddCustomValue("AvailableSwapMemory", stat.getswap_free().toString()); logable.AddCustomValue("Threshold", stat.getswap_free() < minAvailableThreshold ? minAvailableThreshold.toString() : maxUsedPercentageThreshold.toString()); auditLog(logable, stat.getswap_free() < minAvailableThreshold ? AuditLogType.VDS_LOW_SWAP : AuditLogType.VDS_HIGH_SWAP_USE); } }

Target:
private void checkVdsSwapThreshold(VdsStatistics stat) { Integer minAvailableThreshold = Config.GetValue(ConfigValues.LogPhysicalMemoryThresholdInMB); Integer maxUsedPercentageThreshold = Config.GetValue(ConfigValues.LogMaxPhysicalMemoryUsedThresholdInPercentage); Long swapUsedPercent = (stat.getswap_total() - stat.getswap_free()) / stat.getswap_total(); AuditLogType valueToLog = stat.getswap_free() < minAvailableThreshold ? AuditLogType.VDS_LOW_SWAP : AuditLogType.VDS_HIGH_SWAP_USE; if (stat.getswap_free() < minAvailableThreshold || swapUsedPercent > maxUsedPercentageThreshold) { AuditLogableBase logable = new AuditLogableBase(stat.getId()); logable.AddCustomValue("HostName", _vds.getvds_name()); logable.AddCustomValue("UsedSwap", swapUsedPercent.toString()); logable.AddCustomValue("AvailableSwapMemory", stat.getswap_free().toString()); logable.AddCustomValue("Threshold", stat.getswap_free() < minAvailableThreshold ? minAvailableThreshold.toString() : maxUsedPercentageThreshold.toString()); auditLog(logable, valueToLog); } }
Source:
private ListenableFuture<Void> guardQueryWithSuppression(Exception e, AtomicLong committedOffset, ProgressiveBackoff progressiveBackoff) { ListenableFuture<Void> exceptionFuture = Futures.immediateFailedFuture(e); if (!retrier.isRetriable(e)) { return exceptionFuture; } ListenableFuture<Void> suppressedQueryFuture = Futures.catchingAsync( query(committedOffset, progressiveBackoff), Throwable.class, (t) -> { e.addSuppressed(t); return exceptionFuture; }, MoreExecutors.directExecutor()); return Futures.transformAsync( suppressedQueryFuture, (result) -> exceptionFuture, MoreExecutors.directExecutor()); }

Target:
private ListenableFuture<Void> guardQueryWithSuppression(Exception e, AtomicLong committedOffset, ProgressiveBackoff progressiveBackoff) { ListenableFuture<Void> exceptionFuture = Futures.immediateFailedFuture(e); if (!retrier.isRetriable(e)) { return exceptionFuture; } ListenableFuture<Void> suppressedQueryFuture = Futures.catchingAsync( query(committedOffset, progressiveBackoff), Exception.class, (queryException) -> { e.addSuppressed(queryException); return exceptionFuture; }, MoreExecutors.directExecutor()); return Futures.transformAsync( suppressedQueryFuture, (result) -> exceptionFuture, MoreExecutors.directExecutor()); }
Source:
public String toString() { return "ConnectionPoolInfo{" + "name='" + name + '\'' + ", url='" + url + '\'' + ", user='" + user + '\'' + ", password='" + password + '\'' + ", dataSourceClassname='" + dataSourceClassname + '\'' + ", driverClassname='" + driverClassname + '\'' + ", useMetrics=" + useMetrics + ", useHealthChecks=" + useHealthChecks + ", properties=" + properties + '}'; }

Target:
public String toString() { return "ConnectionPoolInfo{" + "name='" + name + '\'' + ", url='" + url + '\'' + ", dataSourceClassname='" + dataSourceClassname + '\'' + ", driverClassname='" + driverClassname + '\'' + ", useMetrics=" + useMetrics + ", useHealthChecks=" + useHealthChecks + ", properties=" + properties + '}'; }
Source:
public ImageResource getValue(VM vm) { if (vm.getVmPoolId() == null) { VmTypeConfig config = new VmTypeConfig(vm.isStateless(), vm.getVmType()); if (configToIcon.containsKey(config)) { Pair<ImageResource, String> value = configToIcon.get(config); setTitle(value.getSecond()); return value.getFirst(); } else { return getApplicationResources().manyDesktopsImage(); } } else { return getApplicationResources().manyDesktopsImage(); } }

Target:
public ImageResource getValue(VM vm) { if (vm.getVmPoolId() == null) { VmTypeConfig config = VmTypeConfig.from(vm.getVmType(), vm.isStateless()); setTitle(config.getTooltip(constants)); return config.getImageResource(getApplicationResources()); } else { return getApplicationResources().manyDesktopsImage(); } }
Source:
public void close() { try { tasks.forEach(BufferedEventSender.Resender::stop); executorService.shutdown(); executorService.awaitTermination(2, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { underlyingSender.close(); } }

Target:
public void close() { try { tasks.forEach(BufferedEventSender.Resender::stop); executorService.shutdown(); executorService.awaitTermination(2, TimeUnit.SECONDS); } catch (InterruptedException e) { log.warn("Interrupted while waiting for the executor service to shutdown, some events might be lost."); Thread.currentThread().interrupt(); } finally { underlyingSender.close(); } }
Source:
private List<AggregationOp> getInternalOps(AggregationOp op) { switch (op) { case COUNT: return ImmutableList.of(AggregationOp.COUNT); case MIN: return ImmutableList.of(AggregationOp.MIN); case MAX: return ImmutableList.of(AggregationOp.MAX); case SUM: return ImmutableList.of(AggregationOp.SUM); case AVG: return ImmutableList.of(AggregationOp.SUM, AggregationOp.COUNT); case STDEV: return ImmutableList.of(AggregationOp.SUM, AggregationOp.SUM_SQUARED, AggregationOp.COUNT); default: throw new IllegalArgumentException("Type " + op + " is invalid"); } }

Target:
private List<AggregationOp> getInternalOps(AggregationOp op) { switch (op) { case COUNT: case MIN: case MAX: case SUM: return ImmutableList.of(op); case AVG: return ImmutableList.of(AggregationOp.SUM, AggregationOp.COUNT); case STDEV: return ImmutableList.of(AggregationOp.SUM, AggregationOp.SUM_SQUARED, AggregationOp.COUNT); default: throw new IllegalArgumentException("Type " + op + " is invalid"); } }
Source:
public Tier loadComplete(Tier newTier) throws EntityNotFoundException { Query query = getEntityManager() .createQuery( "select p from Tier p fetch all properties where p.name = :name and p.vdc =:vdc and p.environmentname= :environmentname"); query.setParameter("name", newTier.getName()); query.setParameter("vdc", newTier.getVdc()); query.setParameter("environmentname", newTier.getEnviromentName()); Tier tier = null; try { tier = (Tier) query.getResultList().get(0); tier.getNetworks().size(); tier.getProductReleases().size(); tier.getSecurityGroup(); } catch (Exception e) { String message = " Tier don't exist in database "; throw new EntityNotFoundException(Tier.class, message, newTier.getName()); } return tier; }

Target:
public Tier loadComplete(Tier newTier) throws EntityNotFoundException { Query query = getEntityManager() .createQuery( "select p from Tier p fetch all properties where p.name = :name and p.vdc =:vdc and p.environmentname= :environmentname"); query.setParameter("name", newTier.getName()); query.setParameter("vdc", newTier.getVdc()); query.setParameter("environmentname", newTier.getEnviromentName()); Tier tier = null; try { tier = (Tier) query.getResultList().get(0); tier.getNetworks().size(); tier.getProductReleases().size(); tier.getSecurityGroup(); } catch (Exception e) { String message = " Tier does not exist in database "; throw new EntityNotFoundException(Tier.class, message, newTier.getName()); } return tier; }
Source:
private NewIndexType buildWithoutSubfields() { ImmutableMap.Builder<String, String> hash = ImmutableMap.builder(); hash.put("type", getFieldType()) .put(INDEX, disableSearch ? INDEX_NOT_SEARCHABLE : INDEX_SEARCHABLE) .put("norms", valueOf(!disableNorms)) .put("store", valueOf(store)); if (FIELD_TYPE_KEYWORD.equals(getFieldType())) { hash.put("doc_values", disabledDocValues ? "false" : "true"); } if (getFieldData()) { hash.put(FIELD_FIELDDATA, FIELDDATA_ENABLED); } return indexType.setProperty(fieldName, hash.build()); }

Target:
private NewIndexType buildWithoutSubfields() { Map<String, Object> hash = new TreeMap<>(); hash.put("type", getFieldType()); hash.put(INDEX, disableSearch ? INDEX_NOT_SEARCHABLE : INDEX_SEARCHABLE); hash.put("norms", valueOf(!disableNorms)); hash.put("store", valueOf(store)); if (FIELD_TYPE_KEYWORD.equals(getFieldType())) { hash.put("doc_values", valueOf(!disabledDocValues)); } if (getFieldData()) { hash.put(FIELD_FIELDDATA, FIELDDATA_ENABLED); } return indexType.setProperty(fieldName, hash); }
Source:
public DateTruncTest() { c1 = Calendar.getInstance(); c1.setTimeZone(TimeZone.getTimeZone("UTC")); c1.set(2000, 2, 3, 4, 5, 6); c1.set(Calendar.MILLISECOND, 7); c1.setMinimalDaysInFirstWeek(4); c1.setFirstDayOfWeek(Calendar.MONDAY); truncatedDate = Calendar.getInstance(); truncatedDate.setTimeZone(TimeZone.getTimeZone("UTC")); truncatedDate.set(2000, 2, 3, 4, 5, 6); truncatedDate.set(Calendar.MILLISECOND, 7); truncatedDate.setMinimalDaysInFirstWeek(4); truncatedDate.setFirstDayOfWeek(Calendar.MONDAY); lastModified = Calendar.getInstance(); lastModified.setTimeZone(TimeZone.getTimeZone("UTC")); lastModified.set(2000, 2, 3, 4, 5, 6); lastModified.set(Calendar.MILLISECOND, 7); lastModified.setMinimalDaysInFirstWeek(4); lastModified.setFirstDayOfWeek(Calendar.MONDAY); }

Target:
public DateTruncTest() { c1 = Calendar.getInstance(); c1.set(2000, 2, 3, 4, 5, 6); c1.set(Calendar.MILLISECOND, 7); c1.setMinimalDaysInFirstWeek(4); c1.setFirstDayOfWeek(Calendar.MONDAY); truncatedDate = Calendar.getInstance(); truncatedDate.set(2000, 2, 3, 4, 5, 6); truncatedDate.set(Calendar.MILLISECOND, 7); truncatedDate.setMinimalDaysInFirstWeek(4); truncatedDate.setFirstDayOfWeek(Calendar.MONDAY); lastModified = Calendar.getInstance(); lastModified.set(2000, 2, 3, 4, 5, 6); lastModified.set(Calendar.MILLISECOND, 7); lastModified.setMinimalDaysInFirstWeek(4); lastModified.setFirstDayOfWeek(Calendar.MONDAY); }
Source:
public static <T extends TypedSPI> Optional<T> getCachedTypedServiceInstance(final Class<T> typedServiceInterface, final String type) { T instance = TYPED_SERVICES.containsKey(typedServiceInterface) ? (T) TYPED_SERVICES.get(typedServiceInterface).get(type) : null; if (null == instance) { return Optional.empty(); } return Optional.of(instance); }

Target:
public static <T extends TypedSPI> Optional<T> getCachedTypedServiceInstance(final Class<T> typedServiceInterface, final String type) { return Optional.ofNullable(TYPED_SERVICES.get(typedServiceInterface)).map(services -> (T) services.get(type)); }
Source:
public int run() { scope.enter(kompiledDir.get()); try { Reader stringToParse = options.stringToParse(); Source source = options.source(); if (options.experimental.kore) { CompiledDefinition def = compiledDef.get(); org.kframework.kore.Sort sort = options.sort; if (sort == null) { if (env.get("KRUN_SORT") != null) { sort = Sort(env.get("KRUN_SORT")); } else { sort = def.programStartSymbol; } } org.kframework.definition.Module mod; if (options.module == null) { mod = def.syntaxModule(); } else { Option<org.kframework.definition.Module> mod2 = def.getParsedDefinition().getModule(options.module); if (mod2.isEmpty()) { throw KEMException.innerParserError("Module " + options.module + " not found. Specify a module with -m."); } mod = mod2.get(); } K parsed = def.getParser(def.getParserModule(mod), sort, kem).apply(FileUtil.read(stringToParse), source); System.out.println(ToKast.apply(parsed)); } else { Context context = contextProvider.get(); Sort sort = sort(options.sort, context); ASTNode out = loader.get().processPgm(stringToParse, source, sort, context, options.parser); StringBuilder kast; KoreFilter koreFilter = new KoreFilter(context); StringBuilder sb = new StringBuilder(); koreFilter.visitNode(out, sb); kast = sb; kast.append("\n"); System.out.print(kast.toString()); } sw.printTotal("Total"); return 0; } finally { scope.exit(); } }

Target:
public int run() { scope.enter(kompiledDir.get()); try { Reader stringToParse = options.stringToParse(); Source source = options.source(); if (options.experimental.kore) { CompiledDefinition def = compiledDef.get(); org.kframework.kore.Sort sort = options.sort; if (sort == null) { if (env.get("KRUN_SORT") != null) { sort = Sort(env.get("KRUN_SORT")); } else { sort = def.programStartSymbol; } } org.kframework.definition.Module mod; if (options.module == null) { mod = def.syntaxModule(); } else { Option<org.kframework.definition.Module> mod2 = def.kompiledDefinition.getModule(options.module); if (mod2.isEmpty()) { throw KEMException.innerParserError("Module " + options.module + " not found. Specify a module with -m."); } mod = mod2.get(); } K parsed = def.getParser(mod, sort, kem).apply(FileUtil.read(stringToParse), source); System.out.println(ToKast.apply(parsed)); } else { Context context = contextProvider.get(); Sort sort = sort(options.sort, context); ASTNode out = loader.get().processPgm(stringToParse, source, sort, context, options.parser); StringBuilder kast; KoreFilter koreFilter = new KoreFilter(context); StringBuilder sb = new StringBuilder(); koreFilter.visitNode(out, sb); kast = sb; kast.append("\n"); System.out.print(kast.toString()); } sw.printTotal("Total"); return 0; } finally { scope.exit(); } }
Source:
public void testPostRewriteHookCanBeIgnored() throws Exception { assumeSupportedPlatform(); Git git = Git.wrap(db); String path = "a.txt"; writeTrashFile(path, "content"); git.add().addFilepattern(path).call(); git.commit().setMessage("to amend"); Hook h = Hook.POST_REWRITE; writeHookFile(h.getName(), "#!/bin/sh\necho \"test\"\n\necho 1>&2 \"stderr\"\nexit 1"); ByteArrayOutputStream out = new ByteArrayOutputStream(); git.commit().setAmend(true).setNoPostRewrite(true) .setMessage("amended commit msg.") .setHookOutputStream(new PrintStream(out)).call(); assertEquals("", out.toString("UTF-8")); }

Target:
public void testPostRewriteHookCanBeIgnored() throws Exception { assumeSupportedPlatform(); Git git = Git.wrap(db); String path = "a.txt"; writeTrashFile(path, "content"); git.add().addFilepattern(path).call(); git.commit().setMessage("to amend").call(); Hook h = Hook.POST_REWRITE; writeHookFile(h.getName(), "#!/bin/sh\necho \"test\"\nexit 1"); ByteArrayOutputStream out = new ByteArrayOutputStream(); git.commit().setAmend(true).setNoPostRewrite(true) .setMessage("amended commit msg.") .setHookOutputStream(new PrintStream(out)).call(); assertEquals("", out.toString("UTF-8")); }
Source:
public boolean isDirty() { return dirty; }

Target:
public boolean isDirty() { return this.dirty; }
Source:
public void delayWindowTest2() { log.info("DelayWindow Test2 : Testing window parameter definition3"); SiddhiManager siddhiManager = new SiddhiManager(); String query = "define window eventWindow(symbol string, price int, volume float) delay('abc') "; SiddhiAppRuntime siddhiAppRuntime = null; try { siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(query); } catch (SiddhiAppCreationException e) { error = false; log.info(e.getCause()); } finally { if (siddhiAppRuntime != null) { siddhiAppRuntime.shutdown(); } } AssertJUnit.assertFalse(error); }

Target:
public void delayWindowTest2() { log.info("DelayWindow Test2 : Testing window parameter definition3"); SiddhiManager siddhiManager = new SiddhiManager(); String query = "define window eventWindow(symbol string, price int, volume float) delay('abc') "; SiddhiAppRuntime siddhiAppRuntime = null; try { siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(query); } catch (SiddhiAppCreationException e) { error = false; AssertJUnit.assertEquals("Delay window's parameter attribute should be either int or long, " + "but found STRING", e.getCause().getMessage()); throw e; } finally { if (siddhiAppRuntime != null) { siddhiAppRuntime.shutdown(); } } }
Source:
public void testDoHandleEvictOlderChannelData() throws Exception { ReceiverReplicationChannel channel1 = handler.doHandle(connection1); channel1.hello(new ReplicationHello("remoteServer", 0)); verify(registry, never()).evictAll(any(SourceMatcher.class)); ReceiverReplicationChannel channel2 = handler.doHandle(connection2); channel2.hello(new ReplicationHello("remoteServer", 0)); verify(registry, never()).evictAll(any(SourceMatcher.class)); ArgumentCaptor<SourceMatcher> argument = ArgumentCaptor.forClass(SourceMatcher.class); channel1.close(); inputSubject2.onNext(new StreamStateUpdate(new StreamStateNotification<>(BufferStart, forFullRegistry()))); verify(registry, never()).evictAll(any(SourceMatcher.class)); inputSubject2.onNext(new StreamStateUpdate(new StreamStateNotification<>(BufferEnd, forFullRegistry()))); Thread.sleep(50); verify(registry).evictAll(argument.capture()); assertThat(argument.getValue().toString(), is(matcherFor(channel1.getSource()).toString())); }

Target:
public void testDoHandleEvictOlderChannelData() throws Exception { ReceiverReplicationChannel channel1 = handler.doHandle(connection1); Source remoteServer1 = new Source(Origin.REPLICATED, "remoteServer", 0); channel1.hello(new ReplicationHello(remoteServer1, 0)); verify(registry, never()).evictAll(any(SourceMatcher.class)); ReceiverReplicationChannel channel2 = handler.doHandle(connection2); Source remoteServer2 = new Source(Origin.REPLICATED, "remoteServer", 1); channel2.hello(new ReplicationHello(remoteServer2, 0)); verify(registry, never()).evictAll(any(SourceMatcher.class)); ArgumentCaptor<SourceMatcher> argument = ArgumentCaptor.forClass(SourceMatcher.class); channel1.close(); inputSubject2.onNext(new StreamStateUpdate(new StreamStateNotification<>(BufferStart, forFullRegistry()))); verify(registry, never()).evictAll(any(SourceMatcher.class)); inputSubject2.onNext(new StreamStateUpdate(new StreamStateNotification<>(BufferEnd, forFullRegistry()))); Thread.sleep(50); verify(registry).evictAll(argument.capture()); assertThat(argument.getValue().match(remoteServer1), is(true)); assertThat(argument.getValue().match(remoteServer2), is(false)); }
Source:
protected void executeCommand() { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.AddBricksToGlusterVolume, new GlusterVolumeBricksActionVDSParameters(getUpServer().getId(), getGlusterVolumeName(), getParameters().getBricks(), getParameters().getReplicaCount(), getParameters().getStripeCount())); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { addGlusterVolumeBricksInDb(getParameters().getBricks(), getParameters().getReplicaCount(), getParameters().getStripeCount()); } setSucceeded(returnValue.getSucceeded()); }

Target:
protected void executeCommand() { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.AddBricksToGlusterVolume, new GlusterVolumeBricksActionVDSParameters(getUpServer().getId(), getGlusterVolumeName(), getParameters().getBricks(), getParameters().getReplicaCount(), getParameters().getStripeCount())); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { addGlusterVolumeBricksInDb(getParameters().getBricks(), getParameters().getReplicaCount(), getParameters().getStripeCount()); } }
Source:
protected void migrateData( ReviewDb db, UpdateUI ui) throws OrmException { Repository git; try { git = mgr.openRepository(allProjects); } catch (IOException e) { throw new OrmException(e); } try { MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git); ProjectConfig config = ProjectConfig.read(md); List<AccountGroup.UUID> adminGroupUUIDs = getAdministrateServerGroups(db, config); if (!adminGroupUUIDs.isEmpty()) { createGroup(db, "Change Owner", adminGroupUUIDs.get(0), "The owner of a change"); } } catch (IOException e) { throw new OrmException(e); } catch (ConfigInvalidException e) { throw new OrmException(e); } finally { git.close(); } }

Target:
protected void migrateData( ReviewDb db, UpdateUI ui) throws OrmException { Repository git; try { git = mgr.openRepository(allProjects); } catch (IOException e) { throw new OrmException(e); } try { MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git); ProjectConfig config = ProjectConfig.read(md); AccountGroup.UUID adminGroupUUID = findAdminGroup(db, config); createGroup(db, "Change Owner", adminGroupUUID, "The owner of a change"); } catch (IOException e) { throw new OrmException(e); } catch (ConfigInvalidException e) { throw new OrmException(e); } finally { git.close(); } }
Source:
public void handlePost(ActionParameters params) throws ActionException { params.requireLoggedInUser(); try { JSONArray paramFeatures = new JSONArray(params.getHttpParam("featureData")); JSONArray updatedFeatureIds = new JSONArray(); for (int i = 0; i < paramFeatures.length(); i++) { JSONObject featureJSON = paramFeatures.getJSONObject(i); OskariLayer layer = getLayer(featureJSON.optString("layerId")); if (!canEdit(layer, params.getUser())) { throw new ActionDeniedException("User doesn't have edit permission for layer: " + layer.getId()); } final String wfstMessage = createWFSTMessage(featureJSON); LOG.debug("Inserting feature to service at", layer.getUrl(), "with payload", wfstMessage); final String responseString = postPayload(layer, wfstMessage); updatedFeatureIds.put(parseFeatureIdFromResponse(responseString)); flushLayerTilesCache(layer.getId()); } ResponseHelper.writeResponse(params, JSONHelper.createJSONObject("fids", updatedFeatureIds)); } catch (JSONException e) { LOG.error(e, "JSON processing error"); throw new ActionException("JSON processing error", e); } }

Target:
public void handlePost(ActionParameters params) throws ActionException { params.requireLoggedInUser(); try { JSONArray paramFeatures = new JSONArray(params.getHttpParam("featureData")); JSONArray updatedFeatureIds = new JSONArray(); Map<Integer, OskariLayer> layers = getLayers(paramFeatures); hasUserPermissionEditLayers(layers, params.getUser()); for (int i = 0; i < paramFeatures.length(); i++) { JSONObject featureJSON = paramFeatures.getJSONObject(i); OskariLayer layer = getLayer(featureJSON.optString("layerId")); final String wfstMessage = createWFSTMessage(featureJSON); LOG.debug("Inserting feature to service at", layer.getUrl(), "with payload", wfstMessage); final String responseString = postPayload(layer, wfstMessage); updatedFeatureIds.put(parseFeatureIdFromResponse(responseString)); } flushLayerTilesCache(layers); ResponseHelper.writeResponse(params, JSONHelper.createJSONObject("fids", updatedFeatureIds)); } catch (JSONException e) { LOG.error(e, "JSON processing error"); throw new ActionException("JSON processing error", e); } }
Source:
public boolean offer(Message msg) { if (capacity == 0) { try { queue.put(msg); } catch (InterruptedException e) { return false; } return true; } return queue.offer(msg); }

Target:
public boolean offer(Message msg) { if (capacity == 0) { try { queue.put(msg); } catch (InterruptedException e) { return false; } return true; } else { return queue.offer(msg); } }
Source:
private GraphHopperStorage newGHStorage(Directory dir, boolean is3D, boolean forEdgeBasedTraversal, int segmentSize) { GraphHopperStorage graph = new GraphBuilder(encodingManager) .setDir(dir).set3D(is3D).withTurnCosts(true).setSegmentSize(segmentSize).build(); for (FlagEncoder encoder : encodingManager.fetchEdgeEncoders()) { FastestWeighting weighting = new FastestWeighting(encoder, new DefaultTurnCostProvider(encoder, graph.getTurnCostStorage())); graph.addCHGraph(new CHProfile(weighting, forEdgeBasedTraversal)); } return graph; }

Target:
private GraphHopperStorage newGHStorage(Directory dir, boolean is3D, boolean forEdgeBasedTraversal, int segmentSize) { GraphHopperStorage graph = new GraphBuilder(encodingManager) .setDir(dir).set3D(is3D).withTurnCosts(true).setSegmentSize(segmentSize).build(); for (FlagEncoder encoder : encodingManager.fetchEdgeEncoders()) { TurnCostProvider turnCostProvider = forEdgeBasedTraversal ? new DefaultTurnCostProvider(encoder, graph.getTurnCostStorage()) : TurnCostProvider.NO_TURN_COST_PROVIDER; FastestWeighting weighting = new FastestWeighting(encoder, turnCostProvider); graph.addCHGraph(new CHProfile(weighting, forEdgeBasedTraversal)); } return graph; }
Source:
public Observation.ObservationStatus getObsStatus(Obs obs) { Observation.ObservationStatus status = Observation.ObservationStatus.FINAL; return status; }

Target:
public Observation.ObservationStatus getObsStatus(Obs obs) { return Observation.ObservationStatus.FINAL; }
Source:
public List<CourseComponent> getVideos(boolean downloadableOnly) { List<CourseComponent> videos = new ArrayList<>(); fetchAllLeafComponents(videos, EnumSet.of(BlockType.VIDEO)); for (Iterator<CourseComponent> videosIterator = videos.iterator(); videosIterator.hasNext(); ) { CourseComponent videoComponent = videosIterator.next(); if (!(videoComponent instanceof VideoBlockModel)) { videosIterator.remove(); } else if (downloadableOnly && videoComponent.getDownloadableVideosCount() == 0) { videosIterator.remove(); } } return videos; }

Target:
public List<CourseComponent> getVideos(boolean downloadableOnly) { List<CourseComponent> videos = new ArrayList<>(); fetchAllLeafComponents(videos, EnumSet.of(BlockType.VIDEO)); for (Iterator<CourseComponent> videosIterator = videos.iterator(); videosIterator.hasNext(); ) { CourseComponent videoComponent = videosIterator.next(); if (!(videoComponent instanceof VideoBlockModel) || downloadableOnly && videoComponent.getDownloadableVideosCount() == 0) { videosIterator.remove(); } } return videos; }
Source:
public List<String> sendTuple(final Tuple<K, V> tuple) { waitForInitializing(); checkState(State.SENDING); return dataSender.sendTuple(tuple); }

Target:
public List<String> sendTuple(final Tuple<K, V> tuple) { waitForSenderInitialized(); stateMachine.checkState(PushShuffleSenderState.SENDING); final List<String> sentReceiverIdList = dataSender.sendTuple(tuple); messageChecker.messageSent(sentReceiverIdList.size()); return sentReceiverIdList; }
Source:
public CourseInfo(InstructorAttributes currentInstructor, CourseDetailsBundle courseDetails, List<InstructorAttributes> instructors) { this.currentInstructor = currentInstructor; this.courseDetails = courseDetails; this.instructors = instructors; this.sections = new ArrayList<>(); for (SectionDetailsBundle section : courseDetails.sections) { boolean isAllowedToViewStudentInSection = currentInstructor.isAllowedForPrivilege(section.name, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS); boolean isAllowedToModifyStudent = currentInstructor.isAllowedForPrivilege(section.name, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); for (TeamDetailsBundle teamDetails : section.teams) { sections.add(new StudentListSectionData(section.name, isAllowedToViewStudentInSection, isAllowedToModifyStudent, createStudentDataInSection(section.name, teamDetails.students))); } } if (sections.size() == 1) { StudentListSectionData section = sections.get(0); this.hasSection = !"None".equals(section.sectionName); } else { this.hasSection = true; } }

Target:
public CourseInfo(InstructorAttributes currentInstructor, CourseDetailsBundle courseDetails, List<InstructorAttributes> instructors) { this.currentInstructor = currentInstructor; this.courseDetails = courseDetails; this.instructors = instructors; this.sections = new ArrayList<>(); for (SectionDetailsBundle section : courseDetails.sections) { boolean isAllowedToViewStudentInSection = currentInstructor.isAllowedForPrivilege(section.name, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS); boolean isAllowedToModifyStudent = currentInstructor.isAllowedForPrivilege(section.name, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); for (TeamDetailsBundle teamDetails : section.teams) { sections.add(new StudentListSectionData(section.name, isAllowedToViewStudentInSection, isAllowedToModifyStudent, createStudentDataInSection(section.name, teamDetails.students))); } } if (sections.size() == 1) { StudentListSectionData section = sections.get(0); this.hasSection = !Const.DEFAULT_SECTION.equals(section.sectionName); } else { this.hasSection = true; } }
Source:
public String toString() { return "Weapon [firerate=" + firerate + ", magazineSize=" + magazineSize + ", damage=" + damage + ", shooting=" + shooting + "]"; }

Target:
public String toString() { return String.format("Weapon [firerate=%s, magazineSize=%s, gameObject=%s, damage=%s, shooting=%s, activeBullets=%s]", firerate, magazineSize, gameObject, damage, shooting, activeBullets); }
Source:
public boolean isLarge() { return this.encodedLength > largeSizeBytes; }

Target:
public boolean isLarge() { return this.onDiskLength() > largeSizeBytes; }
Source:
private void openCropActivity(Uri sourceUri, Uri destinationUri) { UCrop.of(sourceUri, destinationUri) .withAspectRatio(5f, 5f) .start(getActivity(), AddEditPatientFragment.this); }

Target:
private void openCropActivity(Uri sourceUri, Uri destinationUri) { UCrop.of(sourceUri, destinationUri) .withAspectRatio(ApplicationConstants.ASPECT_RATIO_FOR_CROPPING, ApplicationConstants.ASPECT_RATIO_FOR_CROPPING) .start(getActivity(), AddEditPatientFragment.this); }
Source:
public void onNext(final FailedEvaluator failedEvaluator) { final String evaluatorId = failedEvaluator.getId(); if (!idMap.containsKey(evaluatorId)) { LOG.warning("Failed to find a requestor for " + evaluatorId + ". Ignore " + failedEvaluator.toString()); return; } final String requestorId = idMap.get(evaluatorId); if (requestorId.equals(DataLoader.class.getName())) { dataLoader.handleDataLoadingEvalFailure(failedEvaluator); } else if (requestorId.equals(ElasticMemory.class.getName())) { } else { LOG.warning("Unknown failed evaluator. Ignore " + failedEvaluator.toString()); } }

Target:
public void onNext(final FailedEvaluator failedEvaluator) { final String evaluatorId = failedEvaluator.getId(); final String requestorId = evalToRequestorMap.get(evaluatorId); if (requestorId == null) { LOG.warning("Failed to find a requestor for " + evaluatorId + ". Ignore " + failedEvaluator); return; } if (requestorId.equals(DataLoader.class.getName())) { dataLoader.handleDataLoadingEvalFailure(failedEvaluator); } else if (requestorId.equals(ElasticMemory.class.getName())) { } else { LOG.warning("Unknown failed evaluator. Ignore " + failedEvaluator); } }
Source:
private static boolean useInvokeDynamic() { String property = System.getProperty(ENABLE_INVOKEDYNAMIC); if (property != null) { return Boolean.valueOf(property); } else { String javaVersion = System.getProperty("java.version"); return javaVersion.compareTo(INVOKEDYNAMIC_MINIMUM_VERSION) >= 0; } }

Target:
private static boolean useInvokeDynamic() { String property = System.getProperty(ENABLE_INVOKEDYNAMIC); if (property != null) { return Boolean.valueOf(property); } else { JavaVersion javaVersion = new JavaVersion(System.getProperty("java.version")); return javaVersion.compareTo(new JavaVersion(INVOKEDYNAMIC_MINIMUM_VERSION)) >= 0; } }
Source:
public boolean accept(AuditEvent event) { boolean accepted = true; if (event.getLocalizedMessage() != null) { final FileContents currentContents = FileContentsHolder.getCurrentFileContents(); if (currentContents != null) { if (getFileContents() != currentContents) { setFileContents(currentContents); tagSuppressions(); } if (matchesTag(event)) { accepted = false; } } } return accepted; }

Target:
public boolean accept(AuditEvent event) { boolean accepted = true; if (event.getLocalizedMessage() != null) { final FileContents currentContents = FileContentsHolder.getCurrentFileContents(); if (getFileContents() != currentContents) { setFileContents(currentContents); tagSuppressions(); } if (matchesTag(event)) { accepted = false; } } return accepted; }
Source:
protected <EventAtom> boolean removeRule(final RuleSpecification<EventAtom> specification, final EventFilter<? super EventAtom> filter) { Objects.requireNonNull(specification, "Cannot remove null rule specification!"); Objects.requireNonNull(filter, "Cannot remove instance for null filter"); final RuleInstance<?> instance = findInstance(specification, filter); if (instance != null) { instance.dispose(); ruleInstanceTable.remove(specification, filter); return true; } return false; }

Target:
protected <EventAtom> boolean removeRule(final RuleSpecification<EventAtom> specification, final EventFilter<? super EventAtom> filter) { Objects.requireNonNull(specification, "Cannot remove null rule specification!"); Objects.requireNonNull(filter, "Cannot remove instance for null filter"); final RuleInstance<?> instance = findInstance(specification, filter); if (instance != null) { instance.dispose(); ruleInstanceTable.compute(specification, (k, old) -> { old.remove(filter); return old.isEmpty() ? null: old; }); return true; } return false; }
Source:
public void addUser(String user, EntitlementManager managerForThisUser) { perUserManagers.put(user, managerForThisUser); }

Target:
public void addUser(String user, EntitlementManager managerForThisUser) { perUserManagers.put(Preconditions.checkNotNull(user, "user"), Preconditions.checkNotNull(managerForThisUser, "managerForThisUser")); }
Source:
public @ResponseBody JSONObj update(@PathVariable String wsName, @PathVariable Long id, @RequestBody JSONObj obj) throws Exception { Catalog catalog = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, catalog); ImportContext imp = findImport(id); System.out.println("Update import " + id + " with state " + imp.getState()); if (imp.getState() == ImportContext.State.PENDING) { ImportFilter f = filter(obj); return continueImport(imp, ws, f); } Integer t = obj.integer("task"); if (t == null) { throw new BadRequestException("Request must contain task identifier"); } final ImportTask task = imp.task(t); if (task == null) { throw new NotFoundException("No such task: " + t + " for import: " + id); } ResourceInfo resource = task.getLayer().getResource(); if (task.getState() == ImportTask.State.NO_CRS) { JSONObj proj = obj.object("proj"); if (proj == null) { throw new BadRequestException("Request must contain a 'proj' property"); } try { resource.setSRS(IO.srs(proj)); resource.setNativeCRS(IO.crs(proj)); importer.changed(task); } catch(Exception e) { throw new BadRequestException("Unable to parse proj: " + proj.toString()); } } importer.run(imp, new ImportFilter() { @Override public boolean include(ImportTask t) { return task.getId() == t.getId(); } }); if (task.getState() == ImportTask.State.COMPLETE) { return complete(task); } else { switch(task.getState()) { case NO_CRS: case NO_BOUNDS: return pending(task); case ERROR: return failed(task); default: return ignored(task); } } }

Target:
public @ResponseBody JSONObj update(@PathVariable String wsName, @PathVariable Long id, @RequestBody JSONObj obj) throws Exception { Catalog catalog = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, catalog); ImportContext imp = findImport(id); if (imp.getState() == ImportContext.State.PENDING) { ImportFilter f = filter(obj); return continueImport(imp, ws, f); } Integer t = obj.integer("task"); if (t == null) { throw new BadRequestException("Request must contain task identifier"); } final ImportTask task = imp.task(t); if (task == null) { throw new NotFoundException("No such task: " + t + " for import: " + id); } ResourceInfo resource = task.getLayer().getResource(); if (task.getState() == ImportTask.State.NO_CRS) { JSONObj proj = obj.object("proj"); if (proj == null) { throw new BadRequestException("Request must contain a 'proj' property"); } try { resource.setSRS(IO.srs(proj)); resource.setNativeCRS(IO.crs(proj)); importer.changed(task); } catch(Exception e) { throw new BadRequestException("Unable to parse proj: " + proj.toString()); } } importer.run(imp, new ImportFilter() { @Override public boolean include(ImportTask t) { return task.getId() == t.getId(); } }); if (task.getState() == ImportTask.State.COMPLETE) { return complete(task); } else { switch(task.getState()) { case NO_CRS: case NO_BOUNDS: return pending(task); case ERROR: return failed(task); default: return ignored(task); } } }
Source:
public void loadProjectClassloaderFromStringTest() throws Exception { CompilationResponse res = compileProjectInRepo(MavenCLIArgs.CLEAN, MavenCLIArgs.COMPILE, MavenCLIArgs.INSTALL); if (!res.isSuccessful()) { TestUtil.writeMavenOutputIntoTargetFolder(tmp, res.getMavenOutput(), "ClassLoaderProviderTest.loadProjectClassloaderFromStringTest"); } assertThat(res.isSuccessful()).isTrue(); Optional<ClassLoader> clazzLoader = CompilerClassloaderUtils.loadDependenciesClassloaderFromProject(uberfireTmp.toAbsolutePath().toString(), mavenRepo.toAbsolutePath().toString()); assertThat(clazzLoader).isNotNull(); assertThat(clazzLoader.isPresent()).isTrue(); LoadProjectDependencyUtil.loadLoggerFactory(clazzLoader.get()); if (tmpRoot != null) { TestUtil.rm(tmpRoot.toFile()); } }

Target:
public void loadProjectClassloaderFromStringTest() throws Exception { CompilationResponse res = compileProjectInRepo(MavenCLIArgs.CLEAN, MavenCLIArgs.COMPILE, MavenCLIArgs.INSTALL); TestUtil.saveMavenLogIfCompilationResponseNotSuccessfull(tmp, res, this.getClass(), testName); assertThat(res.isSuccessful()).isTrue(); Optional<ClassLoader> clazzLoader = CompilerClassloaderUtils.loadDependenciesClassloaderFromProject(uberfireTmp.toAbsolutePath().toString(), mavenRepo.toAbsolutePath().toString()); assertThat(clazzLoader).isPresent(); LoadProjectDependencyUtil.loadLoggerFactory(clazzLoader.get()); }
Source:
private Optional<String> createTextQueryPlan(QueryInfo queryInfo) { try { if (queryInfo.getOutputStage().isPresent()) { return Optional.of(textDistributedPlan( queryInfo.getOutputStage().get(), functionRegistry, queryInfo.getSession().toSession(sessionPropertyManager), false)); } } catch (Exception e) { log.warn(e, "Error creating explain plan"); } return Optional.empty(); }

Target:
private Optional<String> createTextQueryPlan(QueryInfo queryInfo) { try { if (queryInfo.getOutputStage().isPresent()) { return Optional.of(textDistributedPlan( queryInfo.getOutputStage().get(), functionRegistry, queryInfo.getSession().toSession(sessionPropertyManager), false)); } } catch (Exception e) { log.warn(e, "Error creating explain plan for query %s", queryInfo.getQueryId()); } return Optional.empty(); }
Source:
private RelationshipMetadataValue getRelationMetadataFromOtherItem(Context context, Item otherItem, String relationName, Integer relationshipId) { RelationshipMetadataValue metadataValue = constructMetadataValue(context, MetadataSchemaEnum.RELATION .getName() + "." + relationName); metadataValue.setAuthority(Constants.VIRTUAL_AUTHORITY_PREFIX + relationshipId); metadataValue.setValue(otherItem.getID().toString()); return metadataValue; }

Target:
private RelationshipMetadataValue getRelationMetadataFromOtherItem(Context context, Item otherItem, String relationName, Integer relationshipId) { RelationshipMetadataValue metadataValue = constructMetadataValue(context, MetadataSchemaEnum.RELATION .getName() + "." + relationName); if (metadataValue != null) { metadataValue.setAuthority(Constants.VIRTUAL_AUTHORITY_PREFIX + relationshipId); metadataValue.setValue(otherItem.getID().toString()); return metadataValue; } return null; }
Source:
private Set<Location> getAllChildAndGrandLocations(Set<Location> visitLocations){ Set<Location>allchildAndGrandVisitLocations=new HashSet<Location>(); for(Location visitLocation:visitLocations) { allchildAndGrandVisitLocations.addAll(visitLocation.getChildLocations()); if(visitLocation.getChildLocations() !=null) { getAllChildAndGrandLocations(allchildAndGrandVisitLocations); } else { break; } } return allchildAndGrandVisitLocations; }

Target:
public static Set<Location> getAllChildAndGrandLocations(Set<Location> visitLocations) { Set<Location> allchildAndGrandVisitLocations = new HashSet<Location>(); for (Location visitLocation : visitLocations) { if (visitLocation.getChildLocations() != null) { allchildAndGrandVisitLocations.addAll(visitLocation.getChildLocations()); getAllChildAndGrandLocations(allchildAndGrandVisitLocations); } else { break; } } return allchildAndGrandVisitLocations; }
Source:
private boolean checkPermissions(Attribute attr, Subject subject, String action) { Map<String, Set<String>> map = null; KeyValueCollectionPermission securityPermission; if (attr != null) { map = (Map<String, Set<String>>) attr.getValue(); } if (MapUtils.isNotEmpty(map)) { securityPermission = new KeyValueCollectionPermission(action, map); } else { securityPermission = new KeyValueCollectionPermission(action); } return subject.isPermitted(securityPermission); }

Target:
private boolean checkPermissions(Attribute attr, Subject subject, String action) { Map<String, Set<String>> map = null; KeyValueCollectionPermission securityPermission; if (attr != null) { map = (Map<String, Set<String>>) attr.getValue(); } if (MapUtils.isNotEmpty(map)) { securityPermission = new KeyValueCollectionPermission(action, map); } else { return false; } return subject.isPermitted(securityPermission); }
Source:
public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction read-only property in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } if (readOnly != this.readOnly) { if (autoCommit) { execSQLUpdate(readOnly ? setSessionReadOnly : setSessionNotReadOnly); } } this.readOnly = readOnly; LOGGER.log(Level.FINE, " setReadOnly = {0}", readOnly); }

Target:
public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction read-only property in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } if (readOnly != this.readOnly && autoCommit && this.readOnlyBehavior == ReadOnlyBehavior.always) { execSQLUpdate(readOnly ? setSessionReadOnly : setSessionNotReadOnly); } this.readOnly = readOnly; LOGGER.log(Level.FINE, " setReadOnly = {0}", readOnly); }
Source:
public void addMetric(IMetric metric) { MetricInfo info = metrics.get(metric.getName()); if (info == null) { metrics.put(metric.getName(), new MetricInfo(metric)); } else { info.metric = metric; } }

Target:
public void addMetric(IMetric metric) { if (metric == null) { throw new RuntimeException("BenchmarkResult: Error: A null IMetric was provided to addMetric."); } MetricInfo info = metrics.get(metric.getName()); if (info == null) { metrics.put(metric.getName(), new MetricInfo(metric)); } else { info.metric = metric; } }
Source:
public static AtomicLoadKeyStore newInstance(final String type, final Provider provider) { AtomicLoadKeyStoreSpi keyStoreSpi = new AtomicLoadKeyStoreSpi(() -> KeyStore.getInstance(type, provider)); if (ElytronMessages.tls.isTraceEnabled()) { ElytronMessages.tls.trace("AtomicLoadKeyStore creating:" + "\n type = " + type + "\n provider = " + provider + "\n"); } return new AtomicLoadKeyStore(keyStoreSpi, provider, type); }

Target:
public static AtomicLoadKeyStore newInstance(final String type, final Provider provider) { AtomicLoadKeyStoreSpi keyStoreSpi = new AtomicLoadKeyStoreSpi(() -> KeyStore.getInstance(type, provider)); ElytronMessages.tls.tracef("AtomicLoadKeyStore creating: type = %s, provider = %s", type, provider); return new AtomicLoadKeyStore(keyStoreSpi, provider, type); }
Source:
private TableViewer createTableViewerSection(Composite aParent) { GridLayout layout = new GridLayout(2, false); aParent.setLayout(layout); Label labelHeader = new Label(aParent, SWT.NONE); labelHeader.setText(Messages.BranchSelectionTableModel_question); labelHeader.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); fViewer = new TableViewer(aParent, TABLE_STYLE); buildAndLayoutTable(); ReviewTableSorter.bind(fViewer); fViewer.setComparator(new ReviewTableSorter(1)); fViewer.setContentProvider(new BranchListContentProvider()); fViewer.setLabelProvider(new BranchListLabelProvider()); fViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (selection instanceof StructuredSelection) { Entry entry = (Entry) ((StructuredSelection) selection).getFirstElement(); selectedBranch = (String) entry.getKey(); } } }); fViewer.setInput(potentialBranches); int foundMatchAt = findPerfectMatch(); if (foundMatchAt >= 0) { selectPerfectBranch(foundMatchAt); } return fViewer; }

Target:
private TableViewer createTableViewerSection(Composite aParent) { GridLayout layout = new GridLayout(2, false); aParent.setLayout(layout); Label labelHeader = new Label(aParent, SWT.NONE); labelHeader.setText(NLS.bind(Messages.BranchSelectionTableModel_question, reviewName, selectedPatchSet)); labelHeader.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); fViewer = new TableViewer(aParent, TABLE_STYLE); buildAndLayoutTable(); ReviewTableSorter.bind(fViewer); fViewer.setComparator(new ReviewTableSorter(1)); fViewer.setContentProvider(new BranchListContentProvider()); fViewer.setLabelProvider(new BranchListLabelProvider()); fViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (selection instanceof StructuredSelection) { Entry entry = (Entry) ((StructuredSelection) selection).getFirstElement(); selectedBranch = (String) entry.getKey(); } } }); fViewer.setInput(potentialBranches); int foundMatchAt = findPerfectMatch(); if (foundMatchAt >= 0) { selectPerfectBranch(foundMatchAt); } return fViewer; }