void callBlind(final JavaScriptCallback<Void> javaScriptCallback) { final Stopwatch timer = Stopwatch.createStarted(); final ScheduledFuture<?> future = createTimeoutHook(); JavaScript.getCurrent().addFunction(hookName, new JavaScriptFunction() { boolean done = false; private static final long serialVersionUID = 1L; @Override public void call(JsonArray arguments) { logger.debug("Handling response for " + hookName); if (!done) { done = true; javaScriptCallback.callback(null); } else { logger.warn("This appears to have been a duplicate callback, ignoring it!"); } future.cancel(false); removeHooks(hookName, errorHookName); if (timer.elapsed(TimeUnit.MILLISECONDS) > EXPECTED_RESPONSE_TIME_MS) { logger.warn(jsToExecute + "\n\nResponded after {}ms", timer.elapsed(TimeUnit.MILLISECONDS)); } } }); setupErrorHook(future); JavaScript.getCurrent().execute(wrapJSInTryCatchBlind(jsToExecute)); }
public FileExample() { setCaption("Interactive SVG"); addComponent(new MLabel( "A simple example from an svg file using Embedded component. Unlike with Image component, the SVGs JS etc are active. The example also demonstrates how to provide a trivial server side integration API for the SVG.")); Embedded svg = new Embedded(); svg.setWidth("400px"); svg.setHeight("400px"); svg.setSource(new ClassResource("/pull.svg")); // Expose a JS hook that pull.svg file calls when clicked JavaScript.getCurrent().addFunction("callMyVaadinFunction", (JsonArray arguments) -> { Notification.show("Message from SVG:" + arguments.getString(0)); }); addComponent(svg); }
@SuppressWarnings("serial") private final void registerJavaScriptFunctionsIfNeeded() { if (jsFunctionsRegistered.getAndSet(true)) { return; // already registered } final JavaScript javaScript = JavaScript.getCurrent(); javaScript.addFunction(JS_FUNC_OnSwipe, new JavaScriptFunction() { @Override public void call(final JsonArray arguments) { invokeOnSwipe(arguments); } }); }
public static void getCookieValue(String key, final Callback callback) { final String callbackid = "hybridbpmcookie"+UUID.randomUUID().toString().substring(0,8); JavaScript.getCurrent().addFunction(callbackid, new JavaScriptFunction() { @Override public void call(JsonArray arguments) { JavaScript.getCurrent().removeFunction(callbackid); if(arguments.length() == 0) { callback.onValue(null); } else { callback.onValue(arguments.getString(0)); } } }); JavaScript.getCurrent().execute(String.format( "var nameEQ = \"%2$s=\";var ca = document.cookie.split(';');for(var i=0;i < ca.length;i++) {var c = ca[i];while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) {%1$s( c.substring(nameEQ.length,c.length)); return;};} %1$s();", callbackid,key )); }
public static void detectCookieValue(String key, final Callback callback) { final String callbackid = "viritincookiecb"+UUID.randomUUID().toString().substring(0,8); JavaScript.getCurrent().addFunction(callbackid, new JavaScriptFunction() { private static final long serialVersionUID = -3426072590182105863L; @Override public void call(JsonArray arguments) { JavaScript.getCurrent().removeFunction(callbackid); if(arguments.length() == 0) { callback.onValueDetected(null); } else { callback.onValueDetected(arguments.getString(0)); } } }); JavaScript.getCurrent().execute(String.format( "var nameEQ = \"%2$s=\";var ca = document.cookie.split(';');for(var i=0;i < ca.length;i++) {var c = ca[i];while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) {%1$s( c.substring(nameEQ.length,c.length)); return;};} %1$s();", callbackid,key )); }
/** * Do on test closing * * @param event */ public void requestClose(@Observes final CloseTestEvent event) { log.debug("close requested"); if (requestBack) { log.debug("closing ProcessUI with history back"); JavaScript javaScript = ui.getPage().getJavaScript(); javaScript.execute("window.history.back();"); ui.requestClose(); } else { String path = VaadinServlet.getCurrent().getServletContext().getContextPath(); ui.getPage().setLocation(path + CLOSE_URL); // this is also possible way but not for SWT browser // Page.getCurrent().getJavaScript().execute("window.setTimeout(function(){/*window.open('','_self','');*/window.close();},10);") log.debug("closing ProcessUI"); ui.requestClose(); } }
public static void showHelpBrowserWindow(String guid) { JavaScript javaScript = MainUI.getCurrent().getPage().getJavaScript(); if (!useFirstName) { javaScript.execute(closeNativeWindow(HELP_WINDOW_NAME_1)); } else { javaScript.execute(closeNativeWindow(HELP_WINDOW_NAME_2)); } MainUI.getCurrent().getPage().open("/WebHelp/" + guid, useFirstName ? HELP_WINDOW_NAME_1 : HELP_WINDOW_NAME_2); useFirstName = !useFirstName; }
public static void setBeforePageUnloadMessage(final String message) { final JavaScript javaScript = Page.getCurrent().getJavaScript(); if (message == null || message.trim().isEmpty()) { javaScript.execute("$(window).off('beforeunload');"); } else { // TODO: escape the message javaScript.execute("$(window).on('beforeunload', function() { return \"" + message + "\"; });"); } }
public synchronized void enable(final Component component, final SwipeHandler handler) { Preconditions.checkNotNull(component, "component is null"); final String componentId = component.getId(); Preconditions.checkNotNull(componentId, "componentId is null"); final ComponentSwipe swipe = new ComponentSwipe(componentId, handler); component2swipe.put(component, swipe); componentId2swipe.put(componentId, swipe); registerJavaScriptFunctionsIfNeeded(); final JavaScript javaScript = JavaScript.getCurrent(); javaScript.execute("" + "if (!window.swipesMap) { window.swipesMap={}; }" // + "window.swipesMap['" + componentId + "'] = Swiped.init({" + "query: '#" + componentId + "'" + ", left: 300" + ", right: 300" + ", tolerance: 200" + ", onOpen: function() { " + JS_FUNC_OnSwipe + "('" + componentId + "'); }" + "});" // + "\n console.log('Enabled swiping for element: " + componentId + "');" ); }
public void destroy() { JavaScript.getCurrent().execute("window.swipesMap['" + componentId + "'].destroy(false);"); // isRemoveNode=false }
public static void setCookie(String key, String value, String path) { JavaScript.getCurrent().execute(String.format( "document.cookie = \"%s=%s; path=%s\";", key, value, path )); }
private static void addTypeStyle(final Long tagId, final String color) { final JavaScript javaScript = UI.getCurrent().getPage().getJavaScript(); UI.getCurrent() .access(() -> javaScript.execute( HawkbitCommonUtil.getScriptSMHighlightWithColor(".v-table-row-distribution-upload-type-" + tagId + "{background-color:" + color + " !important;background-image:none !important }"))); }
private void _jsSetTimeStep(TimeStep timeStep) { JavaScript.getCurrent() .execute("document.getElementById('" + LIVE_CHART_ID + "').firstElementChild.contentDocument.getElementsByClassName('stepli')[" + timeStep.ordinal() + "].click();"); }
public static void setCookie(String key, String value, LocalDateTime expirationTime) { String expires = toCookieGMTDate(expirationTime); JavaScript.getCurrent().execute(String.format( "document.cookie = \"%s=%s; Expires=%s\";", key, value, expires )); }
public static void setCookie(String key, String value, String path, LocalDateTime expirationTime) { String expires = toCookieGMTDate(expirationTime); JavaScript.getCurrent().execute(String.format( "document.cookie = \"%s=%s; path=%s\"; Expires=%s\";", key, value, path, expires )); }
void removeHooks(final String hook1, final String hook2) { final JavaScript js = JavaScript.getCurrent(); js.removeFunction(hook1); js.removeFunction(hook2); }
private void setupErrorHook(final ScheduledFuture<?> future) { trace = new JavaScriptException("Java Script Invoked From Here, JS:" + jsToExecute); JavaScript.getCurrent().addFunction(errorHookName, new JavaScriptFunction() { private static final long serialVersionUID = 1L; @Override public void call(JsonArray arguments) { try { String value = arguments.getString(0); logger.error(jsToExecute + " -> resulted in the error: " + value, trace); Exception ex = new JavaScriptException(trace.getMessage() + " , JS Cause: " + value, trace); ErrorWindow.showErrorWindow(ex); } catch (Exception e) { ErrorWindow.showErrorWindow(trace); } finally { future.cancel(false); JavaScript.getCurrent().removeFunction(hookName); JavaScript.getCurrent().removeFunction(errorHookName); } } }); }
private void ajaxRefreshInit(JavaScriptFunction intervalFn) { JavaScript.getCurrent().addFunction("Persephone.logs.refreshLogs", intervalFn); String js = String.format("Persephone.logs.refreshLogsInterval = setInterval(Persephone.logs.refreshLogs, %s);", refreshTimeout * 1000); JavaScript.getCurrent().execute(js); }
private void ajaxRefreshDestroy() { JavaScript.getCurrent().execute("clearInterval(Persephone.logs.refreshLogsInterval)"); JavaScript.getCurrent().removeFunction("Persephone.logs.refreshLogs"); }
public void open() { JavaScript.getCurrent().execute("window.swipesMap['" + componentId + "'].open();"); }
public void close() { JavaScript.getCurrent().execute("window.swipesMap['" + componentId + "'].close(); console.log('swipe.close for " + componentId + "');"); }
private void _jsSetChartDrawType(ChartDrawType chartDrawType) { JavaScript.getCurrent() .execute("document.getElementById('" + LIVE_CHART_ID + "').firstElementChild.contentDocument.getElementsByClassName('chart_drawtype')[" + chartDrawType.ordinal() + "].click();"); }
private void rememberTempAccount(String username, String password) { String storeVal = username + "$" + EnDecryptHelper.encryptText(password); String setCookieVal = String.format("var now = new Date(); now.setTime(now.getTime() + 1 * 1800 * 1000); " + "document.cookie = \"%s=%s; expires=\" + now.toUTCString() + \"; path=/\";", TEMP_ACCOUNT_COOKIE, storeVal); JavaScript.getCurrent().execute(setCookieVal); }
public void respondToExport(String callback, String response) { response = response.replaceAll("\\n", ""); System.err.println("Executing :" +callback+".run('"+response+"')"); JavaScript.eval(callback+".run('"+response+"')"); }
void call(final JavaScriptCallback<JsonArray> callback) { final Stopwatch timer = Stopwatch.createStarted(); final ScheduledFuture<?> future = createTimeoutHook(); JavaScript.getCurrent().addFunction(hookName, new JavaScriptFunction() { private static final long serialVersionUID = 1L; boolean done = false; @Override public void call(JsonArray arguments) { try { if (timer.elapsed(TimeUnit.MILLISECONDS) > EXPECTED_RESPONSE_TIME_MS) { logger.warn(jsToExecute + "\n\nResponded after {}ms", timer.elapsed(TimeUnit.MILLISECONDS)); } logger.debug("Handling response for " + hookName); if (!done) { done = true; callback.callback(arguments); } else { logger.warn("This appears to have been a duplicate callback, ignoring it!"); } } catch (Exception e) { logger.error(e, e); logger.error(trace, trace); } finally { future.cancel(false); removeHooks(hookName, errorHookName); } } }); final String wrappedJs = wrapJSInTryCatch(jsToExecute); setupErrorHook(future); JavaScript.getCurrent().execute(wrappedJs); }
private static void execute(String script) { JavaScript.getCurrent().execute(script); }
/** * <p> * Executes the given JavaScript code to manipulate the chart. * Use the JavaScript variable <code>chart</code> to access the chart. * </p> * <p>Example:</p> * <pre> chart.manipulateChart("chart.addSeries({name: 'new', data: [1, 2]});");</pre> * * @param js JavaScript code to be executed */ public void manipulateChart(String js) { JavaScript.eval( "var chart = $('#" + getDomId() + "').highcharts();\n" + js ); }
private static void addCallback(String jsCallbackName, JavaScriptFunction jsCallback) { JavaScript.getCurrent().addFunction(jsCallbackName, jsCallback); }