auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void forSuccessfulResponseByUrlPattern(final NetworkTrafficInterceptor trafficInterceptor, final String pattern) { changeImplicitWait(0, TimeUnit.SECONDS); try { wait.until( new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { HarEntry entry = trafficInterceptor.getMatchingEntryByUrlPatternFromHar(pattern); return entry != null && entry.getResponse().getStatus() < 400; } @Override public String toString() { return "successful response matching pattern: " + pattern; } } ); } finally { restoreDeaultImplicitWait(); } }

Target:
public void forSuccessfulResponseByUrlPattern(final NetworkTrafficInterceptor trafficInterceptor, final String pattern) { changeImplicitWait(0, TimeUnit.SECONDS); try { wait.until( new ExpectedCondition<Boolean>() { private HarEntry entry; @Override public Boolean apply(WebDriver webDriver) { entry = trafficInterceptor.getEntryByUrlPattern(pattern); return entry != null && entry.getResponse().getStatus() < 400; } @Override public String toString() { return entry == null ? String.format("sent request matching pattern: %s", pattern) : String.format("successful response (pattern: %s)", pattern); } } ); } finally { restoreDeaultImplicitWait(); } }
Source:
protected boolean checkWireTransferTabState(DisbursementVoucherDocument dvDocument) { boolean tabStatesOK = true; PaymentSourceWireTransfer dvWireTransfer = dvDocument.getWireTransfer(); if ((StringUtils.equals(KFSConstants.PaymentSourceConstants.PAYMENT_METHOD_CHECK, dvDocument.getDisbVchrPaymentMethodCode()) || StringUtils.equals( KFSConstants.PaymentSourceConstants.PAYMENT_METHOD_DRAFT, dvDocument.getDisbVchrPaymentMethodCode())) && hasWireTransferValues(dvWireTransfer)) { String questionText = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString( KFSKeyConstants.QUESTION_CLEAR_UNNEEDED_TAB); boolean clearTab = super.askOrAnalyzeYesNoQuestion( KFSConstants.DisbursementVoucherDocumentConstants.CLEAR_WIRE_TRANSFER_TAB_QUESTION_ID, questionText); if (clearTab) { clearWireTransferValues(dvWireTransfer); } else { super.event.setActionForwardName(KFSConstants.MAPPING_BASIC); tabStatesOK = false; } } return tabStatesOK; }

Target:
protected boolean checkWireTransferTabState(DisbursementVoucherDocument dvDocument) { boolean tabStatesOK = true; PaymentSourceWireTransfer dvWireTransfer = dvDocument.getWireTransfer(); if ((StringUtils.equals(KFSConstants.PaymentSourceConstants.PAYMENT_METHOD_CHECK, dvDocument.getDisbVchrPaymentMethodCode()) || StringUtils.equals( KFSConstants.PaymentSourceConstants.PAYMENT_METHOD_DRAFT, dvDocument.getDisbVchrPaymentMethodCode())) && hasWireTransferValues(dvWireTransfer)) { String questionText = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString( CUKFSKeyConstants.QUESTION_CLEAR_UNNEEDED_WIRE_TAB); boolean clearTab = super.askOrAnalyzeYesNoQuestion( KFSConstants.DisbursementVoucherDocumentConstants.CLEAR_WIRE_TRANSFER_TAB_QUESTION_ID, questionText); if (clearTab) { clearWireTransferValues(dvWireTransfer); } else { super.event.setActionForwardName(KFSConstants.MAPPING_BASIC); tabStatesOK = false; } } return tabStatesOK; }
Source:
public void testPaginationWatch() throws Exception { final String testId = UUID.randomUUID().toString(); final String basePath = "/testPaginationWatch-" + testId; createChildren(basePath, 10, 0); long minZkId = -1; final int pageSize = 3; int pageCount = 0; MyWatcher myWatcher = new MyWatcher(); while (true) { final List<PathWithStat> page = zk.getChildrenPaginated(basePath, myWatcher, pageSize, minZkId); if(page.isEmpty()) { break; } if(pageCount < 3) { String childPath = basePath + "/" + "before-pagination-" + pageCount; zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } for (PathWithStat pathWithStat : page) { final String nodePath = pathWithStat.getPath(); LOG.info("Read: " + nodePath); final Stat nodeStat = pathWithStat.getStat(); Assert.assertTrue(nodeStat.getCzxid() > minZkId); minZkId = nodeStat.getCzxid(); } pageCount += 1; } { String childPath = basePath + "/" + "after-pagination"; zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } while (true) { if(!myWatcher.watchFired) { LOG.info("Watch did not fire yet"); Thread.sleep(1000); } else { LOG.info("Watch fired"); break; } } Thread.sleep(1000); Assert.assertTrue(myWatcher.watchFired); }

Target:
public void testPaginationWatch() throws Exception { final String testId = UUID.randomUUID().toString(); final String basePath = "/testPaginationWatch-" + testId; createChildren(basePath, 10, 0); long minCzxId = -1; final int pageSize = 3; FireOnlyOnceWatcher fireOnlyOnceWatcher = new FireOnlyOnceWatcher(); RemoteIterator<PathWithStat> it = zk.getChildrenIterator(basePath, fireOnlyOnceWatcher, pageSize, minCzxId); int childrenIndex = 0; while (it.hasNext()) { ++childrenIndex; PathWithStat pathWithStat = it.next(); final String nodePath = pathWithStat.getPath(); LOG.info("Read: " + nodePath); final Stat nodeStat = pathWithStat.getStat(); Assert.assertTrue(nodeStat.getCzxid() > minCzxId); minCzxId = nodeStat.getCzxid(); if(childrenIndex < 6) { String childPath = basePath + "/" + "before-pagination-" + childrenIndex; zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if(childrenIndex % pageSize == 0) { zk.setData(basePath + "/" + pathWithStat.getPath(), new byte[3], -1); } synchronized (fireOnlyOnceWatcher) { Assert.assertEquals("Watch should not have fired yet", 0, fireOnlyOnceWatcher.watchFiredCount); } } { String childPath = basePath + "/" + "after-pagination"; zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } while (true) { synchronized (fireOnlyOnceWatcher) { if (fireOnlyOnceWatcher.watchFiredCount > 0) { Assert.assertEquals("Watch should have fired once", 1, fireOnlyOnceWatcher.watchFiredCount); break; } fireOnlyOnceWatcher.wait(1000); } } synchronized (fireOnlyOnceWatcher) { fireOnlyOnceWatcher.wait(1000); Assert.assertEquals("Watch should have fired once", 1, fireOnlyOnceWatcher.watchFiredCount); } }
Source:
default <U> Seq<U> traverse(BiFunction<K, V, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return foldLeft(Stream.empty(), (acc, entry) -> acc.append(mapper.apply(entry._1, entry._2))); }

Target:
default <U> Seq<U> traverse(BiFunction<K, V, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return foldLeft(Vector.empty(), (acc, entry) -> acc.append(mapper.apply(entry._1, entry._2))); }
Source:
public void connect(Action1<? super Subscription> connection) { boolean shouldSubscribe = false; synchronized (guard) { if (subscription != null) { connection.call(guardedSubscription); return; } else { shouldSubscribe = true; final Subject<? super T, ? extends R> subject = subjectFactory.call(); subscription = new Subscriber<T>() { @Override public void onCompleted() { subject.onCompleted(); } @Override public void onError(Throwable e) { subject.onError(e); } @Override public void onNext(T args) { subject.onNext(args); } }; guardedSubscription = Subscriptions.create(new Action0() { @Override public void call() { Subscription s; synchronized (guard) { s = subscription; subscription = null; guardedSubscription = null; connectedSubject.set(null); } if (s != null) { s.unsubscribe(); } } }); for(Subscriber<? super R> s : waitingForConnect) { subject.unsafeSubscribe(s); } waitingForConnect.clear(); connectedSubject.set(subject); } } if (shouldSubscribe) { connection.call(guardedSubscription); Subscriber<T> sub; synchronized (guard) { sub = subscription; } if (sub != null) source.subscribe(sub); } }

Target:
public void connect(Action1<? super Subscription> connection) { synchronized (guard) { if (subscription != null) { connection.call(guardedSubscription); return; } else { final Subject<? super T, ? extends R> subject = subjectFactory.call(); subscription = new Subscriber<T>() { @Override public void onCompleted() { subject.onCompleted(); } @Override public void onError(Throwable e) { subject.onError(e); } @Override public void onNext(T args) { subject.onNext(args); } }; final AtomicReference<Subscription> gs = new AtomicReference<Subscription>(); gs.set(Subscriptions.create(new Action0() { @Override public void call() { Subscription s; synchronized (guard) { if ( guardedSubscription == gs.get()) { s = subscription; subscription = null; guardedSubscription = null; connectedSubject.set(null); } else return; } if (s != null) { s.unsubscribe(); } } })); guardedSubscription = gs.get(); for(Subscriber<? super R> s : waitingForConnect) { subject.unsafeSubscribe(s); } waitingForConnect.clear(); connectedSubject.set(subject); } } connection.call(guardedSubscription); Subscriber<T> sub; synchronized (guard) { sub = subscription; } if (sub != null) source.subscribe(sub); }
Source:
public static Set<Symbol> globalSymbols(FileInput fileInput, String packageName, PythonFile pythonFile) { SymbolTableBuilder symbolTableBuilder = new SymbolTableBuilder(packageName, pythonFile); String fullyQualifiedModuleName = SymbolUtils.fullyQualifiedModuleName(packageName, pythonFile.fileName()); fileInput.accept(symbolTableBuilder); Set<Symbol> globalSymbols = new HashSet<>(); for (Symbol globalVariable : fileInput.globalVariables()) { if (globalVariable.kind() == Symbol.Kind.CLASS) { String fullyQualifiedVariableName = globalVariable.fullyQualifiedName(); if (fullyQualifiedVariableName != null && fullyQualifiedVariableName.startsWith(fullyQualifiedModuleName)) { globalSymbols.add(((ClassSymbolImpl) globalVariable).copyWithoutUsages()); } else { globalSymbols.add(((ClassSymbolImpl) globalVariable).copyWithPrefix(fullyQualifiedModuleName)); } } else if (globalVariable.kind() == Symbol.Kind.FUNCTION) { globalSymbols.add(new FunctionSymbolImpl(fullyQualifiedModuleName, globalVariable.name(), ((FunctionSymbol) globalVariable))); } else { globalSymbols.add(new SymbolImpl(globalVariable.name(), fullyQualifiedModuleName + "." + globalVariable.name())); } } return globalSymbols; }

Target:
public static Set<Symbol> globalSymbols(FileInput fileInput, String packageName, PythonFile pythonFile) { SymbolTableBuilder symbolTableBuilder = new SymbolTableBuilder(packageName, pythonFile); String fullyQualifiedModuleName = SymbolUtils.fullyQualifiedModuleName(packageName, pythonFile.fileName()); fileInput.accept(symbolTableBuilder); Set<Symbol> globalSymbols = new HashSet<>(); for (Symbol globalVariable : fileInput.globalVariables()) { String fullyQualifiedVariableName = globalVariable.fullyQualifiedName(); if (((fullyQualifiedVariableName != null) && !fullyQualifiedVariableName.startsWith(fullyQualifiedModuleName)) || globalVariable.usages().stream().anyMatch(u -> u.kind().equals(Usage.Kind.IMPORT))) { continue; } if (globalVariable.kind() == Symbol.Kind.CLASS) { globalSymbols.add(((ClassSymbolImpl) globalVariable).copyWithoutUsages()); } else if (globalVariable.kind() == Symbol.Kind.FUNCTION) { globalSymbols.add(new FunctionSymbolImpl(globalVariable.name(), ((FunctionSymbol) globalVariable))); } else { globalSymbols.add(new SymbolImpl(globalVariable.name(), fullyQualifiedModuleName + "." + globalVariable.name())); } } return globalSymbols; }
Source:
public static IBiomeBlockReplacerProvider provider() { return new IBiomeBlockReplacerProvider() { private final ResourceLocation OCEAN_BLOCK = CubicChunks.location("ocean_block"); private final ResourceLocation OCEAN_HEIGHT = CubicChunks.location("ocean_height"); @Override public IBiomeBlockReplacer create(ICubicWorld world, CubicBiomeType biome, BiomeBlockReplacerConfig conf) { IBlockState oceanBlock = Block.getBlockFromName(conf.getString(OCEAN_BLOCK)).getDefaultState(); int oceanHeight = conf.getInt(OCEAN_HEIGHT); return new OceanWaterReplacer(oceanBlock, oceanHeight); } @Override public Set<ConfigOptionInfo> getPossibleConfigOptions() { return Sets.newHashSet( new ConfigOptionInfo(OCEAN_BLOCK, Blocks.WATER.getRegistryName().toString()), new ConfigOptionInfo(OCEAN_HEIGHT, 63) ); } }; }

Target:
public static IBiomeBlockReplacerProvider provider() { return new IBiomeBlockReplacerProvider() { private final ResourceLocation OCEAN_BLOCK = CubicChunks.location("ocean_block"); private final ResourceLocation OCEAN_LEVEL = CubicChunks.location("ocean_level"); @Override public IBiomeBlockReplacer create(ICubicWorld world, CubicBiome biome, BiomeBlockReplacerConfig conf) { IBlockState oceanBlock = Block.getBlockFromName(conf.getString(OCEAN_BLOCK)).getDefaultState(); int oceanHeight = conf.getInt(OCEAN_LEVEL); return new OceanWaterReplacer(oceanBlock, oceanHeight); } @Override public Set<ConfigOptionInfo> getPossibleConfigOptions() { return Sets.newHashSet( new ConfigOptionInfo(OCEAN_BLOCK, Blocks.WATER.getRegistryName().toString()), new ConfigOptionInfo(OCEAN_LEVEL, 63) ); } }; }
Source:
public static void main(String[] args) throws Exception { if(args.length < 1) { usage(); return; } try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) { String chartTitle = modelReader.readLine(); String[] series = modelReader.readLine().split(","); List<String> listLanguages = new ArrayList<>(10); List<Double> listCountries = new ArrayList<>(10); List<Double> listSpeakers = new ArrayList<>(10); String ln; while((ln = modelReader.readLine()) != null) { String[] vals = ln.split(","); listCountries.add(Double.valueOf(vals[0])); listSpeakers.add(Double.valueOf(vals[1])); listLanguages.add(vals[2]); } String[] categories = listLanguages.toArray(new String[listLanguages.size()]); Double[] values1 = listCountries.toArray(new Double[listCountries.size()]); Double[] values2 = listSpeakers.toArray(new Double[listSpeakers.size()]); try (XWPFDocument doc = new XWPFDocument()) { XWPFChart chart = doc.createChart(5000000,5000000); setBarData(chart, chartTitle, series, categories, values1, values2); try (OutputStream out = new FileOutputStream("bar-chart-demo-output.docx")) { doc.write(out); } } catch(Exception e) { e.printStackTrace(); } } System.out.println("Done"); }

Target:
public static void main(String[] args) throws Exception { if(args.length < 1) { usage(); return; } try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) { String chartTitle = modelReader.readLine(); String[] series = modelReader.readLine().split(","); List<String> listLanguages = new ArrayList<>(10); List<Double> listCountries = new ArrayList<>(10); List<Double> listSpeakers = new ArrayList<>(10); String ln; while((ln = modelReader.readLine()) != null) { String[] vals = ln.split(","); listCountries.add(Double.valueOf(vals[0])); listSpeakers.add(Double.valueOf(vals[1])); listLanguages.add(vals[2]); } String[] categories = listLanguages.toArray(new String[listLanguages.size()]); Double[] values1 = listCountries.toArray(new Double[listCountries.size()]); Double[] values2 = listSpeakers.toArray(new Double[listSpeakers.size()]); try (XWPFDocument doc = new XWPFDocument()) { XWPFChart chart = doc.createChart(XDDFChart.DEFAULT_WIDTH, XDDFChart.DEFAULT_HEIGHT); setBarData(chart, chartTitle, series, categories, values1, values2); try (OutputStream out = new FileOutputStream("bar-chart-demo-output.docx")) { doc.write(out); } } catch(Exception e) { e.printStackTrace(); } } System.out.println("Done"); }
Source:
protected void updateValidityChecks(ActionsViewTable viewTable) { List<ScriptGeneratorAction> actions = scriptGeneratorModel.getActions(); TableItem[] items = viewTable.table().getItems(); int validityColumnIndex = viewTable.table().getColumnCount()-1; for (int i = 0; i < actions.size(); i++) { if (actions.get(i).isValid()) { items[i].setBackground(clearColor); items[i].setBackground(validityColumnIndex, validColor); } else { items[i].setBackground(invalidLightColor); items[i].setBackground(validityColumnIndex, invalidDarkColor); } } }

Target:
protected void updateValidityChecks(ActionsViewTable viewTable) { List<ScriptGeneratorAction> actions = scriptGeneratorModel.getActions(); TableItem[] items = viewTable.table().getItems(); int validityColumnIndex = viewTable.table().getColumnCount()-1; for (int i = 0; i < actions.size(); i++) { if(i < items.length) { if (!scriptGeneratorModel.languageSupported) { items[i].setBackground(lightValidityCheckErrorColor); items[i].setBackground(validityColumnIndex, darkValidityCheckErrorColor); } else if (actions.get(i).isValid()) { items[i].setBackground(clearColor); items[i].setBackground(validityColumnIndex, validColor); } else { items[i].setBackground(invalidLightColor); items[i].setBackground(validityColumnIndex, invalidDarkColor); } } else { LOG.warn("ScriptGeneratorViewModel - ActionsTable and UI Table mismatch"); } } }
Source:
public void addSpiceUsbControllers(Guid vmId, int numberOfControllers) { VmBase vmBase = getVmBase(vmId); if (vmBase.getBiosType().getChipsetType() == ChipsetType.Q35) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, createSingleUsbControllerSpecParams(Q35_MODEL), true, false); } else { for (int index = 0; index < numberOfControllers; index++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, getSpiceUsbControllerSpecParams(EHCI_MODEL, 1, index), true, false); for (int companionIndex = 1; companionIndex <= COMPANION_USB_CONTROLLERS; companionIndex++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, getSpiceUsbControllerSpecParams(UHCI_MODEL, companionIndex, index), true, false); } } } }

Target:
public void addSpiceUsbControllers(Guid vmId, int numberOfControllers) { VmBase vmBase = getVmBase(vmId); if (vmBase.getBiosType().getChipsetType() == ChipsetType.Q35) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, createSingleUsbControllerSpecParams(XHCI_MODEL), true, false); } else { for (int index = 0; index < numberOfControllers; index++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, createSpiceUsbControllerSpecParams(EHCI_MODEL, 1, index), true, false); for (int companionIndex = 1; companionIndex <= COMPANION_USB_CONTROLLERS; companionIndex++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmId), VmDeviceGeneralType.CONTROLLER, VmDeviceType.USB, createSpiceUsbControllerSpecParams(UHCI_MODEL, companionIndex, index), true, false); } } } }
Source:
public void fillMsqMaxSelectableChoices(int qnNumber, String value) { WebElement inputBox = getMsqMaxSelectableChoicesBox(qnNumber); String id = inputBox.getAttribute("id"); fillTextBox(browser.driver.findElement(By.id(id)), value); }

Target:
public void fillMsqMaxSelectableChoices(int qnNumber, String value) { WebElement inputBox = getMsqMaxSelectableChoicesBox(qnNumber); fillTextBox(inputBox, value); executeScript("$(arguments[0]).change();", inputBox); }
Source:
public static Comparator<TurboIssue> getSortComparator(IModel model, String key, boolean inverted, boolean metadataRefresh) { Comparator<TurboIssue> comparator = (a, b) -> 0; boolean isLabelGroup = false; switch (key) { case "comments": comparator = (a, b) -> a.getCommentCount() - b.getCommentCount(); break; case "repo": comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId()); break; case "updated": case "date": comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt()); break; case "nonselfupdate": if (metadataRefresh) { comparator = (a, b) -> b.getMetadata().getNonSelfUpdatedAt().compareTo(a.getMetadata().getNonSelfUpdatedAt()); } else { comparator = (a, b) -> b.getUpdatedAt().compareTo(a.getUpdatedAt()); } break; case "id": comparator = (a, b) -> a.getId() - b.getId(); break; default: isLabelGroup = true; break; } if (isLabelGroup) { return getLabelGroupComparator(model, key, inverted); } else { if (!inverted) { return comparator; } else { final Comparator<TurboIssue> finalComparator = comparator; return (a, b) -> -finalComparator.compare(a, b); } } }

Target:
public static Comparator<TurboIssue> getSortComparator(IModel model, String key, boolean inverted, boolean metadataRefresh) { Comparator<TurboIssue> comparator = (a, b) -> 0; boolean isLabelGroup = false; switch (key) { case "comments": comparator = (a, b) -> a.getCommentCount() - b.getCommentCount(); break; case "repo": comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId()); break; case "updated": case "date": comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt()); break; case "nonSelfUpdate": if (metadataRefresh) { comparator = (a, b) -> a.getMetadata().getNonSelfUpdatedAt().compareTo(b.getMetadata().getNonSelfUpdatedAt()); } else { comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt()); } break; case "id": comparator = (a, b) -> a.getId() - b.getId(); break; default: isLabelGroup = true; break; } if (isLabelGroup) { return getLabelGroupComparator(model, key, inverted); } else { if (!inverted) { return comparator; } else { final Comparator<TurboIssue> finalComparator = comparator; return (a, b) -> -finalComparator.compare(a, b); } } }
Source:
public void testCreate() throws Exception { String testUserName = "test-user"; UserDto user = new UserDto(); user.setEnabled(true); user.setUsername(testUserName); user.setPassword("test-password"); user.setSecurityTokenKey("some-security-token"); userService.save(new EncodedPasswordUser(user, passwordEncoder)); User foundEntity = userService.findByUsername(testUserName); assertThat(foundEntity).as("Unable to locate user " + testUserName + ". Save operation failed!").isNotNull(); logger.debug("Found stored user\n\t{}\n", foundEntity); assertThat(foundEntity.getUsername()).isEqualTo(testUserName); assertThat(foundEntity.getPassword()) .as("Expected a hashed password, received plain-text!") .isNotEqualTo("test-password"); assertThat(foundEntity.getPassword()).as("User contains empty password!").isNotNull(); assertThat(foundEntity.isEnabled()).isTrue(); assertThat(foundEntity.getSecurityTokenKey()).isEqualTo("some-security-token"); }

Target:
public void testCreate() throws Exception { String testUserName = "test-user"; UserDto user = new UserDto(); user.setEnabled(true); user.setUsername(testUserName); user.setPassword("test-password"); user.setSecurityTokenKey("some-security-token"); userService.save(new EncodedPasswordUser(user, passwordEncoder)); User foundEntity = userService.findByUsername(testUserName); assertThat(foundEntity).as("Unable to locate user " + testUserName + ". Save operation failed!").isNotNull(); logger.debug("Found stored user: {}", foundEntity); assertThat(foundEntity.getUsername()).isEqualTo(testUserName); assertThat(foundEntity.getPassword()) .as("Expected a hashed password, received plain-text!") .isNotEqualTo("test-password"); assertThat(foundEntity.getPassword()).as("User contains empty password!").isNotNull(); assertThat(foundEntity.isEnabled()).isTrue(); assertThat(foundEntity.getSecurityTokenKey()).isEqualTo("some-security-token"); }
Source:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf msgBuf = (ByteBuf) msg; if (msgBuf.getByte(msgBuf.readerIndex()) == 0x1) { ctx.fireChannelRead(msgBuf); return; } msgBuf.readByte(); ByteBufInputStream msgInputStream = new ByteBufInputStream(msgBuf); try { Request request = Request.parseFrom(msgInputStream); Header header = request.getHeader(); if (log.isDebugEnabled()) { log.debug("Request pi from {}", header.getType(), ctx.channel().remoteAddress()); } AbstractServer handler = handlerMap.get(header.getType()); if (handler == null) { log.warn("Received unregistered message {}, dropping", header.getType()); } else { try { handler.handleRequest(request, ctx, this); } catch(Throwable t) { log.error("channelRead: Handling failed due to {}:{}", header.getType(),t.getClass().getSimpleName(), t.getMessage(), t); } } } catch (Exception e) { log.error("Exception during read!", e); } finally { msgInputStream.close(); msgBuf.release(); } }

Target:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf msgBuf = (ByteBuf) msg; byte msgMark = msgBuf.getByte(msgBuf.readerIndex()); if (msgMark == API.LEGACY_CORFU_MSG_MARK) { ctx.fireChannelRead(msgBuf); return; } else if(msgMark != API.PROTO_CORFU_MSG_MARK) { throw new IllegalStateException("Received incorrectly marked message."); } msgBuf.readByte(); ByteBufInputStream msgInputStream = new ByteBufInputStream(msgBuf); try { Request request = Request.parseFrom(msgInputStream); Header header = request.getHeader(); if (log.isDebugEnabled()) { log.debug("channelRead: Request from {}", header.getType(), ctx.channel().remoteAddress()); } AbstractServer handler = handlerMap.get(header.getType()); if (handler == null) { log.warn("channelRead: Received unregistered request {}, dropping", header.getType()); } else { if(requestIsValid(request, ctx)) { if(log.isTraceEnabled()) { log.trace("channelRead: Request routed to {}: {}", handler.getClass().getSimpleName(), request); } try { handler.handleRequest(request, ctx, this); } catch(Throwable t) { log.error("channelRead: Handling failed due to {}:{}", header.getType(), t.getClass().getSimpleName(), t.getMessage(), t); } } } } catch (Exception e) { log.error("channelRead: Exception during read!", e); } finally { msgInputStream.close(); msgBuf.release(); } }
Source:
public void Search() { if (getEntity() != null) { AsyncDataProvider.GetVmsRunningOnOrMigratingToVds(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { @SuppressWarnings("unchecked") ArrayList<VM> list = (ArrayList<VM>) returnValue; HostVmListModel model = (HostVmListModel) target; model.setItems(list); } }), getEntity().getId()); } else { setItems(new ArrayList<VM>()); } }

Target:
public void Search() { if (getEntity() != null) { AsyncDataProvider.GetVmsRunningOnOrMigratingToVds(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { @SuppressWarnings("unchecked") final ArrayList<VM> list = (ArrayList<VM>) returnValue; final HostVmListModel model = (HostVmListModel) target; model.setItems(list); } }), getEntity().getId()); } else { setItems(new ArrayList<VM>()); } }
Source:
private Object[][] testRemoveContentsBeforeProvider() { return new Object[][] { { span(chunk(6,10), chunk(11,15)), null, span(chunk(6,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(), span(chunk(6,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(6, 0)), span(chunk(6,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(7, 0)), span(chunk(7,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(9, 0)), span(chunk(9,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(10, 0)), span(chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(11, 0)), span(chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(12, 0)), span(chunk(12,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(15, 0)), span() }, { span(chunk(6,10), chunk(11,15)), span(chunk(16, 0)), span() }, }; }

Target:
private Object[][] testRemoveContentsBeforeProvider() { return new Object[][] { { span(chunk(6,10), chunk(11,15)), null, span(chunk(6,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(), span(chunk(6,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(6,0)), span(chunk(6,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(7,0)), span(chunk(7,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(9,0)), span(chunk(9,10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(10,0)), span(chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(11,0)), span(chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(12,0)), span(chunk(12,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(15,0)), span() }, { span(chunk(6,10), chunk(11,15)), span(chunk(16,0)), span() }, { span(chunk(6,10), chunk(11,15)), span(chunk(6,10), chunk(7,16)), span(chunk(6, 10), chunk(11,15)) }, { span(chunk(6,10), chunk(11,15)), span(chunk(16,17), chunk(18,19)), span() }, }; }
Source:
public HelixVcrCluster(CloudConfig cloudConfig, ClusterMapConfig clusterMapConfig, ClusterMap clusterMap) throws Exception { if (Utils.isNullOrEmpty(cloudConfig.VCR_CLUSTER_ZK_CONNECT_STRING)) { throw new IllegalArgumentException("Missing value for " + CloudConfig.VCR_CLUSTER_ZK_CONNECT_STRING); } else if (Utils.isNullOrEmpty(cloudConfig.VCR_CLUSTER_NAME)) { throw new IllegalArgumentException("Missing value for " + CloudConfig.VCR_CLUSTER_NAME); } else if (Utils.isNullOrEmpty(cloudConfig.VCR_CLUSTER_ZK_CONNECT_STRING)) { throw new IllegalArgumentException("Missing value for " + CloudConfig.VCR_CLUSTER_ZK_CONNECT_STRING); } currentDataNode = new CloudDataNode(cloudConfig, clusterMapConfig); List<? extends PartitionId> allPartitions = clusterMap.getAllPartitionIds(null); logger.trace("All partitions from clusterMap: " + allPartitions); partitionIdMap = allPartitions.stream().collect(Collectors.toMap(PartitionId::toPathString, Function.identity())); vcrClusterName = cloudConfig.vcrClusterName; vcrInstanceName = ClusterMapUtils.getInstanceName(clusterMapConfig.clusterMapHostName, clusterMapConfig.clusterMapPort); manager = HelixManagerFactory.getZKHelixManager(vcrClusterName, vcrInstanceName, InstanceType.PARTICIPANT, cloudConfig.vcrClusterZkConnectString); manager.getStateMachineEngine() .registerStateModelFactory(LeaderStandbySMD.name, new HelixVcrStateModelFactory(this)); manager.connect(); helixAdmin = manager.getClusterManagmentTool(); metrics = new HelixVcrClusterMetrics(clusterMap.getMetricRegistry()); logger.info("HelixVcrCluster started successfully."); }

Target:
public HelixVcrCluster(CloudConfig cloudConfig, ClusterMapConfig clusterMapConfig, ClusterMap clusterMap) throws Exception { if (Utils.isNullOrEmpty(cloudConfig.VCR_CLUSTER_ZK_CONNECT_STRING)) { throw new IllegalArgumentException("Missing value for " + CloudConfig.VCR_CLUSTER_ZK_CONNECT_STRING); } else if (Utils.isNullOrEmpty(cloudConfig.VCR_CLUSTER_NAME)) { throw new IllegalArgumentException("Missing value for " + CloudConfig.VCR_CLUSTER_NAME); } currentDataNode = new CloudDataNode(cloudConfig, clusterMapConfig); List<? extends PartitionId> allPartitions = clusterMap.getAllPartitionIds(null); logger.trace("All partitions from clusterMap: {}.", allPartitions); partitionIdMap = allPartitions.stream().collect(Collectors.toMap(PartitionId::toPathString, Function.identity())); vcrClusterName = cloudConfig.vcrClusterName; vcrInstanceName = ClusterMapUtils.getInstanceName(clusterMapConfig.clusterMapHostName, clusterMapConfig.clusterMapPort); manager = HelixManagerFactory.getZKHelixManager(vcrClusterName, vcrInstanceName, InstanceType.PARTICIPANT, cloudConfig.vcrClusterZkConnectString); manager.getStateMachineEngine() .registerStateModelFactory(LeaderStandbySMD.name, new HelixVcrStateModelFactory(this)); manager.connect(); helixAdmin = manager.getClusterManagmentTool(); metrics = new HelixVcrClusterMetrics(clusterMap.getMetricRegistry()); logger.info("HelixVcrCluster started successfully."); }
Source:
public boolean upgrade() { try { String envPortalURL = environment.getProperty("portalURL", Key.MANAGEMENT_URL.defaultValue()); final Optional<Parameter> optionalParameter = parameterRepository.findById(Key.MANAGEMENT_URL.key()); if (!optionalParameter.isPresent()) { Parameter managementURLParam = new Parameter(); managementURLParam.setKey(Key.MANAGEMENT_URL.key()); managementURLParam.setValue(envPortalURL); managementURLParam.setReferenceType(ParameterReferenceType.ENVIRONMENT); managementURLParam.setReferenceId(GraviteeContext.getDefaultEnvironment()); parameterRepository.create(managementURLParam); } else if (StringUtils.isEmpty(optionalParameter.get().getValue())) { Parameter managementURLParam = optionalParameter.get(); managementURLParam.setValue(envPortalURL); parameterRepository.update(managementURLParam); } } catch (TechnicalException e) { logger.error("Error while updating 'portal.url' parameter : {}", e); } return true; }

Target:
public boolean upgrade() { try { String envPortalURL = environment.getProperty("portalURL", Key.MANAGEMENT_URL.defaultValue()); final Optional<Parameter> optionalParameter = parameterRepository.findById(Key.MANAGEMENT_URL.key()); if (!optionalParameter.isPresent()) { Parameter managementURLParam = new Parameter(); managementURLParam.setKey(Key.MANAGEMENT_URL.key()); managementURLParam.setValue(envPortalURL); managementURLParam.setReferenceType(ParameterReferenceType.ENVIRONMENT); managementURLParam.setReferenceId(GraviteeContext.getDefaultEnvironment()); parameterRepository.create(managementURLParam); } else if (StringUtils.isEmpty(optionalParameter.get().getValue())) { Parameter managementURLParam = optionalParameter.get(); managementURLParam.setValue(envPortalURL); parameterRepository.update(managementURLParam); } } catch (TechnicalException e) { logger.error("Error while updating 'management.url' parameter : {}", e); } return true; }
Source:
public double computeFor(ASTMethodOrConstructorDeclaration node, MetricVersion version) { JavaParserVisitor visitor = (CycloVersion.IGNORE_BOOLEAN_PATHS.equals(version)) ? new CycloPathUnawareOperationVisitor() : new StandardCycloVisitor(); MutableInt cyclo = (MutableInt) node.jjtAccept(visitor, new MutableInt(1)); return (double) cyclo.getValue(); }

Target:
public double computeFor(ASTMethodOrConstructorDeclaration node, MetricVersion version) { JavaParserVisitor visitor = (CycloVersion.IGNORE_BOOLEAN_PATHS == version) ? new CycloPathUnawareOperationVisitor() : new StandardCycloVisitor(); MutableInt cyclo = (MutableInt) node.jjtAccept(visitor, new MutableInt(1)); return (double) cyclo.getValue(); }
Source:
private void findByCoordsFn() { final Button latView = (Button) findViewById(R.id.buttonLatitude); final Button lonView = (Button) findViewById(R.id.buttonLongitude); final String latText = latView.getText().toString(); final String lonText = lonView.getText().toString(); if (latText == null || StringUtils.isEmpty(latText) || lonText == null || StringUtils.isEmpty(lonText)) { latView.setText(cgBase.formatLatitude(geo.latitudeNow, true)); lonView.setText(cgBase.formatLongitude(geo.longitudeNow, true)); } else { Map<String, Object> latParsed = cgBase.parseCoordinate(latText, "lat"); Map<String, Object> lonParsed = cgBase.parseCoordinate(lonText, "lat"); if (latParsed == null || latParsed.get("coordinate") == null || latParsed.get("string") == null) { showToast(res.getString(R.string.err_parse_lat)); return; } if (lonParsed == null || lonParsed.get("coordinate") == null || lonParsed.get("string") == null) { showToast(res.getString(R.string.err_parse_lon)); return; } final Intent cachesIntent = new Intent(this, cgeocaches.class); cachesIntent.putExtra("type", "coordinate"); cachesIntent.putExtra("latitude", (Double) latParsed.get("coordinate")); cachesIntent.putExtra("longitude", (Double) lonParsed.get("coordinate")); cachesIntent.putExtra("cachetype", settings.cacheType); startActivity(cachesIntent); } }

Target:
private void findByCoordsFn() { final Button latView = (Button) findViewById(R.id.buttonLatitude); final Button lonView = (Button) findViewById(R.id.buttonLongitude); final String latText = latView.getText().toString(); final String lonText = lonView.getText().toString(); if (StringUtils.isEmpty(latText) || StringUtils.isEmpty(lonText)) { latView.setText(cgBase.formatLatitude(geo.latitudeNow, true)); lonView.setText(cgBase.formatLongitude(geo.longitudeNow, true)); } else { Map<String, Object> latParsed = cgBase.parseCoordinate(latText, "lat"); Map<String, Object> lonParsed = cgBase.parseCoordinate(lonText, "lat"); if (latParsed == null || latParsed.get("coordinate") == null || latParsed.get("string") == null) { showToast(res.getString(R.string.err_parse_lat)); return; } if (lonParsed == null || lonParsed.get("coordinate") == null || lonParsed.get("string") == null) { showToast(res.getString(R.string.err_parse_lon)); return; } final Intent cachesIntent = new Intent(this, cgeocaches.class); cachesIntent.putExtra("type", "coordinate"); cachesIntent.putExtra("latitude", (Double) latParsed.get("coordinate")); cachesIntent.putExtra("longitude", (Double) lonParsed.get("coordinate")); cachesIntent.putExtra("cachetype", settings.cacheType); startActivity(cachesIntent); } }
Source:
public UsageStatisticsReportDTO generateReport() { final SystemInfoUtils sysInfoUtils = new SystemInfoUtils(); final UsageStatisticsReportDTO usageStatisticsReport = new UsageStatisticsReportDTO(); try { usageStatisticsReport.setSystemId(m_stateManager.getOrGenerateSystemId()); } catch (IOException e) { LOG.warn("An error occurred while retrieving the system id.", e); } usageStatisticsReport.setOsName(System.getProperty("os.name")); usageStatisticsReport.setOsArch(System.getProperty("os.arch")); usageStatisticsReport.setOsVersion(System.getProperty("os.version")); usageStatisticsReport.setVersion(sysInfoUtils.getVersion()); usageStatisticsReport.setPackageName(sysInfoUtils.getPackageName()); usageStatisticsReport.setNodes(m_nodeDao.countAll()); usageStatisticsReport.setIpInterfaces(m_ipInterfaceDao.countAll()); usageStatisticsReport.setSnmpInterfaces(m_snmpInterfaceDao.countAll()); usageStatisticsReport.setMonitoredServices(m_monitoredServiceDao.countAll()); usageStatisticsReport.setEvents(m_eventDao.countAll()); usageStatisticsReport.setAlarms(m_alarmDao.countAll()); usageStatisticsReport.setNodesBySysOid(m_nodeDao.getNumberOfNodesBySysOid()); return usageStatisticsReport; }

Target:
public UsageStatisticsReportDTO generateReport() { final SystemInfoUtils sysInfoUtils = new SystemInfoUtils(); final UsageStatisticsReportDTO usageStatisticsReport = new UsageStatisticsReportDTO(); try { usageStatisticsReport.setSystemId(m_stateManager.getOrGenerateSystemId()); } catch (IOException e) { LOG.warn("An error occurred while retrieving the system id. " + "The usage report will be submitted with a null system id.", e); } usageStatisticsReport.setOsName(System.getProperty("os.name")); usageStatisticsReport.setOsArch(System.getProperty("os.arch")); usageStatisticsReport.setOsVersion(System.getProperty("os.version")); usageStatisticsReport.setVersion(sysInfoUtils.getVersion()); usageStatisticsReport.setPackageName(sysInfoUtils.getPackageName()); usageStatisticsReport.setNodes(m_nodeDao.countAll()); usageStatisticsReport.setIpInterfaces(m_ipInterfaceDao.countAll()); usageStatisticsReport.setSnmpInterfaces(m_snmpInterfaceDao.countAll()); usageStatisticsReport.setMonitoredServices(m_monitoredServiceDao.countAll()); usageStatisticsReport.setEvents(m_eventDao.countAll()); usageStatisticsReport.setAlarms(m_alarmDao.countAll()); usageStatisticsReport.setNodesBySysOid(m_nodeDao.getNumberOfNodesBySysOid()); return usageStatisticsReport; }
Source:
private BaseObject findNotificationPreference(XWikiDocument xWikiDocument, NotificationPreference notificationPreference) throws NotificationException { List<BaseObject> objects = xWikiDocument.getXObjects(NOTIFICATION_PREFERENCE_CLASS); if (objects != null) { Iterator<BaseObject> it = objects.iterator(); while (it.hasNext()) { BaseObject object = it.next(); if (object != null && notificationPreference.getEventType().equals(object.getStringValue(EVENT_TYPE_FIELD)) && notificationPreference.getApplicationId().equals( object.getStringValue(APPLICATION_ID_FIELD))) { String format = object.getStringValue(FORMAT_FIELD); if ((StringUtils.isBlank(format) && notificationPreference.getFormat().equals( NotificationFormat.ALERT)) || notificationPreference.getFormat().equals(NotificationFormat.valueOf( format.toUpperCase()))) { return object; } } } } return null; }

Target:
private BaseObject findNotificationPreference(XWikiDocument xWikiDocument, NotificationPreference notificationPreference) throws NotificationException { List<BaseObject> objects = xWikiDocument.getXObjects(NOTIFICATION_PREFERENCE_CLASS); if (objects != null) { for (BaseObject object : objects) { if (object != null && notificationPreference.getEventType().equals(object.getStringValue(EVENT_TYPE_FIELD)) && notificationPreference.getApplicationId().equals( object.getStringValue(APPLICATION_ID_FIELD))) { String format = object.getStringValue(FORMAT_FIELD); if ((StringUtils.isBlank(format) && notificationPreference.getFormat().equals( NotificationFormat.ALERT)) || notificationPreference.getFormat().equals(NotificationFormat.valueOf( format.toUpperCase()))) { return object; } } } } return null; }
Source:
public boolean hasPermission(Permission permissionRequirement) { if (true) return true; return getRoles().stream() .map(Role::getPermissions) .flatMap(Collection::stream) .anyMatch(permission -> permission.implies(permissionRequirement)); }

Target:
public boolean hasPermission(Permission permissionRequirement) { return getRoles().stream() .map(Role::getPermissions) .flatMap(Collection::stream) .anyMatch(permission -> permission.implies(permissionRequirement)); }
Source:
private void setupFeedAutoSkipPreference() { findPreference("skipping").setOnPreferenceClickListener(preference -> { new FeedPreferenceSkipDialog(getContext(), feedPreferences.getFeedSkipIntro(), feedPreferences.getFeedSkipEnding()) { @Override protected void onConfirmed(String skipIntroStr, String skipEndingStr) { int skipIntro; int skipEnding; try { skipIntro = Integer.parseInt(skipIntroStr); } catch (NumberFormatException e) { skipIntro = 0; } try { skipEnding = Integer.parseInt(skipEndingStr); } catch (NumberFormatException e) { skipEnding = 0; } feedPreferences.setFeedSkipIntro(skipIntro); feedPreferences.setFeedSkipEnding(skipEnding); feed.savePreferences(); } }.show(); return false; }); }

Target:
private void setupFeedAutoSkipPreference() { findPreference(PREF_AUTO_SKIP).setOnPreferenceClickListener(preference -> { new FeedPreferenceSkipDialog(getContext(), feedPreferences.getFeedSkipIntro(), feedPreferences.getFeedSkipEnding()) { @Override protected void onConfirmed(int skipIntro, int skipEnding) { feedPreferences.setFeedSkipIntro(skipIntro); feedPreferences.setFeedSkipEnding(skipEnding); feed.savePreferences(); EventBus.getDefault().post( new SkipIntroEndingChangedEvent(feedPreferences.getFeedSkipIntro(), feedPreferences.getFeedSkipEnding(), feed.getId())); } }.show(); return false; }); }
Source:
private void testGeneralQuestionOperations() throws Exception { testCancelAddingNewQuestion(); testCancelEditQuestion(); testNewQuestionLink(); testInputValidationForQuestion(); testAddQuestionAction(); testEditQuestionLink(); testEditQuestionAction(); testCopyQuestion(); testChangeFeedbackGiver(); testChangeFeedbackRecipient(); testVisibilityOptionsCorrespondToFeedbackPath(); testVisibilityOptionsUncheckedWhenHidden(); testEditQuestionNumberAction(); testAjaxOnVisibilityMessageButton(); testDeleteQuestionAction(2); testEditThenDeleteQuestionAction(1); testEditNonExistentQuestion(); testResponseRate(); }

Target:
private void testGeneralQuestionOperations() throws Exception { testCancelAddingNewQuestion(); testCancelEditQuestion(); testNewQuestionLink(); testInputValidationForQuestion(); testAddQuestionAction(); testEditQuestionLink(); testEditQuestionAction(); testCopyQuestion(); testChangeFeedbackGiver(); testChangeFeedbackRecipient(); testVisibilityOptionsCorrespondToFeedbackPath(); testVisibilityOptionsUncheckedWhenHidden(); testEditQuestionNumberAction(); testAjaxOnVisibilityMessageButton(); testDeleteQuestionAction(2); testEditWithEmptyQuestionTextThenDeleteQuestionAction(1); testEditNonExistentQuestion(); testResponseRate(); }
Source:
public Void visitTableFinish(TableFinishNode node, IOPlanBuilder context) { WriterTarget writerTarget = node.getTarget(); if (writerTarget instanceof CreateHandle) { CreateHandle createHandle = (CreateHandle) writerTarget; context.setOutputTable(new QualifiedTablePrefix( createHandle.getHandle().getConnectorId().getCatalogName(), createHandle.getSchemaTableName().getSchemaName(), createHandle.getSchemaTableName().getTableName())); } else if (writerTarget instanceof InsertHandle) { InsertHandle insertHandle = (InsertHandle) writerTarget; context.setOutputTable(new QualifiedTablePrefix( insertHandle.getHandle().getConnectorId().getCatalogName(), insertHandle.getSchemaTableName().getSchemaName(), insertHandle.getSchemaTableName().getTableName())); } else if (writerTarget instanceof DeleteHandle) { DeleteHandle deleteHandle = (DeleteHandle) writerTarget; context.setOutputTable(new QualifiedTablePrefix( deleteHandle.getHandle().getConnectorId().getCatalogName(), deleteHandle.getSchemaTableName().getSchemaName(), deleteHandle.getSchemaTableName().getTableName())); } else if (writerTarget instanceof CreateName || writerTarget instanceof InsertReference) { throw new IllegalStateException(format("%s should not appear in final plan", writerTarget.getClass().getSimpleName())); } else { throw new IllegalStateException(format("Cannot recognize WriterTarget subclass %s", writerTarget.getClass().getSimpleName())); } node.getSources().forEach(plan -> plan.accept(this, context)); return null; }

Target:
public Void visitTableFinish(TableFinishNode node, IOPlanBuilder context) { WriterTarget writerTarget = node.getTarget(); if (writerTarget instanceof CreateHandle) { CreateHandle createHandle = (CreateHandle) writerTarget; context.setOutputTable(new CatalogSchemaTableName( createHandle.getHandle().getConnectorId().getCatalogName(), createHandle.getSchemaTableName().getSchemaName(), createHandle.getSchemaTableName().getTableName())); } else if (writerTarget instanceof InsertHandle) { InsertHandle insertHandle = (InsertHandle) writerTarget; context.setOutputTable(new CatalogSchemaTableName( insertHandle.getHandle().getConnectorId().getCatalogName(), insertHandle.getSchemaTableName().getSchemaName(), insertHandle.getSchemaTableName().getTableName())); } else if (writerTarget instanceof DeleteHandle) { DeleteHandle deleteHandle = (DeleteHandle) writerTarget; context.setOutputTable(new CatalogSchemaTableName( deleteHandle.getHandle().getConnectorId().getCatalogName(), deleteHandle.getSchemaTableName().getSchemaName(), deleteHandle.getSchemaTableName().getTableName())); } else if (writerTarget instanceof CreateName || writerTarget instanceof InsertReference) { throw new IllegalStateException(format("%s should not appear in final plan", writerTarget.getClass().getSimpleName())); } else { throw new IllegalStateException(format("Unknown WriterTarget subclass %s", writerTarget.getClass().getSimpleName())); } return processChildren(node, context); }
Source:
public static void register(ScalarFunctionModule module) { for (var timestampType : List.of(DataTypes.TIMESTAMP, DataTypes.TIMESTAMPZ)) { module.register( Signature.scalar( ArithmeticFunctions.Names.ADD, DataTypes.INTERVAL.getTypeSignature(), timestampType.getTypeSignature(), timestampType.getTypeSignature() ).withForbiddenCoercion(), args -> new IntervalTimestampArithmeticScalar( "+", ArithmeticFunctions.Names.ADD, args, args.get(1)) ); module.register( Signature.scalar( ArithmeticFunctions.Names.ADD, timestampType.getTypeSignature(), DataTypes.INTERVAL.getTypeSignature(), DataTypes.INTERVAL.getTypeSignature() ).withForbiddenCoercion(), args -> new IntervalTimestampArithmeticScalar( "+", ArithmeticFunctions.Names.ADD, args, args.get(0)) ); module.register( Signature.scalar( ArithmeticFunctions.Names.SUBTRACT, timestampType.getTypeSignature(), DataTypes.INTERVAL.getTypeSignature(), DataTypes.INTERVAL.getTypeSignature() ).withForbiddenCoercion(), args -> new IntervalTimestampArithmeticScalar( "-", ArithmeticFunctions.Names.SUBTRACT, args, args.get(0) ) ); } }

Target:
public static void register(ScalarFunctionModule module) { for (var timestampType : List.of(DataTypes.TIMESTAMP, DataTypes.TIMESTAMPZ)) { module.register( Signature.scalar( ArithmeticFunctions.Names.ADD, DataTypes.INTERVAL.getTypeSignature(), timestampType.getTypeSignature(), timestampType.getTypeSignature() ).withForbiddenCoercion(), args -> new IntervalTimestampArithmeticScalar( "+", ArithmeticFunctions.Names.ADD, args, args.get(1)) ); module.register( Signature.scalar( ArithmeticFunctions.Names.ADD, timestampType.getTypeSignature(), DataTypes.INTERVAL.getTypeSignature(), timestampType.getTypeSignature() ).withForbiddenCoercion(), args -> new IntervalTimestampArithmeticScalar( "+", ArithmeticFunctions.Names.ADD, args, args.get(0)) ); module.register( Signature.scalar( ArithmeticFunctions.Names.SUBTRACT, timestampType.getTypeSignature(), DataTypes.INTERVAL.getTypeSignature(), timestampType.getTypeSignature() ).withForbiddenCoercion(), args -> new IntervalTimestampArithmeticScalar( "-", ArithmeticFunctions.Names.SUBTRACT, args, args.get(0) ) ); } }