auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private double getClassMembersCount(int numClasses, List<Double> breaks, double[] arClassMembers, HistogramClassification.Bucket b) { int bucketCount = b.getCount(); double assignedElements = 0.0; for (int i = 0; i < numClasses; i++) { double current = breaks.get(i); double next = breaks.get(i + 1); boolean last = i + 1 == numClasses; Double overlapping; if (last) { overlapping = getOverlappingPercentages(current, next, b.getMin(), b.getMax()); } else { overlapping = getOverlappingPercentages(current, Math.nextDown(next), b.getMin(), b.getMax()); } if (overlapping.doubleValue() == 1.0 || overlapping.equals(NaN)) { arClassMembers[i] += bucketCount; assignedElements = bucketCount; } else if (overlapping.doubleValue() == 0.0) { arClassMembers[i] += 0.0; } else { double classMembers = overlapping * bucketCount; arClassMembers[i] += classMembers; assignedElements += classMembers; } } return bucketCount - assignedElements; }

Target:
private void getClassMembersCount(int numClasses, List<Double> breaks, double[] arClassMembers, HistogramClassification.Bucket b) { int bucketCount = b.getCount(); for (int i = 0; i < numClasses; i++) { double current = breaks.get(i); double next = breaks.get(i + 1); boolean last = i + 1 == numClasses; Double overlapping; if (last) { overlapping = getOverlappingPercentages(current, next, b.getMin(), b.getMax()); } else { overlapping = getOverlappingPercentages(current, Math.nextDown(next), b.getMin(), b.getMax()); } if (overlapping.doubleValue() == 1.0) { arClassMembers[i] += bucketCount; } else if (overlapping.doubleValue() == 0.0) { arClassMembers[i] += 0.0; } else { double classMembers = overlapping * bucketCount; arClassMembers[i] += classMembers; } } }
Source:
public void onScreenLoad(ScreenLoadEvent event) { if (event.getScreen().getToken().equals(getTargetHistoryToken())){ Gerrit.currentMenu = null; addStyleName(Gerrit.RESOURCES.css().activeRow()); } else { removeStyleName(Gerrit.RESOURCES.css().activeRow()); } }

Target:
public void onScreenLoad(ScreenLoadEvent event) { if (match(event.getScreen().getToken())) { Gerrit.selectMenu(bar); addStyleName(Gerrit.RESOURCES.css().activeRow()); } else { removeStyleName(Gerrit.RESOURCES.css().activeRow()); } }
Source:
public void testConvertToDataModelTypeWithoutStats() { file.getSamplesData().clear(); List<String> sampleNames = null; uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantSourceEntryConverter converter = new uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantSourceEntryConverter( VariantStorageManager.IncludeSrc.FULL, new DBObjectToSamplesConverter(sampleNames)); VariantSourceEntry converted = converter.convert(mongoFile); assertEquals(file, converted); converter = new uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantSourceEntryConverter( VariantStorageManager.IncludeSrc.FULL, new DBObjectToSamplesConverter(sampleNames)); converted = converter.convert(mongoFile); assertEquals(file, converted); }

Target:
public void testConvertToDataModelTypeWithoutStats() { file.getSamplesData().clear(); List<String> sampleNames = new ArrayList<String>(); DBObjectToVariantSourceEntryConverter converter = new DBObjectToVariantSourceEntryConverter( new DBObjectToSamplesConverter(sampleNames)); VariantSourceEntry converted = converter.convert(mongoFile); assertEquals(file, converted); converter = new DBObjectToVariantSourceEntryConverter( new DBObjectToSamplesConverter(sampleNames)); converted = converter.convert(mongoFile); assertEquals(file, converted); }
Source:
private void initStreamLogDirectory() { try { if (!logDir.toFile().exists()) { Files.createDirectories(logDir); } String corfuDir = logDir.getParent().toString(); FileStore fs = Files.getFileStore(Paths.get(corfuDir)); if (fs.isReadOnly()) { throw new IllegalArgumentException("Cannot start Corfu on a read-only filesystem:" +corfuDir); } if (logSizeLimit != Long.MAX_VALUE && logSizeLimit > fs.getTotalSpace()) { String msg = String.format("Invalid quota: quota(%d) is greater than the file store size (%d)", logSizeLimit, fs.getTotalSpace()); throw new IllegalArgumentException(msg); } File corfuDirFile = new File(corfuDir); if (!corfuDirFile.canWrite()) { throw new IllegalArgumentException("Corfu directory is not writable " + corfuDir); } File logDirectory = new File(logDir.toString()); if (!logDirectory.canWrite()) { throw new IllegalArgumentException("Stream log directory not writable in "+corfuDir); } } catch (IOException ioe) { throw new LogUnitException(ioe); } log.info("initStreamLogDirectory: initialized {}", logDir); }

Target:
private void initStreamLogDirectory() { try { if (!logDir.toFile().exists()) { Files.createDirectories(logDir); } String corfuDir = logDir.getParent().toString(); FileStore corfuDirBackend = Files.getFileStore(Paths.get(corfuDir)); if (corfuDirBackend.isReadOnly()) { throw new LogUnitException("Cannot start Corfu on a read-only filesystem:" + corfuDir); } if (logSizeLimit != -1 && logSizeLimit > corfuDirBackend.getTotalSpace()) { String msg = String.format("Invalid quota: quota(%d) is greater than the file store size (%d)", logSizeLimit, corfuDirBackend.getTotalSpace()); throw new LogUnitException(msg); } File corfuDirFile = new File(corfuDir); if (!corfuDirFile.canWrite()) { throw new LogUnitException("Corfu directory is not writable " + corfuDir); } File logDirectory = new File(logDir.toString()); if (!logDirectory.canWrite()) { throw new LogUnitException("Stream log directory not writable in " + corfuDir); } } catch (IOException ioe) { throw new LogUnitException(ioe); } log.info("initStreamLogDirectory: initialized {}", logDir); }
Source:
public void run() { if (isInterruptedOrCanceled(monitor)) { return; } final Resource resource = resourceSet.loadResource(uri); Diagnostic resourceDiagnostic = EcoreUtil.computeDiagnostic(resource, true); if (resourceDiagnostic.getSeverity() >= Diagnostic.WARNING) { safeMergeDiagnostic(resourceDiagnostic); } if (getResolutionScope() != CrossReferenceResolutionScope.SELF) { final Set<URI> crossReferencedResources = resourceSet.discoverCrossReferences(resource, monitor); for (URI crossRef : crossReferencedResources) { if (Thread.currentThread().isInterrupted() || monitor.isCanceled()) { break; } demandRemoteResolve(resourceSet, crossRef, monitor); } } demandUnload(resourceSet, resource, monitor); }

Target:
public void run() { if (isInterruptedOrCanceled(monitor)) { demandResolvingAndUnloadingPoolShutdown(); return; } final Resource resource = resourceSet.loadResource(uri); Diagnostic resourceDiagnostic = EcoreUtil.computeDiagnostic(resource, true); if (resourceDiagnostic.getSeverity() >= Diagnostic.WARNING) { safeMergeDiagnostic(resourceDiagnostic); } if (getResolutionScope() != CrossReferenceResolutionScope.SELF) { final Set<URI> crossReferencedResources = resourceSet.discoverCrossReferences(resource, monitor); for (URI crossRef : crossReferencedResources) { if (isInterruptedOrCanceled(monitor)) { demandResolvingAndUnloadingPoolShutdown(); break; } demandRemoteResolve(resourceSet, crossRef, monitor); } } demandUnload(resourceSet, resource, monitor); }
Source:
public BalanceTopImpl getBalanceTop() { return balanceTop; }

Target:
public BalanceTop getBalanceTop() { return balanceTop; }
Source:
private static boolean attemptToCreateKeyspaceOnHost(InetSocketAddress host, CassandraKeyValueServiceConfig config) throws TException { try { CassandraClient client = CassandraClientFactory.getClientInternal(host, config); KsDef ksDef = createKsDefForFresh(client, config); client.system_add_keyspace(ksDef); log.info("Created keyspace: {}", UnsafeArg.of("keyspace", config.getKeyspaceOrThrow())); CassandraKeyValueServices.waitForSchemaVersions( config, client, "(adding the initial empty keyspace)", true); return true; } catch (InvalidRequestException e) { return keyspaceAlreadyExists(host, config); } }

Target:
private static boolean attemptToCreateKeyspaceOnHost(InetSocketAddress host, CassandraKeyValueServiceConfig config) throws TException { try { CassandraClient client = CassandraClientFactory.getClientInternal(host, config); KsDef ksDef = createKsDefForFresh(client, config); client.system_add_keyspace(ksDef); log.info("Created keyspace: {}", SafeArg.of("keyspace", config.getKeyspaceOrThrow())); CassandraKeyValueServices.waitForSchemaVersions( config, client, "(adding the initial empty keyspace)", true); return true; } catch (InvalidRequestException e) { return keyspaceAlreadyExists(host, config); } }
Source:
@Override public <T> Collection<T> services(String name) { if (!enterBusy()) return null; try { ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null); Collection<ServiceContextImpl> ctxs = serviceContexts(name); if (F.isEmpty(ctxs)) return null; Collection<T> res = new ArrayList<>(ctxs.size()); synchronized (ctxs) { for (ServiceContextImpl ctx : ctxs) { Service srvc = ctx.service(); if (srvc != null) res.add((T)srvc); } } return res; } finally { leaveBusy(); } }

Target:
@Override public <T> Collection<T> services(String name) { if (!enterBusy()) return null; try { ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null); Collection<ServiceContextImpl> ctxs = serviceContexts(name); if (ctxs == null) return null; synchronized (ctxs) { if (F.isEmpty(ctxs)) return null; Collection<T> res = new ArrayList<>(ctxs.size()); for (ServiceContextImpl ctx : ctxs) { Service srvc = ctx.service(); if (srvc != null) res.add((T)srvc); } return res; } } finally { leaveBusy(); } }
Source:
public void init() throws SlickException { if (!initialized) { this.map.init(); initialized = true; try { float moveSpeed = 16.0F; Vector2D viewPortDrawingPosition = Vector2D.zero(); final Viewport newViewport; newViewport = new Viewport(Game.SCREEN_WIDTH, Game.SCREEN_HEIGHT, this.map); DrawableViewPort drawableViewPort = new DrawableViewPort(newViewport, viewPortDrawingPosition, Vector2D.zero(), graphics, moveSpeed); input.addMouseListener(new DrawableViewPortMoverListener(drawableViewPort)); drawableViewPorts.add(drawableViewPort); } catch (SlickException e) { throw new IllegalStateException("Unable to create new viewport!"); } } }

Target:
public void init() throws SlickException { if (!initialized) { this.map.init(); initialized = true; try { float moveSpeed = 16.0F; Vector2D viewportDrawingPosition = Vector2D.zero(); Viewport viewport = new Viewport(screenResolution, viewportDrawingPosition, Vector2D.zero(), graphics, this.map, moveSpeed); input.addMouseListener(new ViewportMovementListener(viewport, screenResolution)); viewports.add(viewport); } catch (SlickException e) { throw new IllegalStateException("Unable to create new viewport!", e); } } }
Source:
public static boolean isDefault(Message object) { checkNotNull(object); return object.getDefaultInstanceForType().equals(object); }

Target:
public static boolean isDefault(Message object) { checkNotNull(object); final boolean result = object.getDefaultInstanceForType().equals(object); return result; }
Source:
protected List<Folder> findFoldersByHost(Host host) throws DotHibernateException { List<Folder> folderList= getSubFolders(null, "/", host.getIdentifier(), null); Collections.sort(folderList, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); return folderList; }

Target:
protected List<Folder> findFoldersByHost(Host host) throws DotHibernateException { List<Folder> folderList = getSubFolders(null, "/", host.getIdentifier(), null); Collections.sort(folderList, (Folder folder1, Folder folder2) -> folder1.getName() .compareToIgnoreCase(folder2.getName())); return folderList; }
Source:
public CRFetchArtifactTask fetchTaskToCRFetchTask(FetchTask task) { CRFetchArtifactTask fetchTask = new CRFetchArtifactTask( task.getStage().toString(), task.getJob().toString(), task.getSrc()); fetchTask.setDestination(task.getDest()); fetchTask.setPipelineName(task.getPipelineName().toString()); fetchTask.setSourceIsDirectory(task.isSourceAFile()); commonCRTaskMembers(fetchTask, task); return fetchTask; }

Target:
private CRFetchArtifactTask fetchTaskToCRFetchTask(FetchTask task) { CRFetchArtifactTask fetchTask = new CRFetchArtifactTask( task.getStage().toString(), task.getJob().toString(), task.getSrc()); fetchTask.setDestination(task.getDest()); fetchTask.setPipelineName(task.getPipelineName().toString()); fetchTask.setSourceIsDirectory(!task.isSourceAFile()); commonCRTaskMembers(fetchTask, task); return fetchTask; }
Source:
public void testNullPartitionValues() { assertUpdate("" + "CREATE TABLE test_null_partition (test VARCHAR, part VARCHAR)\n" + "WITH (partitioned_by = ARRAY['part'])"); assertUpdate("INSERT INTO test_null_partition VALUES ('hello', 'test'), ('world', null)", 2); assertQuery( "SELECT * FROM test_null_partition", "VALUES ('hello', 'test'), ('world', null)"); assertQuery( "SELECT * FROM \"test_null_partition$partitions\"", "VALUES ('test'), (null)"); assertUpdate("DROP TABLE test_null_partition"); }

Target:
public void testNullPartitionValues() { assertUpdate("" + "CREATE TABLE test_null_partition (test VARCHAR, part VARCHAR)\n" + "WITH (partitioned_by = ARRAY['part'])"); assertUpdate("INSERT INTO test_null_partition VALUES ('hello', 'test'), ('world', null)", 2); assertQuery( "SELECT * FROM test_null_partition", "VALUES ('hello', 'test'), ('world', null)"); assertQuery( "SELECT * FROM \"test_null_partition$partitions\"", "VALUES 'test', null"); assertUpdate("DROP TABLE test_null_partition"); }
Source:
public void createControl(Composite parent) { Composite comp = SWTFactory.createComposite(parent, 1, 1, GridData.FILL_HORIZONTAL); setControl(comp); SWTFactory.createWrapLabel(comp, "What is your source for this baseline?", 1); locationIsDirectory = SWTFactory.createRadioButton(comp, "An existing Eclipse installation directory"); locationIsTarget = SWTFactory.createRadioButton(comp, "A target platform"); locationIsDirectory.setSelection(true); SelectionListener typeListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { update(); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }; MouseListener mouseClickListener = new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { update(); getContainer().showPage(getNextPage()); } }; locationIsTarget.addSelectionListener(typeListener); locationIsTarget.addMouseListener(mouseClickListener); locationIsDirectory.addSelectionListener(typeListener); locationIsDirectory.addMouseListener(mouseClickListener); update(); PlatformUI.getWorkbench().getHelpSystem().setHelp(comp, IApiToolsHelpContextIds.APIPROFILES_WIZARD_PAGE); Dialog.applyDialogFont(comp); }

Target:
public void createControl(Composite parent) { Composite comp = SWTFactory.createComposite(parent, 1, 1, GridData.FILL_HORIZONTAL); setControl(comp); SWTFactory.createWrapLabel(comp, WizardMessages.SelectApiBaselineTypeWizardPage_SelectBaselineSource, 1); locationIsDirectory = SWTFactory.createRadioButton(comp, WizardMessages.SelectApiBaselineTypeWizardPage_SourceInstallationDirectory); locationIsTarget = SWTFactory.createRadioButton(comp, WizardMessages.SelectApiBaselineTypeWizardPage_SourceTargetPlatform); locationIsDirectory.setSelection(true); SelectionListener typeListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { update(); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }; MouseListener mouseClickListener = new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { update(); getContainer().showPage(getNextPage()); } }; locationIsTarget.addSelectionListener(typeListener); locationIsTarget.addMouseListener(mouseClickListener); locationIsDirectory.addSelectionListener(typeListener); locationIsDirectory.addMouseListener(mouseClickListener); update(); PlatformUI.getWorkbench().getHelpSystem().setHelp(comp, IApiToolsHelpContextIds.APIPROFILES_WIZARD_PAGE); Dialog.applyDialogFont(comp); }
Source:
private void addConfigAttributesClasses(ContextConfigurationAttributes configAttributes, Class<?>[] classes) { Set<Class<?>> combined = new HashSet<>(Arrays.asList(classes)); if (configAttributes.getClasses() != null) { combined.addAll(Arrays.asList(configAttributes.getClasses())); } configAttributes.setClasses(ClassUtils.toClassArray(combined)); }

Target:
private void addConfigAttributesClasses(ContextConfigurationAttributes configAttributes, Class<?>[] classes) { Set<Class<?>> combined = new LinkedHashSet<>(Arrays.asList(classes)); if (configAttributes.getClasses() != null) { combined.addAll(Arrays.asList(configAttributes.getClasses())); } configAttributes.setClasses(ClassUtils.toClassArray(combined)); }
Source:
public ScoredCandidates<T> generate( T content, ResultDescription desc, EquivToTelescopeResult equivToTelescopeResult ) { DefaultScoredCandidates.Builder<T> candidates = DefaultScoredCandidates.fromSource("Alias"); desc.startStage("Resolving aliases:"); EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName("Alias Resolving Equivalence Generator"); for (Alias alias : getExpandedAliases(content.getAliases())) { desc.appendText("namespace: %s, value: %s", alias.getNamespace(), alias.getValue()); Iterable<LookupEntry> lookupEntries = lookupEntryStore.entriesForAliases( Optional.of(alias.getNamespace()), ImmutableSet.of(alias.getValue()), publishers, includeUnpublishedContent ); List<String> lookupUris = new ArrayList<>(); for (LookupEntry lookupEntry : lookupEntries) { lookupUris.add(lookupEntry.uri()); } ResolvedContent resolved = resolver.findByCanonicalUris(lookupUris); for (T identified : Iterables.filter(resolved.getAllResolvedResults(), cls)) { if (identified.isActivelyPublished()) { candidates.addEquivalent(identified, aliasMatchingScore); desc.appendText("Resolved %s", identified.getCanonicalUri()); generatorComponent.addComponentResult(identified.getId(), aliasMatchingScore.toString()); } } if (resolved.getUnresolved().size() > 0) { desc.appendText("Missed %s", resolved.getUnresolved().size()); } } equivToTelescopeResult.addGeneratorResult(generatorComponent); desc.finishStage(); return candidates.build(); }

Target:
public ScoredCandidates<T> generate( T content, ResultDescription desc, EquivToTelescopeResult equivToTelescopeResult ) { DefaultScoredCandidates.Builder<T> candidates = DefaultScoredCandidates.fromSource("Alias"); desc.startStage("Resolving aliases:"); EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName("Alias Resolving Equivalence Generator"); for (Alias alias : getExpandedAliases(content.getAliases())) { desc.appendText("namespace: %s, value: %s", alias.getNamespace(), alias.getValue()); Iterable<LookupEntry> lookupEntries = lookupEntryStore.entriesForAliases( Optional.of(alias.getNamespace()), ImmutableSet.of(alias.getValue()), publishers, includeUnpublishedContent ); List<String> lookupUris = MoreStreams.stream(lookupEntries) .map(LookupEntry::uri) .collect(MoreCollectors.toImmutableList()); ResolvedContent resolved = resolver.findByCanonicalUris(lookupUris); for (T identified : Iterables.filter(resolved.getAllResolvedResults(), cls)) { if (identified.isActivelyPublished()) { candidates.addEquivalent(identified, aliasMatchingScore); desc.appendText("Resolved %s", identified.getCanonicalUri()); generatorComponent.addComponentResult(identified.getId(), aliasMatchingScore.toString()); } } if (resolved.getUnresolved().size() > 0) { desc.appendText("Missed %s", resolved.getUnresolved().size()); } } equivToTelescopeResult.addGeneratorResult(generatorComponent); desc.finishStage(); return candidates.build(); }
Source:
public void canPerformLockAndRefreshLock() throws InterruptedException { lockWithFullResponse(requestForWriteLock(LOCK_A), TEST_CLIENT); LockRefreshToken token = lockWithFullResponse(requestForWriteLock(LOCK_A), TEST_CLIENT).getLockRefreshToken(); Set<LockRefreshToken> lockRefreshTokens = cluster.lockService().refreshLockRefreshTokens( ImmutableList.of(token)); assertThat(lockRefreshTokens).contains(token); }

Target:
public void canPerformLockAndRefreshLock() throws InterruptedException { HeldLocksToken token1 = lockWithFullResponse(requestForWriteLock(LOCK_A), TEST_CLIENT); LockRefreshToken token = token1.getLockRefreshToken(); Set<LockRefreshToken> lockRefreshTokens = cluster.lockService().refreshLockRefreshTokens( ImmutableList.of(token)); assertThat(lockRefreshTokens).contains(token); unlock(token1); }
Source:
public Summary gatherDeps(BuildRule root) { if (!(root instanceof JavaLibrary)) { throw new RuntimeException("Boom"); } Set<JavaLibrary> toPackage = new HashSet<>(); Set<HasMavenCoordinates> mavenDeps; toPackage.addAll(((HasClasspathEntries) root).getTransitiveClasspathDeps()); mavenDeps = toPackage.stream() .filter(HasMavenCoordinates::isMavenCoordsPresent) .filter(lib -> !lib.equals(root)) .collect(Collectors.toSet()); for (HasMavenCoordinates mavenDep : mavenDeps) { ImmutableSet<JavaLibrary> transitive = ((HasClasspathEntries) mavenDep).getTransitiveClasspathDeps(); toPackage.removeAll(transitive); mavenDeps.removeAll( transitive.stream() .filter(dep -> !dep.equals(mavenDep)) .collect(Collectors.toSet())); } return new Summary( toPackage, ((HasClasspathEntries) root).getTransitiveClasspathDeps(), mavenDeps); }

Target:
public Summary gatherDeps(BuildRule root) { if (!(root instanceof JavaLibrary)) { throw new HumanReadableException( "Maven jars can only be constructed from java_library targets: %s", root.getFullyQualifiedName()); } Set<JavaLibrary> toPackage = new HashSet<>(); ImmutableSet<JavaLibrary> classpathDeps = ((HasClasspathEntries) root).getTransitiveClasspathDeps(); toPackage.addAll(classpathDeps); Set<HasMavenCoordinates> mavenDeps = toPackage.stream() .filter(HasMavenCoordinates::isMavenCoordsPresent) .filter(lib -> !lib.equals(root)) .collect(Collectors.toSet()); Set<JavaLibrary> toRemoveFromMavenDeps = new HashSet<>(); for (HasMavenCoordinates mavenDep : mavenDeps) { ImmutableSet<JavaLibrary> transitive = ((HasClasspathEntries) mavenDep).getTransitiveClasspathDeps(); toPackage.removeAll(transitive); toRemoveFromMavenDeps.addAll( transitive.stream() .filter(dep -> !dep.equals(mavenDep)) .collect(Collectors.toSet())); } mavenDeps.removeAll(toRemoveFromMavenDeps); return new Summary( toPackage, classpathDeps, mavenDeps); }
Source:
public ColumnFamilyStep row(final CharSequence row) { return row(new Text(row.toString())); }

Target:
public ColumnFamilyStep row(final CharSequence row) { return row(encodeCharSequence(row)); }
Source:
public LearnedConstraint(SymbolicValue sv, @Nullable Constraint constraint) { Objects.requireNonNull(sv); this.sv = sv; this.constraint = constraint; }

Target:
public LearnedConstraint(SymbolicValue sv, @Nullable Constraint constraint) { this.sv = sv; this.constraint = constraint; }
Source:
public long check(final AbstractCloudComputer c) { if (c.isIdle()) { done(c); } return 1; }

Target:
public long check(final AbstractCloudComputer c) { if (c.isIdle() && !disabled) { final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds(); if (idleMilliseconds > TimeUnit2.MINUTES.toMillis(idleMinutes)) { LOGGER.log(Level.FINE, "Disconnecting {0}", c.getName()); done(c); } } return 1; }
Source:
public void testDistinctCountPushdown() { PlanNode justScan = buildPlan(planBuilder -> tableScan(planBuilder, pinotTable, regionId, secondsSinceEpoch, city, fare)); PlanNode distinctAggregation = buildPlan(planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(justScan).singleGroupingSet(v("regionid")))); testPQL(planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(distinctAggregation).globalGrouping().addAggregation(v("count_regionid"), getRowExpression("count(regionid)", defaultSessionHolder))), "SELECT DISTINCTCOUNT(regionId) FROM realtimeOnly"); }

Target:
public void testDistinctCountPushdown() { PlanNode justScan = buildPlan(planBuilder -> tableScan(planBuilder, pinotTable, regionId, secondsSinceEpoch, city, fare)); PlanNode distinctAggregation = buildPlan(planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(justScan).singleGroupingSet(variable("regionid")))); testPQL( planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(distinctAggregation).globalGrouping().addAggregation(variable("count_regionid"), getRowExpression("count(regionid)", defaultSessionHolder))), "SELECT DISTINCTCOUNT(regionId) FROM realtimeOnly"); }
Source:
public boolean equals(Object obj) { if (!(obj instanceof Sample)) { return false; } Sample other = (Sample) obj; boolean timestampEquals = true; if ((timestamp != null && other.timestamp == null) || (timestamp == null && other.timestamp != null)) { timestampEquals = false; } if (timestamp != null && other.timestamp != null) { timestampEquals = timestamp.equals(other.timestamp); } return other.name.equals(name) && other.labelNames.equals(labelNames) && other.labelValues.equals(labelValues) && other.value == value && timestampEquals; }

Target:
public boolean equals(Object obj) { if (!(obj instanceof Sample)) { return false; } Sample other = (Sample) obj; return other.name.equals(name) && other.labelNames.equals(labelNames) && other.labelValues.equals(labelValues) && other.value == value && ((timestampMs == null && other.timestampMs == null) || (other.timestampMs != null) && (other.timestampMs.equals(timestampMs))); }
Source:
public void updateCacheWithHostNames() { JGitFileSystemsCache fc = fsManager.getFsCache(); List<JGitFileSystem> jGitFileSystems = fc.getFileSystems().stream() .map(fsName -> ((JGitFileSystemProxy) fsManager.get(fsName)).getRealJGitFileSystem()).collect(Collectors.toList()); for (JGitFileSystem fs : jGitFileSystems) { JGitFileSystemImpl fsImpl = (JGitFileSystemImpl) fs; fs.setPublicURI(fullHostNames); fsManager.replaceFSCacheEntry(fs.getName(), fsImpl); } }

Target:
public void updateCacheWithHostNames() { JGitFileSystemsCache fc = fsManager.getFsCache(); fc.getFileSystems() .stream() .map(fsName -> ((JGitFileSystemProxy) fsManager.get(fsName)).getRealJGitFileSystem()) .forEach(fs -> { JGitFileSystemImpl fsImpl = (JGitFileSystemImpl) fs; fs.setPublicURI(fullHostNames); fsManager.updateFSCacheEntry(fs.getName(), fsImpl); }); }
Source:
public static void createAndStart(String keyfile, char[] passphrase, int port, SocialNetwork social, MutablePointers mutable, Args args) { try { String hostname = args.getArg("domain", "localhost"); System.out.println("Starting social network server listening on: " + hostname+":"+port +" proxying to "+social); InetSocketAddress address = new InetSocketAddress(hostname, port); HttpSocialNetworkServer server = new HttpSocialNetworkServer(social, mutable, address); server.start(); } catch (Exception e) { e.printStackTrace(); System.out.println("Couldn't start Corenode server!"); } }

Target:
public static void createAndStart(String keyfile, char[] passphrase, int port, SocialNetwork social, MutablePointers mutable, Args args) { try { String hostname = args.getArg("domain", "localhost"); System.out.println("Starting social network server listening on: " + hostname+":"+port +" proxying to "+social); InetSocketAddress address = new InetSocketAddress(hostname, port); HttpSocialNetworkServer server = new HttpSocialNetworkServer(social, mutable, address); server.start(); } catch (Exception e) { e.printStackTrace(); System.out.println("Couldn't start Social Network server!"); } }
Source:
private void freeLockForValidationPassedCommands() { for (CommandBase<?> command : getCommands()) { if (command.getReturnValue().isValid()) { command.freeLock(); } } }

Target:
private void freeLockForValidationPassedCommands() { getCommands().stream().filter(command->command.getReturnValue().isValid()).forEach(command->command.freeLock()); }
Source:
public void setUp() throws Exception { Resource instanceResource = new Resource( 1.0, ByteAmount.fromGigabytes(3), ByteAmount.fromGigabytes(1)); Resource requiredResource = new Resource( 5.0, ByteAmount.fromGigabytes(11), ByteAmount.fromGigabytes(5)); Set<InstancePlan> instancesOne = new HashSet<>(); instancesOne.add(new InstancePlan( new InstanceId("exclaim1", 1, 0), instanceResource)); instancesOne.add(new InstancePlan( new InstanceId("exclaim1", 3, 0), instanceResource)); instancesOne.add(new InstancePlan( new InstanceId("word", 5, 0), instanceResource)); containerOnePlan = new ContainerPlan(1, instancesOne, requiredResource); Set<InstancePlan> instancesTwo = new HashSet<>(); instancesTwo.add(new InstancePlan( new InstanceId("exclaim1", 4, 0), instanceResource)); instancesTwo.add(new InstancePlan( new InstanceId("exclaim1", 2, 0), instanceResource)); instancesTwo.add(new InstancePlan( new InstanceId("word", 6, 0), instanceResource)); containerTwoPlan = new ContainerPlan(2, instancesTwo, requiredResource); Set<ContainerPlan> containerPlans = new HashSet<>(); containerPlans.add(containerOnePlan); containerPlans.add(containerTwoPlan); plan = new PackingPlan("A", containerPlans); }

Target:
public void setUp() throws Exception { final String COMPONENT_A = "exclaim1"; final String COMPONENT_B = "word"; ContainerPlan containerPlanA = PackingTestUtils.testContainerPlan( 1, new Pair<>(COMPONENT_A, 1), new Pair<>(COMPONENT_A, 3), new Pair<>(COMPONENT_B, 5)); ContainerPlan containerPlanB = PackingTestUtils.testContainerPlan( 2, new Pair<>(COMPONENT_A, 2), new Pair<>(COMPONENT_A, 4), new Pair<>(COMPONENT_B, 6)); Set<ContainerPlan> containerPlans = new HashSet<>(); containerPlans.add(containerPlanA); containerPlans.add(containerPlanB); plan = new PackingPlan("A", containerPlans); }
Source:
public Observable<String> searchCategories(String filter, int itemLimit, int offset) { return responseToCategoryName(CategoryInterface.searchCategories(filter.toLowerCase(), itemLimit, offset)); }

Target:
public Observable<String> searchCategories(String filter, int itemLimit, int offset) { return responseToCategoryName(CategoryInterface.searchCategories(filter, itemLimit, offset)); }
Source:
public LongSumAggregatorFactory( @JsonProperty("name") String name, @JsonProperty("fieldName") final String fieldName ) { Preconditions.checkNotNull(name, "Must have a valid, nonl null aggregator name"); Preconditions.checkNotNull(fieldName, "Must have a valid, non null fieldName"); this.name = name; this.fieldName = fieldName; }

Target:
public LongSumAggregatorFactory( @JsonProperty("name") String name, @JsonProperty("fieldName") final String fieldName ) { Preconditions.checkNotNull(name, "Must have a valid, non-null aggregator name"); Preconditions.checkNotNull(fieldName, "Must have a valid, non-null fieldName"); this.name = name; this.fieldName = fieldName; }
Source:
public void putRecord(Data key, Record record) { markRecordStoreExpirable(record.getTtl()); storage.put(key, record); mutationObserver.onPutRecord(key, record); updateStatsOnPut(record.getHits()); }

Target:
public void putRecord(Data key, Record record) { markRecordStoreExpirable(record.getTtl()); storage.put(key, record); mutationObserver.onReplicationPutRecord(key, record); updateStatsOnPut(record.getHits()); }
Source:
public List<RemoteSiteConfiguration> getRemoteSites() { List<RemoteSiteConfiguration> list = new ArrayList<>(); for (ValueDependency<RemoteSiteConfiguration> site : this.sites) { RemoteSiteConfiguration value = site.getValue(); list.add(value); } return list; }

Target:
public List<RemoteSiteConfiguration> getRemoteSites() { List<RemoteSiteConfiguration> list = new ArrayList<>(this.sites.size()); for (ValueDependency<RemoteSiteConfiguration> site : this.sites) { RemoteSiteConfiguration value = site.getValue(); list.add(value); } return list; }
Source:
public void testGetIntentContainsSkipCacheAndClaimsForBrokerActivity() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); sThreadExecutor.execute(new Runnable() { @Override public void run() { final String claimsChallenge = "testClaims"; final AuthenticationRequest authRequest = createAuthenticationRequest("<LINK_0>", "resource", "client", "redirect", "loginhint", PromptBehavior.Auto, "", UUID.randomUUID(), false); authRequest.setClaimsChallenge(claimsChallenge); final Context context = getMockContext(); final BrokerProxy brokerProxy = new BrokerProxy(context); final BrokerEvent brokerEvent = new BrokerEvent(EventStrings.BROKER_REQUEST_SILENT); Telemetry.getInstance().flush("1234"); brokerEvent.setRequestId("1234"); Telemetry.getInstance().startEvent(brokerEvent.getTelemetryRequestId(), EventStrings.BROKER_REQUEST_INTERACTIVE); try { final Intent intent = brokerProxy.getIntentForBrokerActivity(authRequest, brokerEvent); assertTrue(Boolean.toString(true).equals(intent.getStringExtra(AuthenticationConstants.Broker.BROKER_SKIP_CACHE))); assertTrue(claimsChallenge.equals(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_CLAIMS))); } catch (final AuthenticationException exc) { fail("Exception ia not expected."); } verifyBrokerEventList(brokerEvent); latch.countDown(); } }); latch.await(); }

Target:
public void testGetIntentContainsSkipCacheAndClaimsForBrokerActivity() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); sThreadExecutor.execute(new Runnable() { @Override public void run() { final String claimsChallenge = "testClaims"; final AuthenticationRequest authRequest = createAuthenticationRequest("<LINK_0>", "resource", "client", "redirect", "loginhint", PromptBehavior.Auto, "", UUID.randomUUID(), false); authRequest.setClaimsChallenge(claimsChallenge); final Context context = getMockContext(); final BrokerProxy brokerProxy = new BrokerProxy(context); final BrokerEvent brokerEvent = new BrokerEvent(EventStrings.BROKER_REQUEST_SILENT); Telemetry.getInstance().flush("1234"); brokerEvent.setRequestId("1234"); Telemetry.getInstance().startEvent(brokerEvent.getTelemetryRequestId(), EventStrings.BROKER_REQUEST_INTERACTIVE); try { final Intent intent = brokerProxy.getIntentForBrokerActivity(authRequest, brokerEvent); assertTrue(Boolean.toString(true).equals(intent.getStringExtra(AuthenticationConstants.Broker.BROKER_SKIP_CACHE))); assertTrue(claimsChallenge.equals(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_CLAIMS))); } catch (final AuthenticationException exc) { fail("Exception is not expected."); } verifyBrokerEventList(brokerEvent); latch.countDown(); } }); latch.await(); }
Source:
return (Response) reply; } }; public static Supplier<String> DEFAULT_CORRELATION_ID_GENERATOR = new IncrementingCorrelationIdGenerator(""); private final Function<Object, Response> _replyHandler; private final Map<String, BlockingCell<Object>> _continuationMap = new HashMap<String, BlockingCell<Object>>(); private final Supplier<String> _correlationIdGenerator; private DefaultConsumer _consumer; public RpcClient(RpcClientParams params) throws IOException { _channel = params.getChannel(); _exchange = params.getExchange(); _routingKey = params.getRoutingKey(); _replyTo = params.getReplyTo(); if (params.getTimeout() < NO_TIMEOUT) { throw new IllegalArgumentException("Timeout argument must be NO_TIMEOUT(-1) or non-negative."); } _timeout = params.getTimeout(); _useMandatory = params.shouldUseMandatory(); _replyHandler = params.getReplyHandler(); _correlationIdGenerator = params.getCorrelationIdGenerator(); _consumer = setupConsumer(); if (_useMandatory) { this._channel.addReturnListener(returnMessage -> { synchronized (_continuationMap) { String replyId = returnMessage.getProperties().getCorrelationId(); BlockingCell<Object> blocker = _continuationMap.remove(replyId); if (blocker == null) { LOGGER.warn("No outstanding request for correlation ID {}", replyId); } else { blocker.set(new UnroutableRpcRequestException(returnMessage)); } } }); } }

Target:
return (Response) reply; } }; private final Function<Object, Response> _replyHandler; private final Map<String, BlockingCell<Object>> _continuationMap = new HashMap<String, BlockingCell<Object>>(); private final Supplier<String> _correlationIdGenerator; private DefaultConsumer _consumer; public RpcClient(RpcClientParams params) throws IOException { _channel = params.getChannel(); _exchange = params.getExchange(); _routingKey = params.getRoutingKey(); _replyTo = params.getReplyTo(); if (params.getTimeout() < NO_TIMEOUT) { throw new IllegalArgumentException("Timeout argument must be NO_TIMEOUT(-1) or non-negative."); } _timeout = params.getTimeout(); _useMandatory = params.shouldUseMandatory(); _replyHandler = params.getReplyHandler(); _correlationIdGenerator = params.getCorrelationIdGenerator(); _consumer = setupConsumer(); if (_useMandatory) { this._channel.addReturnListener(returnMessage -> { synchronized (_continuationMap) { String replyId = returnMessage.getProperties().getCorrelationId(); BlockingCell<Object> blocker = _continuationMap.remove(replyId); if (blocker == null) { LOGGER.warn("No outstanding request for correlation ID {}", replyId); } else { blocker.set(new UnroutableRpcRequestException(returnMessage)); } } }); } }
Source:
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) { long totalHits = response.getHits().getTotalHits(); float maxScore = response.getHits().getMaxScore(); List<T> results = new ArrayList<>(); for (SearchHit hit : response.getHits()) { if (hit != null) { T result = mapSearchHit(hit, clazz); setPersistentEntityId(result, hit.getId(), clazz); setPersistentEntityVersion(result, hit.getVersion(), clazz); setPersistentEntityScore(result, hit.getScore(), clazz); populateScriptFields(result, hit); results.add(result); } } return new AggregatedPageImpl<T>(results, pageable, totalHits, response.getAggregations(), response.getScrollId(), maxScore); }

Target:
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) { long totalHits = SearchHitsUtil.getTotalCount(response.getHits()); float maxScore = response.getHits().getMaxScore(); List<T> results = new ArrayList<>(); for (SearchHit hit : response.getHits()) { if (hit != null) { T result = mapSearchHit(hit, clazz); setPersistentEntityId(result, hit.getId(), clazz); setPersistentEntityVersion(result, hit.getVersion(), clazz); setPersistentEntityScore(result, hit.getScore(), clazz); populateScriptFields(result, hit); results.add(result); } } return new AggregatedPageImpl<T>(results, pageable, totalHits, response.getAggregations(), response.getScrollId(), maxScore); }
Source:
public Coin parse(String str) throws NumberFormatException { checkArgument(str.length() > 0); char first = str.charAt(0); if (first == negativeSign || first == positiveSign) str = str.substring(1); String numbers; String decimals; int decimalMarkIndex = str.indexOf(decimalMark); if (decimalMarkIndex != -1) { numbers = str.substring(0, decimalMarkIndex); decimals = (str + "00000000").substring(decimalMarkIndex + 1); if (decimals.indexOf(decimalMark) != -1) throw new NumberFormatException("more than one decimal mark"); } else { numbers = str; decimals = "00000000"; } String satoshis = numbers + decimals.substring(0, 8 - shift); for (char c : satoshis.toCharArray()) if (!Character.isDigit(c)) throw new NumberFormatException("illegal character: " + c); Coin coin = Coin.valueOf(Long.parseLong(satoshis)); if (first == negativeSign) coin = coin.negate(); return coin; }

Target:
public Coin parse(String str) throws NumberFormatException { checkState(DECIMALS_PADDING.length() >= Coin.NUM_COIN_DECIMALS); if (str.isEmpty()) throw new NumberFormatException("empty string"); char first = str.charAt(0); if (first == negativeSign || first == positiveSign) str = str.substring(1); String numbers; String decimals; int decimalMarkIndex = str.indexOf(decimalMark); if (decimalMarkIndex != -1) { numbers = str.substring(0, decimalMarkIndex); decimals = (str + DECIMALS_PADDING).substring(decimalMarkIndex + 1); if (decimals.indexOf(decimalMark) != -1) throw new NumberFormatException("more than one decimal mark"); } else { numbers = str; decimals = DECIMALS_PADDING; } String satoshis = numbers + decimals.substring(0, Coin.NUM_COIN_DECIMALS - shift); for (char c : satoshis.toCharArray()) if (!Character.isDigit(c)) throw new NumberFormatException("illegal character: " + c); Coin coin = Coin.valueOf(Long.parseLong(satoshis)); if (first == negativeSign) coin = coin.negate(); return coin; }
Source:
public void cleaningCompensationDataAfterSuccess() { log.debug("Command successfully executed, releasing macs: {}" + macsToReleaseOnCommit); macsToReleaseOnCommit.forEach(macPool::freeMac); this.macsToReleaseOnCommit.clear(); }

Target:
public void cleaningCompensationDataAfterSuccess() { log.debug("Command successfully executed, releasing macs: {}" + macsToReleaseOnCommit); macsToReleaseOnCommit.forEach(macPool::freeMac); }
Source:
private void mapProject(final IProject source, final IProjectDescription description, final IProgressMonitor monitor, IPath gitDir) throws CoreException, TeamException { IProject destination = source.getWorkspace().getRoot() .getProject(description.getName()); RepositoryMapping repositoryMapping = RepositoryMapping.create(destination, gitDir.toFile()); SubMonitor subMonitor = SubMonitor.convert(monitor, 50); if (repositoryMapping != null) { GitProjectData projectData = new GitProjectData(destination); projectData.setRepositoryMappings(Arrays.asList(repositoryMapping)); projectData.store(); GitProjectData.add(destination, projectData); RepositoryProvider.map(destination, GitProvider.class.getName()); destination.refreshLocal(IResource.DEPTH_INFINITE, subMonitor.newChild(50)); } }

Target:
private void mapProject(final IProject source, final IProjectDescription description, final IProgressMonitor monitor, IPath gitDir) throws CoreException, TeamException { IProject destination = source.getWorkspace().getRoot() .getProject(description.getName()); RepositoryMapping repositoryMapping = RepositoryMapping.create(destination, gitDir.toFile()); if (repositoryMapping != null) { GitProjectData projectData = new GitProjectData(destination); projectData.setRepositoryMappings(Arrays.asList(repositoryMapping)); projectData.store(); GitProjectData.add(destination, projectData); RepositoryProvider.map(destination, GitProvider.class.getName()); destination.refreshLocal(IResource.DEPTH_INFINITE, monitor); } }
Source:
private AttributeMapping(String searchDn, boolean recursiveSearch, String filter, String ldapName, String name, String rdn, int recursiveDepth) { this.searchDn = searchDn; this.recursiveSearch = recursiveSearch; this.filter = filter; this.ldapName = ldapName; this.name = name; this.rdn = rdn; this.recursiveDepth = recursiveDepth; }

Target:
AttributeMapping(String searchDn, boolean recursiveSearch, String filter, String ldapName, String name, String rdn, int recursiveDepth) { this.searchDn = searchDn; this.recursiveSearch = recursiveSearch; this.filter = filter; this.ldapName = ldapName; this.name = name; this.rdn = rdn; this.recursiveDepth = recursiveDepth; }
Source:
public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout gd= new GridLayout(); gd.numColumns= 2; composite.setLayout(gd); Label label= new Label(composite, SWT.LEFT); label.setText(fNameLabel); label.setLayoutData(new GridData()); fTextControl= new Text(composite, SWT.SINGLE | SWT.BORDER); fTextControl.setText(fProjectName); fTextControl.setSelection(fProjectName.length()); fTextControl.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (!fTextControl.isDisposed()) { validateText(fTextControl.getText()); } } }); fTextControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fTextControl.setFocus(); setControl(composite); Dialog.applyDialogFont(composite); validateText(fProjectName); }

Target:
public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout gd= new GridLayout(); gd.numColumns= 2; composite.setLayout(gd); Label label= new Label(composite, SWT.LEFT); label.setText(fNameLabel); label.setLayoutData(new GridData()); fTextControl= new Text(composite, SWT.SINGLE | SWT.BORDER); fTextControl.setText(fProjectName); fTextControl.setSelection(fProjectName.length()); fTextControl.addModifyListener(e -> { if (!fTextControl.isDisposed()) { validateText(fTextControl.getText()); } }); fTextControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fTextControl.setFocus(); setControl(composite); Dialog.applyDialogFont(composite); validateText(fProjectName); }
Source:
private void addAuthorizationForUser(String userName, String resourceId, String action, short allow, boolean updateCache) throws UserStoreException { authorizationCache.clearCacheByTenant(this.tenantId); Connection dbConnection = null; PreparedStatement prepStmt = null; try { dbConnection = getDBConnection(); int permissionId = this.getPermissionId(dbConnection, resourceId, action); if (permissionId == -1) { this.addPermissionId(dbConnection, resourceId, action); permissionId = this.getPermissionId(dbConnection, resourceId, action); } DatabaseUtil.updateDatabase(dbConnection, DBConstants.DELETE_USER_PERMISSION_SQL, userName, resourceId, action, tenantId, tenantId); DatabaseUtil.updateDatabase(dbConnection, DBConstants.ADD_USER_PERMISSION_SQL, permissionId, userName, allow, tenantId); if(updateCache){ if (allow == UserCoreConstants.ALLOW) { permissionTree.authorizeUserInTree(userName, resourceId, action, true); } else { permissionTree.denyUserInTree(userName, resourceId, action, true); authorizationCache.clearCacheEntry(cacheIdentifier, tenantId, userName, resourceId, action); } } dbConnection.commit(); } catch (Exception e) { try { if (dbConnection != null) { dbConnection.rollback(); } } catch (SQLException e1) { throw new UserStoreException("Error in connection rollback " + e1.getMessage(), e1); } log.error("Error! " + e.getMessage(), e); throw new UserStoreException("Error! " + e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, prepStmt); } }

Target:
private void addAuthorizationForUser(String userName, String resourceId, String action, short allow, boolean updateCache) throws UserStoreException { authorizationCache.clearCacheByTenant(this.tenantId); Connection dbConnection = null; PreparedStatement prepStmt = null; try { dbConnection = getDBConnection(); int permissionId = this.getPermissionId(dbConnection, resourceId, action); if (permissionId == -1) { this.addPermissionId(dbConnection, resourceId, action); permissionId = this.getPermissionId(dbConnection, resourceId, action); } DatabaseUtil.updateDatabase(dbConnection, DBConstants.DELETE_USER_PERMISSION_SQL, userName, resourceId, action, tenantId, tenantId); DatabaseUtil.updateDatabase(dbConnection, DBConstants.ADD_USER_PERMISSION_SQL, permissionId, userName, allow, tenantId); if(updateCache){ if (allow == UserCoreConstants.ALLOW) { permissionTree.authorizeUserInTree(userName, resourceId, action, true); } else { permissionTree.denyUserInTree(userName, resourceId, action, true); authorizationCache.clearCacheEntry(cacheIdentifier, tenantId, userName, resourceId, action); } } dbConnection.commit(); } catch (Exception e) { try { if (dbConnection != null) { dbConnection.rollback(); } } catch (SQLException e1) { throw new UserStoreException("Error in connection rollback ", e1); } log.error("Error! " + e.getMessage(), e); throw new UserStoreException("Error! " + e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, prepStmt); } }