auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void checkFind() { projectExplorer.waitItem(PROJECT_NAME_2); projectExplorer.openItemByPath( PROJECT_NAME_2 + "/src/main/java/org/eclipse/qa/examples/AppController.java"); editor.clickOnItemInContextMenu(FIND); editor.waitContextMenuIsNotPresent(); findText.waitFindTextMainFormIsOpen(); findText.typeTextIntoFindField("class"); findText.waitTextIntoFindField("class"); loader.waitOnClosed(); findText.waitPathIntoRootField("/" + PROJECT_NAME_2 + "/src/main/java/org/eclipse/qa/examples"); findText.clickOnSearchButtonMainForm(); findText.waitFindInfoPanelIsOpen(); findText.waitExpectedTextInFindInfoPanel("AppController.java"); }

Target:
public void checkFind() { projectExplorer.waitItem(PROJECT_NAME_2); projectExplorer.openItemByPath( PROJECT_NAME_2 + "/src/main/java/org/eclipse/qa/examples/AppController.java"); editor.openContextMenuInEditor(); editor.clickOnItemInContextMenu(FIND); editor.waitContextMenuIsNotPresent(); findText.waitFindTextMainFormIsOpen(); findText.typeTextIntoFindField("class"); findText.waitTextIntoFindField("class"); loader.waitOnClosed(); findText.waitPathIntoRootField("/" + PROJECT_NAME_2 + "/src/main/java/org/eclipse/qa/examples"); findText.clickOnSearchButtonMainForm(); findText.waitFindInfoPanelIsOpen(); findText.waitExpectedTextInFindInfoPanel("AppController.java"); }
Source:
public void appendNewLine(String content) { waitForElementByElement(sourceModeTextArea); sourceModeTextArea.sendKeys(Keys.ENTER); sourceModeTextArea.sendKeys(content); PageObjectLogging.log("appendNewLine", "text "+content+" added to the source mode in new line", true); }

Target:
private void appendNewLine(String content) { waitForElementByElement(sourceModeTextArea); sourceModeTextArea.sendKeys(Keys.ENTER); sourceModeTextArea.sendKeys(content); PageObjectLogging.log("appendNewLine", "text "+content+" added to the source mode in new line", true); }
Source:
public void createNetworkInterfaceCard() { final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup); final NetworkInterfaceCardProperties networkInterfaceCardProperties = NetworkInterfaceCardProperties.create(null, null, null, Arrays.asList(IpConfiguration.create("myipconfig", null, null, null, IpConfigurationProperties.create(null, null, "Dynamic", IdReference.create(subnetID), null)) ) ); final Map<String, String> tags = ImmutableMap.of("jclouds", "livetest"); NetworkInterfaceCard nic = nicApi.createOrUpdate(NETWORKINTERFACECARD_NAME, LOCATION, networkInterfaceCardProperties, tags); assertEquals(nic.name(), NETWORKINTERFACECARD_NAME); assertEquals(nic.location(), LOCATION); assertTrue(nic.properties().ipConfigurations().size() > 0); assertEquals(nic.properties().ipConfigurations().get(0).name(), "myipconfig"); assertEquals(nic.properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(), "Dynamic"); assertEquals(nic.properties().ipConfigurations().get(0).properties().subnet().id(), subnetID); assertEquals(nic.tags().get("jclouds"), "livetest"); }

Target:
public void createNetworkInterfaceCard() { final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup); final NetworkInterfaceCardProperties networkInterfaceCardProperties = NetworkInterfaceCardProperties.builder().ipConfigurations( Arrays.asList(IpConfiguration.builder() .name("myipconfig") .properties(IpConfigurationProperties.builder() .privateIPAllocationMethod("Dynamic") .subnet(IdReference.create(subnetID)).build() ).build() )).build(); final Map<String, String> tags = ImmutableMap.of("jclouds", "livetest"); NetworkInterfaceCard nic = nicApi.createOrUpdate(NETWORKINTERFACECARD_NAME, LOCATION, networkInterfaceCardProperties, tags); assertEquals(nic.name(), NETWORKINTERFACECARD_NAME); assertEquals(nic.location(), LOCATION); assertTrue(nic.properties().ipConfigurations().size() > 0); assertEquals(nic.properties().ipConfigurations().get(0).name(), "myipconfig"); assertEquals(nic.properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(), "Dynamic"); assertEquals(nic.properties().ipConfigurations().get(0).properties().subnet().id(), subnetID); assertEquals(nic.tags().get("jclouds"), "livetest"); }
Source:
public boolean equals (Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj instanceof AtomicTransaction) { try { AtomicTransaction tx = (AtomicTransaction) obj; ControlWrapper txControl = tx._theAction; if ((_theAction == null) && (txControl == null)) { return true; } else if ((_theAction != null) && (txControl==null)) { return false; } else { return _theAction.equals(txControl); } } catch (Exception e) { } } return false; }

Target:
public boolean equals (Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj instanceof AtomicTransaction) { try { AtomicTransaction tx = (AtomicTransaction) obj; ControlWrapper txControl = tx._theAction; if ((_theAction == null) && (txControl == null)) { return true; } else if (_theAction == null) { return false; } else { return _theAction.equals(txControl); } } catch (Exception e) { } } return false; }
Source:
public void getFileName_ReturnsFileNameForSVG() { Embedding embedding = new Embedding("image/svg+xml", "some data", null); String fileName = embedding.getFileName(); assertThat(fileName).isEqualTo("embedding_-642587818.svg"); }

Target:
public void getFileName_ReturnsFileNameForSVG() { Embedding embedding = new Embedding("image/svg+xml", "some data"); String fileName = embedding.getFileName(); assertThat(fileName).isEqualTo("embedding_-642587818.svg"); }
Source:
public Properties getPropertiesForAnnotation(TestPropertyOverride annotation) { Properties properties = new Properties(); if (annotation == null) { return properties; } for (String fileName : annotation.propertyFiles()) { try { InputStream propFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName); if(propFileStream != null) { properties.load(propFileStream); } else { throw new FileNotFoundException(fileName); } properties.load(propFileStream); } catch (IOException e) { throw new TestConfigException("Failed to load property file from classpath", e); } } for (String override : annotation.value()) { String[] parts = override.split("=", 2); if (parts.length < 2) { throw new TestConfigException("Error parsing TestPropertyOverride for: " + annotation.value() + " Please ensure you are specifying overrides in the form \"key=value\""); } properties.put(parts[0], parts[1]); } return properties; }

Target:
public Properties getPropertiesForAnnotation(TestPropertyOverride annotation) { Properties properties = new Properties(); if (annotation == null) { return properties; } for (String fileName : annotation.propertyFiles()) { try { InputStream propFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName); if(propFileStream != null) { properties.load(propFileStream); } else { throw new FileNotFoundException(fileName); } } catch (IOException e) { throw new TestConfigException("Failed to load property file from classpath", e); } } for (String override : annotation.value()) { String[] parts = override.split("=", 2); if (parts.length < 2) { throw new TestConfigException("Error parsing TestPropertyOverride for: " + annotation.value() + " Please ensure you are specifying overrides in the form \"key=value\""); } properties.put(parts[0], parts[1]); } return properties; }
Source:
public void stop() { running = false; }

Target:
public void stop() { running = false; executorService.shutdown(); }
Source:
public void generateReport_OnInvalidPath_ThrowsException() { setUpWithJson(SAMPLE_JSON); page = new FeaturesOverviewPage(reportResult, configuration) { @Override public String getWebPage() { return StringUtils.EMPTY; } }; thrown.expect(ValidationException.class); Deencapsulation.invoke(page, "generatePage"); }

Target:
public void generateReport_OnInvalidPath_ThrowsException() { page = new FeaturesOverviewPage(reportResult, configuration) { @Override public String getWebPage() { return StringUtils.EMPTY; } }; thrown.expect(ValidationException.class); Deencapsulation.invoke(page, "generatePage"); }
Source:
private void createCommentAnnotations(IDocument document, AnnotationModelEvent event, IComment comment) { int startLine = 0; int endLine = 0; for (ILocation location : comment.getLocations()) { if (location instanceof ILineLocation) { ILineLocation lineLocation = (ILineLocation) location; try { startLine = lineLocation.getRangeMin(); endLine = lineLocation.getRangeMax(); int offset = 0; int length = 0; if (startLine != 0) { offset = document.getLineOffset(startLine - 1); if (endLine == 0) { endLine = startLine; } length = Math.max(document.getLineOffset(endLine - 1) - offset, 0); } length = Math.max(1, length); CommentAnnotation ca = new CommentAnnotation(offset, length, comment); if (!annotations.contains(ca)) { annotations.add(ca); event.annotationAdded(ca); } } catch (BadLocationException e) { StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, "Unable to add annotation.", e)); } } } }

Target:
private void createCommentAnnotations(IDocument document, AnnotationModelEvent event, IComment comment) { int startLine = 0; int endLine = 0; for (ILocation location : comment.getLocations()) { if (location instanceof ILineLocation) { ILineLocation lineLocation = (ILineLocation) location; try { startLine = lineLocation.getRangeMin(); endLine = lineLocation.getRangeMax(); int offset = 0; int length = 0; if (startLine != 0) { offset = document.getLineOffset(startLine - 1); if (endLine == 0) { endLine = startLine; } length = Math.max(document.getLineOffset(endLine - 1) - offset, 0); } length = Math.max(1, length); CommentAnnotation ca = new CommentAnnotation(offset, length, comment); if (annotations.add(ca)) { event.annotationAdded(ca); } } catch (BadLocationException e) { StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, "Unable to add annotation.", e)); } } } }
Source:
public Optional<PlanNodeStatsEstimate> doCalculate(RowNumberNode node, StatsProvider statsProvider, Lookup lookup, Session session, TypeProvider types) { PlanNodeStatsEstimate sourceStats = statsProvider.getStats(node.getSource()); if (sourceStats.isOutputRowCountUnknown()) { return Optional.of(PlanNodeStatsEstimate.unknown()); } double partitionCount = 1; for (Symbol groupBySymbol : node.getPartitionBy()) { SymbolStatsEstimate symbolStatistics = sourceStats.getSymbolStatistics(groupBySymbol); int nullRow = (symbolStatistics.getNullsFraction() == 0.0) ? 0 : 1; partitionCount *= symbolStatistics.getDistinctValuesCount() + nullRow; } partitionCount = min(sourceStats.getOutputRowCount(), partitionCount); if (isNaN(partitionCount)) { return Optional.of(PlanNodeStatsEstimate.unknown()); } double sourceRowsCount = sourceStats.getOutputRowCount(); double rowsPerPartition = sourceRowsCount / partitionCount; if (node.getMaxRowCountPerPartition().isPresent()) { rowsPerPartition = min(rowsPerPartition, node.getMaxRowCountPerPartition().get()); } double outputRowsCount = partitionCount * rowsPerPartition; return Optional.of(PlanNodeStatsEstimate.buildFrom(sourceStats) .setOutputRowCount(outputRowsCount) .addSymbolStatistics(node.getRowNumberSymbol(), SymbolStatsEstimate.builder() .setLowValue(0) .setHighValue(rowsPerPartition) .setDistinctValuesCount(rowsPerPartition) .setNullsFraction(0.0) .setAverageRowSize(BIGINT.getFixedSize()) .build()) .build()); }

Target:
public Optional<PlanNodeStatsEstimate> doCalculate(RowNumberNode node, StatsProvider statsProvider, Lookup lookup, Session session, TypeProvider types) { PlanNodeStatsEstimate sourceStats = statsProvider.getStats(node.getSource()); if (sourceStats.isOutputRowCountUnknown()) { return Optional.empty(); } double sourceRowsCount = sourceStats.getOutputRowCount(); double partitionCount = 1; for (Symbol groupBySymbol : node.getPartitionBy()) { SymbolStatsEstimate symbolStatistics = sourceStats.getSymbolStatistics(groupBySymbol); int nullRow = (symbolStatistics.getNullsFraction() == 0.0) ? 0 : 1; partitionCount *= symbolStatistics.getDistinctValuesCount() + nullRow; } partitionCount = min(sourceRowsCount, partitionCount); if (isNaN(partitionCount)) { return Optional.empty(); } double rowsPerPartition = sourceRowsCount / partitionCount; if (node.getMaxRowCountPerPartition().isPresent()) { rowsPerPartition = min(rowsPerPartition, node.getMaxRowCountPerPartition().get()); } double outputRowsCount = sourceRowsCount; if (node.getMaxRowCountPerPartition().isPresent()) { outputRowsCount = partitionCount * rowsPerPartition; } return Optional.of(PlanNodeStatsEstimate.buildFrom(sourceStats) .setOutputRowCount(outputRowsCount) .addSymbolStatistics(node.getRowNumberSymbol(), SymbolStatsEstimate.builder() .setLowValue(1) .setDistinctValuesCount(rowsPerPartition) .setNullsFraction(0.0) .setAverageRowSize(BIGINT.getFixedSize()) .build()) .build()); }
Source:
public Host addCertificateInfo(Host host) { VdcQueryReturnValue getVdsCertificateSubjectResult = runQuery(VdcQueryType.GetVdsCertificateSubjectByVdsId, new GetVdsByVdsIdParameters(asGuid(host.getId()))); if (getVdsCertificateSubjectResult != null && getVdsCertificateSubjectResult.getSucceeded() && getVdsCertificateSubjectResult.getReturnValue() != null) { String subject = getVdsCertificateSubjectResult.getReturnValue().toString(); if (subject != null){ host.setCertificate(new Certificate()); host.getCertificate().setSubject(subject); host.getCertificate().setOrganization(subject.split(",")[0].replace("O=", "")); } } else { LOG.error("Could not fetch certificate info for host " + host.getId()); } return host; }

Target:
public Host addCertificateInfo(Host host) { VdcQueryReturnValue result = runQuery(VdcQueryType.GetVdsCertificateSubjectByVdsId, new GetVdsByVdsIdParameters(asGuid(host.getId()))); if (result != null && result.getSucceeded() && result.getReturnValue() != null) { String subject = result.getReturnValue().toString(); if (subject != null){ host.setCertificate(new Certificate()); host.getCertificate().setSubject(subject); host.getCertificate().setOrganization(subject.split(",")[0].replace("O=", "")); } } else { LOG.error("Could not fetch certificate info for host " + host.getId()); } return host; }
Source:
public void testSubquerySimplification() throws Exception { Client client = getClient(); String sql; client.callProcedure("@AdHoc", "insert into R5 values (1,2,3)"); client.callProcedure("@AdHoc", "insert into R5 values (4,5,6)"); sql = "select * from (select C as D, D from R5) T;"; validateTableOfLongs(client, sql, new long[][] {{2, 3}, {5,6}}); sql = "select * from (select A as C, C as D, D from R5) T where C = 1;"; validateTableOfLongs(client, sql, new long[][] {{1, 2, 3}}); sql = "select * from (select A + C + D ACD from R5) T where ACD = 6;"; validateTableOfLongs(client, sql, new long[][] {{6}}); }

Target:
public void testSubquerySimplification() throws Exception { Client client = getClient(); String sql; client.callProcedure("@AdHoc", "insert into R5 values (1,2,3)"); client.callProcedure("@AdHoc", "insert into R5 values (4,5,6)"); sql = "select * from (select C as D, D from R5) T;"; validateTableOfLongs(client, sql, new long[][] {{2, 3}, {5,6}}); sql = "select * from (select A as C, C as D, D from R5) T where C = 1;"; validateTableOfLongs(client, sql, new long[][] {{1, 2, 3}}); sql = "select a from (select * from (select d as a, c, a as d from R5) T1) T2;"; validateTableOfLongs(client, sql, new long[][] {{3}, {6}}); sql = "select * from (select A + C + D ACD from R5) T where ACD = 6;"; validateTableOfLongs(client, sql, new long[][] {{6}}); sql = "select * from (select A + C + D ACD, A*C*D ACD from R5) T;"; validateTableOfLongs(client, sql, new long[][] {{6, 6}, {15, 120}}); sql = "select * from (select * from (select * from R5) T1) T2;"; validateTableOfLongs(client, sql, new long[][] {{1,2,3}, {4,5,6}}); sql = "select MAX(C), D from (select A C, C D from R5) T1 GROUP BY D HAVING MAX(C) > 1;"; validateTableOfLongs(client, sql, new long[][] {{4,5}}); }
Source:
private void failBootstrapLoad(WarehouseInstance.Tuple tuple, int failAfterNumTables) throws Throwable { BehaviourInjection<CallerArguments, Boolean> callerVerifier = new BehaviourInjection<CallerArguments, Boolean>() { int cntTables = 0; @Nullable @Override public Boolean apply(@Nullable CallerArguments args) { cntTables++; if (args.dbName.equalsIgnoreCase(replicatedDbName) && cntTables > failAfterNumTables) { injectionPathCalled = true; LOG.warn("Verifier - DB : " + args.dbName + " TABLE : " + args.tblName); return false; } return true; } }; InjectableBehaviourObjectStore.setAlterTableModifier(callerVerifier); try { replica.loadFailure(replicatedDbName, tuple.dumpLocation); callerVerifier.assertInjectionsPerformed(true, false); } finally { InjectableBehaviourObjectStore.resetAlterTableModifier(); } }

Target:
private void failBootstrapLoad(WarehouseInstance.Tuple tuple, int failAfterNumTables) throws Throwable { BehaviourInjection<CallerArguments, Boolean> callerVerifier = new BehaviourInjection<CallerArguments, Boolean>() { int cntTables = 0; String prevTable = null; @Nullable @Override public Boolean apply(@Nullable CallerArguments args) { if (prevTable == null || !prevTable.equalsIgnoreCase(args.tblName)) { cntTables++; } prevTable = args.tblName; if (args.dbName.equalsIgnoreCase(replicatedDbName) && cntTables > failAfterNumTables) { injectionPathCalled = true; LOG.warn("Verifier - DB : " + args.dbName + " TABLE : " + args.tblName); return false; } return true; } }; InjectableBehaviourObjectStore.setAlterTableModifier(callerVerifier); try { replica.loadFailure(replicatedDbName, tuple.dumpLocation); callerVerifier.assertInjectionsPerformed(true, false); } finally { InjectableBehaviourObjectStore.resetAlterTableModifier(); } }
Source:
protected int doWork() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsReadable(SEQUENCE_DICTIONARY); IOUtil.assertFileIsReadable(CHAIN); IOUtil.assertFileIsWritable(OUTPUT); final LiftOver liftOver = new LiftOver(CHAIN); liftOver.setLiftOverMinMatch(MIN_LIFTOVER_PCT); final IntervalList fromIntervals = IntervalList.fromFile(INPUT); final SAMFileHeader toHeader = SamReaderFactory.makeDefault().open(SEQUENCE_DICTIONARY).getFileHeader(); liftOver.validateToSequences(toHeader.getSequenceDictionary()); final IntervalList toIntervals = new IntervalList(toHeader); boolean anyFailed = false; for (final Interval fromInterval : fromIntervals) { final Interval toInterval = liftOver.liftOver(fromInterval); if (toInterval != null) { toIntervals.add(toInterval); } else { anyFailed = true; LOG.warn("Liftover failed for ", fromInterval, "(len ", fromInterval.length(), ")"); final List<LiftOver.PartialLiftover> partials = liftOver.diagnosticLiftover(fromInterval); for (final LiftOver.PartialLiftover partial : partials) { LOG.info(partial); } } } toIntervals.sorted(); toIntervals.write(OUTPUT); return anyFailed ? 1 : 0; }

Target:
protected int doWork() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsReadable(SEQUENCE_DICTIONARY); IOUtil.assertFileIsReadable(CHAIN); IOUtil.assertFileIsWritable(OUTPUT); final LiftOver liftOver = new LiftOver(CHAIN); liftOver.setLiftOverMinMatch(MIN_LIFTOVER_PCT); final IntervalList fromIntervals = IntervalList.fromFile(INPUT); final SAMFileHeader toHeader = SamReaderFactory.makeDefault().getFileHeader(SEQUENCE_DICTIONARY); liftOver.validateToSequences(toHeader.getSequenceDictionary()); final IntervalList toIntervals = new IntervalList(toHeader); boolean anyFailed = false; for (final Interval fromInterval : fromIntervals) { final Interval toInterval = liftOver.liftOver(fromInterval); if (toInterval != null) { toIntervals.add(toInterval); } else { anyFailed = true; LOG.warn("Liftover failed for ", fromInterval, "(len ", fromInterval.length(), ")"); final List<LiftOver.PartialLiftover> partials = liftOver.diagnosticLiftover(fromInterval); for (final LiftOver.PartialLiftover partial : partials) { LOG.info(partial); } } } toIntervals.sorted(); toIntervals.write(OUTPUT); return anyFailed ? 1 : 0; }
Source:
private Pair<Double, PointSensitivityBuilder> compositionFactorAndSensitivityNonCutoff() { if (nextFixing.isBefore(lastFixingNonCutoff)) { LocalDate startDate = index.calculateEffectiveFromFixing(nextFixing); LocalDate endDate = index.calculateMaturityFromEffective(index .calculateEffectiveFromFixing(lastFixingNonCutoff)); double accrualFactor = index.getDayCount().yearFraction(startDate, endDate); double rate = provider.overnightIndexRatePeriod(index, startDate, endDate); PointSensitivityBuilder rateSensitivity = provider.overnightIndexRatePeriodSensitivity(index, startDate, endDate); rateSensitivity = rateSensitivity.multipliedBy(accrualFactor); return Pair.of(1.0d + accrualFactor * rate, rateSensitivity); } return Pair.of(1.0d, PointSensitivityBuilder.none()); }

Target:
private ObjectDoublePair<PointSensitivityBuilder> compositionFactorAndSensitivityNonCutoff() { if (nextFixing.isBefore(lastFixingNonCutoff)) { LocalDate startDate = index.calculateEffectiveFromFixing(nextFixing); LocalDate endDate = index.calculateMaturityFromEffective( index.calculateEffectiveFromFixing(lastFixingNonCutoff)); double accrualFactor = index.getDayCount().yearFraction(startDate, endDate); double rate = provider.overnightIndexRatePeriod(index, startDate, endDate); PointSensitivityBuilder rateSensitivity = provider.overnightIndexRatePeriodSensitivity(index, startDate, endDate); rateSensitivity = rateSensitivity.multipliedBy(accrualFactor); return ObjectDoublePair.of(rateSensitivity, 1.0d + accrualFactor * rate); } return ObjectDoublePair.of(PointSensitivityBuilder.none(), 1.0d); }
Source:
protected void run() throws Exception { if (all) { Map<String, Ref> allRefs = db.getRefDatabase().getRefs(ALL); for (final Ref r : allRefs.values()) { ObjectId objectId = r.getObjectId(); outw.println(objectId != null ? objectId.name() : r.getName()); } } else { if (verify && commits.size() > 1) { throw new CmdLineException(CLIText.get().needSingleRevision); } for (final ObjectId o : commits) { outw.println(o.name()); } } }

Target:
protected void run() throws Exception { if (all) { Map<String, Ref> allRefs = db.getRefDatabase().getRefs(ALL); for (final Ref r : allRefs.values()) { ObjectId objectId = r.getObjectId(); assert objectId != null; outw.println(objectId.name()); } } else { if (verify && commits.size() > 1) { throw new CmdLineException(CLIText.get().needSingleRevision); } for (final ObjectId o : commits) { outw.println(o.name()); } } }
Source:
public Config createConfig(Map<String, Object> configInput) throws IOException { return loader.loadString(mapper.writeValueAsString(configInput)).toConfig(configFactory); }

Target:
public Config createConfig(Map<String, Object> configInput) throws IOException { return configFactory.create(configInput); }
Source:
protected void updateCpuPinningVisibility() { if (getModel().getIsAutoAssign().getEntity() == null) { return; } if (getModel().getSelectedCluster() != null) { boolean isLocalSD = getModel().getSelectedDataCenter() != null && getModel().getSelectedDataCenter().isLocal(); boolean hasCpuPinning = Boolean.FALSE.equals(getModel().getIsAutoAssign().getEntity()) || isLocalSD; getModel().getCpuPinning().setIsChangeable(hasCpuPinning); if (!hasCpuPinning) { getModel().getCpuPinning().setChangeProhibitionReason(constants.cpuPinningUnavailable()); } getModel().getCpuPinning().setIsChangeable(hasCpuPinning); } }

Target:
protected void updateCpuPinningVisibility() { if (getModel().getIsAutoAssign().getEntity() == null) { return; } if (getModel().getSelectedCluster() != null) { boolean isLocalSD = getModel().getSelectedDataCenter() != null && getModel().getSelectedDataCenter().isLocal(); boolean hasCpuPinning = Boolean.FALSE.equals(getModel().getIsAutoAssign().getEntity()) || isLocalSD; getModel().getCpuPinning().setIsChangeable(hasCpuPinning); if (!hasCpuPinning) { getModel().getCpuPinning().setChangeProhibitionReason(constants.cpuPinningUnavailable()); } } }
Source:
public void deleteIdentifier(DvObject dvObject) throws Exception { logger.log(Level.FINE,"deleteIdentifier"); String identifier = getIdentifier(dvObject); Map<String, String> doiMetadata = new HashMap<>(); try { doiMetadata = doiDataCiteRegisterService.getMetadata(identifier); } catch (Exception e) { logger.log(Level.WARNING, "deleteIdentifier: get matadata failed. " + e.getMessage(), e); } String idStatus = doiMetadata.get("_status"); if ( idStatus != null ) { switch ( idStatus ) { case RESERVED: case DRAFT: logger.log(Level.INFO, "Delete status is reserved.."); try { doiDataCiteRegisterService.deleteIdentifier(identifier); deleteDraftIdentifier(dvObject); } catch (Exception e) { logger.log(Level.WARNING, "delete failed: " + e.getMessage(), e); } break; case PUBLIC: case FINDABLE: Map<String, String> metadata = addDOIMetadataForDestroyedDataset(dvObject); metadata.put("_status", "registered"); metadata.put("_target", getTargetUrl(dvObject)); doiDataCiteRegisterService.deactivateIdentifier(identifier, metadata, dvObject); break; } } }

Target:
public void deleteIdentifier(DvObject dvObject) throws IOException, HttpException { logger.log(Level.FINE,"deleteIdentifier"); String identifier = getIdentifier(dvObject); String idStatus = DRAFT; if(dvObject.isReleased()) { idStatus = PUBLIC; } if ( idStatus != null ) { switch ( idStatus ) { case RESERVED: case DRAFT: logger.log(Level.INFO, "Delete status is reserved.."); doiDataCiteRegisterService.deleteIdentifier(identifier); deleteDraftIdentifier(dvObject); break; case PUBLIC: case FINDABLE: Map<String, String> metadata = addDOIMetadataForDestroyedDataset(dvObject); metadata.put("_status", "registered"); metadata.put("_target", getTargetUrl(dvObject)); doiDataCiteRegisterService.deactivateIdentifier(identifier, metadata, dvObject); break; } } }
Source:
public void testCleanup() throws Exception { addDatasetInstance(NamespaceId.DEFAULT.toId(), PartitionedFileSet.class.getName(), "pfs", PartitionedFileSetProperties.builder() .setPartitioning(Partitioning.builder().addLongField("snapshot").build()) .setInputFormat(AvroKeyInputFormat.class) .setOutputFormat(AvroKeyOutputFormat.class) .build()); PartitionedFileSet partitionedFileSet = (PartitionedFileSet) getDataset("pfs").get(); PartitionKey key = PartitionKey.builder().addLongField("snapshot", System.currentTimeMillis() - 1000 * 60).build(); PartitionOutput partition = partitionedFileSet.getPartitionOutput(key); partition.addPartition(); SnapshotFileSet snapshotFileSet = new SnapshotFileSet(partitionedFileSet); snapshotFileSet.deleteMatchingPartitionsByTime(System.currentTimeMillis()); Assert.assertNull(partitionedFileSet.getPartition(key)); }

Target:
public void testCleanup() throws Exception { addDatasetInstance(NamespaceId.DEFAULT.toId(), PartitionedFileSet.class.getName(), "pfs", PartitionedFileSetProperties.builder() .setPartitioning(Partitioning.builder().addLongField(SnapshotFileSet.SNAPSHOT_FIELD).build()) .setInputFormat(AvroKeyInputFormat.class) .setOutputFormat(AvroKeyOutputFormat.class) .build()); PartitionedFileSet partitionedFileSet = (PartitionedFileSet) getDataset("pfs").get(); PartitionKey deletedPartitionKey = PartitionKey.builder().addLongField(SnapshotFileSet.SNAPSHOT_FIELD, System.currentTimeMillis() - (1000 * 60)).build(); PartitionOutput partitionToDelete = partitionedFileSet.getPartitionOutput(deletedPartitionKey); partitionToDelete.addPartition(); PartitionKey persistentPartitionKey = PartitionKey.builder().addLongField(SnapshotFileSet.SNAPSHOT_FIELD, System.currentTimeMillis() - (1000 * 20)).build(); PartitionOutput partitionToKeep = partitionedFileSet.getPartitionOutput(persistentPartitionKey); partitionToKeep.addPartition(); SnapshotFileSet snapshotFileSet = new SnapshotFileSet(partitionedFileSet); snapshotFileSet.deleteMatchingPartitionsByTime(System.currentTimeMillis() - (1000 * 30)); Assert.assertNull(partitionedFileSet.getPartition(deletedPartitionKey)); Assert.assertNotNull(partitionedFileSet.getPartition(persistentPartitionKey)); }
Source:
public static PlayQueue autoQueueOf(@NonNull final StreamInfo info, @NonNull final List<PlayQueueItem> existingItems) { final Set<String> urls = new HashSet<>(existingItems.size()); for (final PlayQueueItem item : existingItems) { urls.add(item.getUrl()); } final List<InfoItem> relatedItems = info.getRelatedStreams(); if (relatedItems == null) { return null; } if (relatedItems.get(0) != null && relatedItems.get(0) instanceof StreamInfoItem && !urls.contains(relatedItems.get(0).getUrl())) { return getAutoQueuedSinglePlayQueue((StreamInfoItem) relatedItems.get(0)); } final List<StreamInfoItem> autoQueueItems = new ArrayList<>(); for (final InfoItem item : info.getRelatedStreams()) { if (item instanceof StreamInfoItem && !urls.contains(item.getUrl())) { autoQueueItems.add((StreamInfoItem) item); } } Collections.shuffle(autoQueueItems); return autoQueueItems.isEmpty() ? null : getAutoQueuedSinglePlayQueue(autoQueueItems.get(0)); }

Target:
public static PlayQueue autoQueueOf(@NonNull final StreamInfo info, @NonNull final List<PlayQueueItem> existingItems) { final Set<String> urls = new HashSet<>(existingItems.size()); for (final PlayQueueItem item : existingItems) { urls.add(item.getUrl()); } final List<InfoItem> relatedItems = info.getRelatedStreams(); if (relatedItems == null) { return null; } if (relatedItems.get(0) != null && relatedItems.get(0) instanceof StreamInfoItem && !urls.contains(relatedItems.get(0).getUrl())) { return getAutoQueuedSinglePlayQueue((StreamInfoItem) relatedItems.get(0)); } final List<StreamInfoItem> autoQueueItems = new ArrayList<>(); for (final InfoItem item : relatedItems) { if (item instanceof StreamInfoItem && !urls.contains(item.getUrl())) { autoQueueItems.add((StreamInfoItem) item); } } Collections.shuffle(autoQueueItems); return autoQueueItems.isEmpty() ? null : getAutoQueuedSinglePlayQueue(autoQueueItems.get(0)); }
Source:
public MessageQueue queue() { return MessageQueue.CertificationSuccess_PushMessage; }

Target:
public MessageQueue queue() { return MessageQueue.RegisterBankAccount_PushMessage; }
Source:
public void testValidateNullGermplasmId() { this.errors = new MapBindingResult(new HashMap<String, String>(), LotDto.class.getName()); final Integer germplasmId = null; this.lotGeneratorInputDto.setGid(germplasmId); this.lotGeneratorInputDto.setLocationId(6000); this.lotGeneratorInputDto.setGenerateStock(false); this.lotGeneratorInputDto.setScaleId(8264); this.lotGeneratorInputDto.setStockId("ABCD"); this.lotGeneratorInputDto.setComments("Comments"); final VariableFilter variableFilter = new VariableFilter(); variableFilter.addPropertyId(TermId.INVENTORY_AMOUNT_PROPERTY.getId()); this.germplasmValidator.validateGermplasmId(this.errors, germplasmId); Assert.assertTrue(this.errors.getAllErrors().size() == 1); final ObjectError objectError = this.errors.getAllErrors().get(0); assertThat(Arrays.asList(objectError.getCodes()), CoreMatchers.hasItem("germplasm.required")); }

Target:
public void testValidateNullGermplasmId() { this.errors = new MapBindingResult(new HashMap<String, String>(), LotDto.class.getName()); final Integer germplasmId = null; this.lotGeneratorInputDto.setGid(germplasmId); this.lotGeneratorInputDto.setLocationId(LOCATION_ID); this.lotGeneratorInputDto.setGenerateStock(false); this.lotGeneratorInputDto.setScaleId(SCALE_ID); this.lotGeneratorInputDto.setStockId(STOCK_ID); this.lotGeneratorInputDto.setComments(COMMENTS); final VariableFilter variableFilter = new VariableFilter(); variableFilter.addPropertyId(TermId.INVENTORY_AMOUNT_PROPERTY.getId()); this.germplasmValidator.validateGermplasmId(this.errors, germplasmId); Assert.assertEquals(this.errors.getAllErrors().size(), 1); final ObjectError objectError = this.errors.getAllErrors().get(0); assertThat(Arrays.asList(objectError.getCodes()), CoreMatchers.hasItem("germplasm.required")); }
Source:
private static List<Class<? extends Monitor>> getMonitorsFromNames(List<String> monitorNames) { List<Class<? extends Monitor>> monitors = Lists.newArrayList(); if (monitorNames == null) { return monitors; } try { for (String monitorName : monitorNames) { String effectiveMonitorName = monitorName.replace(OLD_METAMX_PACKAGE_NAME, NEW_DRUID_PACKAGE_NAME); Class<? extends Monitor> monitorClass = (Class<? extends Monitor>) Class.forName(effectiveMonitorName); monitors.add(monitorClass); } return monitors; } catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe); } }

Target:
private static List<Class<? extends Monitor>> getMonitorsFromNames(List<String> monitorNames) { List<Class<? extends Monitor>> monitors = Lists.newArrayList(); if (monitorNames == null) { return monitors; } try { for (String monitorName : monitorNames) { String effectiveMonitorName = monitorName.replace(OLD_METAMX_PACKAGE_NAME, NEW_DRUID_PACKAGE_NAME); if (!effectiveMonitorName.equals(monitorName)) { log.warn( "Deprecated Monitor class name [%s] found, please use package %s instead of %s", monitorName, NEW_DRUID_PACKAGE_NAME, OLD_METAMX_PACKAGE_NAME ); } Class<? extends Monitor> monitorClass = (Class<? extends Monitor>) Class.forName(effectiveMonitorName); monitors.add(monitorClass); } return monitors; } catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe); } }
Source:
public ChannelSetBuilder(Type type, Optional<Integer> hashChannel, int expectedPositions, OperatorContext operatorContext, JoinCompiler joinCompiler) { List<Type> types = ImmutableList.of(type); this.hash = createGroupByHash(operatorContext.getSession(), types, HASH_CHANNELS, hashChannel, expectedPositions, joinCompiler); this.operatorContext = operatorContext; this.nullBlockPage = new Page(type.createBlockBuilder(new BlockBuilderStatus(), 1, UNKNOWN.getFixedSize()).appendNull().build()); this.localMemoryContext = operatorContext.localUserMemoryContext(); }

Target:
public ChannelSetBuilder(Type type, Optional<Integer> hashChannel, int expectedPositions, OperatorContext operatorContext, JoinCompiler joinCompiler) { List<Type> types = ImmutableList.of(type); this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); this.hash = createGroupByHash(operatorContext.getSession(), types, HASH_CHANNELS, hashChannel, expectedPositions, joinCompiler); this.nullBlockPage = new Page(type.createBlockBuilder(new BlockBuilderStatus(), 1, UNKNOWN.getFixedSize()).appendNull().build()); this.localMemoryContext = operatorContext.localUserMemoryContext(); }
Source:
public void testInnerSuperCallEs2015Out() { setLanguageOut(LanguageMode.ECMASCRIPT_2015); test( lines( "class A {", " m() {", " return this;", " }", "}", "class X extends A {", " async m() {", " return super.m();", " }", "}"), lines( "class A {", " m() {", " return this;", " }", "}", "class X extends A {", " m() {", " const $jscomp$async$this = this;", " const $jscomp$async$super$get$m =", " () => Object.getPrototypeOf(this.constructor).prototype.m;", " return $jscomp.asyncExecutePromiseGeneratorFunction(", " function* () {", " return $jscomp$async$super$get$m().call($jscomp$async$this);", " });", " }", "}")); }

Target:
public void testInnerSuperCallEs2015Out() { setLanguageOut(LanguageMode.ECMASCRIPT_2015); test( lines( "class A {", " m() {", " return this;", " }", "}", "class X extends A {", " async m() {", " return super.m();", " }", "}"), lines( "class A {", " m() {", " return this;", " }", "}", "class X extends A {", " m() {", " const $jscomp$async$this = this;", " const $jscomp$async$super$get$m =", " () => Object.getPrototypeOf(Object.getPrototypeOf(this)).m;", " return $jscomp.asyncExecutePromiseGeneratorFunction(", " function* () {", " return $jscomp$async$super$get$m().call($jscomp$async$this);", " });", " }", "}")); }
Source:
protected void handleGroupedCounterAspect(ITmfEvent event, ITmfStateSystemBuilder ss, CounterAspect aspect, int rootQuark) { int quark = rootQuark; for (Class<? extends ITmfEventAspect<?>> groupClass : aspect.getGroups()) { ITmfEventAspect<?> parentAspect = fAspectImpls.get(groupClass); if (parentAspect != null) { quark = ss.getQuarkRelativeAndAdd(quark, parentAspect.getName()); quark = ss.getQuarkRelativeAndAdd(quark, String.valueOf(parentAspect.resolve(event))); } } handleCounterAspect(event, ss, aspect, quark); }

Target:
protected void handleGroupedCounterAspect(ITmfEvent event, ITmfStateSystemBuilder ss, CounterAspect aspect, int rootQuark) { int quark = rootQuark; for (Class<? extends ITmfEventAspect<?>> groupClass : aspect.getGroups()) { ITmfEventAspect<?> parentAspect = fAspectImpls.get(groupClass); if (parentAspect != null) { Object parentAspectContent = parentAspect.resolve(event); if (parentAspectContent != null) { quark = ss.getQuarkRelativeAndAdd(quark, parentAspect.getName()); quark = ss.getQuarkRelativeAndAdd(quark, String.valueOf(parentAspectContent)); } else { return; } } } handleCounterAspect(event, ss, aspect, quark); }
Source:
public static void closeAll() { LOG.debug("Closing all handles"); Iterator<String> handleIds = connectionMap.keySet().iterator(); String handleId = null; while (handleIds.hasNext()) { try { handleId = handleIds.next(); close(handleId); } catch (Exception err) { LOG.error("Error closing handle ID " + handleId, err); } } }

Target:
public static void closeAll() { LOG.debug("Closing all handles"); synchronized (lock) { Iterator<Map.Entry<String, List<Connection>>> itr = connectionMap.entrySet().iterator(); Map.Entry<String, List<Connection>> connHandle = null; while (itr.hasNext()) { connHandle = itr.next(); closeConnections(connHandle.getKey(), connHandle.getValue()); itr.remove(); } } }
Source:
public void pause() { getLifeCycle().transition(LifeCycle.State.PAUSING); try { if (!mJournalApplier.isSuspended()) { suspend(); } } catch (IOException e) { LOG.error("State machine pause failed", e); throw new IllegalStateException(e); } getLifeCycle().transition(LifeCycle.State.PAUSED); }

Target:
public void pause() { getLifeCycle().transition(LifeCycle.State.PAUSING); try { if (!mJournalApplier.isSuspended()) { suspend(); } } catch (IOException e) { throw new IllegalStateException("State machine pause failed", e); } getLifeCycle().transition(LifeCycle.State.PAUSED); }
Source:
public void registerBundleService () { if(System.getProperty(WebKeys.OSGI_ENABLED)!=null){ BundleContext context = HostActivator.instance().getBundleContext(); if (null != context) { Hashtable<String, String> props = new Hashtable<String, String>(); context.registerService(WorkflowAPIOsgiService.class.getName(), this, props); } else { Logger.debug(this, "Bundle Context is null, WorkflowAPIOsgiService has been not registered"); } } }

Target:
public void registerBundleService () { if(System.getProperty(WebKeys.OSGI_ENABLED)!=null){ BundleContext context = HostActivator.instance().getBundleContext(); if (null != context) { Hashtable<String, String> props = new Hashtable<String, String>(); context.registerService(WorkflowAPIOsgiService.class.getName(), this, props); } else { Logger.error(this, "Bundle Context is null, WorkflowAPIOsgiService has been not registered"); } } }
Source:
private void writeMetricsHeader(ch.qos.logback.classic.Logger logger, RollingFileAppender appender) { LOG.debug("Start writing header to file .."); String header = new StringBuilder("Current Date").append(",") .append("Flow Name").append(",") .append("File Name").append(",") .append("Total Events Read Per File").append(",") .append("Total Events Ingested Per File").append(",") .append("Min Event Size Per File").append(",") .append("Average Event Size Per File").append(",") .append("Max Event Size Per File").append(",") .append("Min Write Latency Per Stream").append(",") .append("Average Write Latency Per Stream").append(",") .append("Max Write Latency Per Stream").append("\n").toString(); appender.doAppend(new LoggingEvent(loggerClass, logger, null, header, null, null)); LOG.debug("Successfully write header"); }

Target:
private void writeMetricsHeader(ch.qos.logback.classic.Logger logger, RollingFileAppender appender) { LOG.debug("Start writing header to file .."); String header = new StringBuilder("Current Date").append(",") .append("Flow Name").append(",") .append("File Name").append(",") .append("Total Events Read Per File").append(",") .append("Total Events Ingested Per File").append(",") .append("Min Event Size Per File").append(",") .append("Average Event Size Per File").append(",") .append("Max Event Size Per File").append(",") .append("Min Write Latency Per Stream").append(",") .append("Average Write Latency Per Stream").append(",") .append("Max Write Latency Per Stream").append("\n").toString(); appender.doAppend(new LoggingEvent(loggerClass, logger, null, header, null, null)); LOG.debug("Successfully wrote header"); }
Source:
public Response register(Action action) { validateParameters(action, "cluster.id|name"); validateVnicMappings(action); validateClusterMappings(action); validateRoleMappings(action); validateDomainMappings(action); validateAffinityGroupMappings(action); validateAffinityLabelMappings(action); validateLunMappings(action); ImportVmFromConfParameters params = new ImportVmFromConfParameters(getVnicProfileMappings(action), getReassignBadMacs(action)); ExternalRegistrationConfigurationMapper.mapFromModel(action.getRegistrationConfiguration(), params); params.setContainerId(guid); params.setStorageDomainId(parent.getStorageDomainId()); params.setClusterId(getClusterId(action)); params.setImagesExistOnTargetStorageDomain(true); if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if (action.isSetVm() && action.getVm().isSetName()) { params.getVm().setName(action.getVm().getName()); } } if (action.isSetAllowPartialImport()) { params.setAllowPartialImport(action.isAllowPartialImport()); } return doAction(ActionType.ImportVmFromConfiguration, params, action); }

Target:
public Response register(Action action) { validateParameters(action, "cluster.id|name"); if (action.isSetRegistrationConfiguration()) { validateVnicMappings(action); validateClusterMappings(action); validateRoleMappings(action); validateDomainMappings(action); validateAffinityGroupMappings(action); validateAffinityLabelMappings(action); validateLunMappings(action); } ImportVmFromConfParameters params = new ImportVmFromConfParameters(getVnicProfileMappings(action), getReassignBadMacs(action)); ExternalRegistrationConfigurationMapper.mapFromModel(action.getRegistrationConfiguration(), params); params.setContainerId(guid); params.setStorageDomainId(parent.getStorageDomainId()); params.setClusterId(getClusterId(action)); params.setImagesExistOnTargetStorageDomain(true); if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if (action.isSetVm() && action.getVm().isSetName()) { params.getVm().setName(action.getVm().getName()); } } if (action.isSetAllowPartialImport()) { params.setAllowPartialImport(action.isAllowPartialImport()); } return doAction(ActionType.ImportVmFromConfiguration, params, action); }
Source:
public Opt<Identity> enter(final String user, final String pwd) { Opt<Identity> valid = new Opt.Empty<Identity>(); if (this.users.containsKey(user) && this.users.get(user).equals(pwd)) { valid = new Opt.Single<Identity>( new Identity.Simple(PsBasic.generateIdentityUrn(user)) ); } return valid; }

Target:
public Opt<Identity> enter(final String user, final String pwd) { final Opt<Identity> valid; if (this.users.containsKey(user) && this.users.get(user).pass().equals(pwd)) { valid = new Opt.Single<Identity>( new Identity.Simple(this.users.get(user).urn()) ); } else { valid = new Opt.Empty<Identity>(); } return valid; }
Source:
protected void onMetadataChanged(@NonNull final MediaSourceTag tag) { super.onMetadataChanged(tag); boolean showKodiButton = KoreUtil.isServiceSupportedByKore(tag.getMetadata().getServiceId()) && PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(context.getString(R.string.show_play_with_kodi_key), false); kodiButton.setVisibility(showKodiButton ? View.VISIBLE : View.GONE); titleTextView.setText(tag.getMetadata().getName()); channelTextView.setText(tag.getMetadata().getUploaderName()); }

Target:
protected void onMetadataChanged(@NonNull final MediaSourceTag tag) { super.onMetadataChanged(tag); final boolean showKodiButton = KoreUtil.isServiceSupportedByKore(tag.getMetadata().getServiceId()) && PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(context.getString(R.string.show_play_with_kodi_key), false); kodiButton.setVisibility(showKodiButton ? View.VISIBLE : View.GONE); titleTextView.setText(tag.getMetadata().getName()); channelTextView.setText(tag.getMetadata().getUploaderName()); }
Source:
void submitGetBlobOperation(String blobId, FutureResult<ReadableStreamChannel> futureResult, Callback<ReadableStreamChannel> callback) { try { GetBlobOperation getBlobOperation = new GetBlobOperation(routerConfig, routerMetrics, clusterMap, responseHandler, blobId, futureResult, callback, operationCompleteCallback, readyForPollCallback, blobIdFactory, time); getOperations.add(getBlobOperation); readyForPollCallback.onPollReady(); } catch (RouterException e) { routerMetrics.getBlobErrorCount.inc(); routerMetrics.countError(e); routerMetrics.operationDequeuingRate.mark(); operationCompleteCallback.completeOperation(futureResult, callback, null, e); } }

Target:
void submitGetBlobOperation(String blobId, FutureResult<ReadableStreamChannel> futureResult, Callback<ReadableStreamChannel> callback) { try { GetBlobOperation getBlobOperation = new GetBlobOperation(routerConfig, routerMetrics, clusterMap, responseHandler, blobId, futureResult, callback, operationCompleteCallback, readyForPollCallback, blobIdFactory, time); getOperations.add(getBlobOperation); } catch (RouterException e) { routerMetrics.getBlobErrorCount.inc(); routerMetrics.countError(e); routerMetrics.operationDequeuingRate.mark(); operationCompleteCallback.completeOperation(futureResult, callback, null, e); } }
Source:
public byte[] getPublicCertificate() { return publicCertificate.getBytes(); }

Target:
public byte[] getPublicCertificate() { return publicCertificate.getBytes(StandardCharsets.UTF_8); }
Source:
private String getDomainFromDB(String userId, int tenantId) throws UserStoreException { String domainName = null; try (Connection dbConnection = getDBConnection(true); PreparedStatement preparedStatement = dbConnection.prepareStatement(GET_DOMAIN)) { preparedStatement.setString(1, userId); preparedStatement.setInt(2, tenantId); try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { domainName = resultSet.getString(DOMAIN_COLUMN_NAME); } } } catch (SQLException ex) { throw new UserStoreException("Error occurred while reading the domain name for user id from database.", ex); } return domainName; }

Target:
private String getDomainFromDB(String userId, int tenantId) throws UserStoreException { String domainName = null; try (Connection dbConnection = getDBConnection(); PreparedStatement preparedStatement = dbConnection.prepareStatement(GET_DOMAIN)) { preparedStatement.setString(1, userId); preparedStatement.setInt(2, tenantId); try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { domainName = resultSet.getString(DOMAIN_COLUMN_NAME); } } } catch (SQLException ex) { throw new UserStoreException("Error occurred while reading the domain name for user id from database.", ex); } return domainName; }