Java 类com.vaadin.ui.JavaScriptFunction 实例源码

项目:VaadinUtils    文件:JSCallWithReturnValue.java   
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));

}
项目:live-image-editor    文件:LiveImageEditor.java   
/**
 * Constructs a new editor that will send the edited image to the specified {@link ImageReceiver} after the
 * {@link #requestEditedImage()} method is called.
 *
 * @param imageReceiver The {@link ImageReceiver} used to return the edited image. The
 *                      {@link ImageReceiver#receiveImage(InputStream)} will be called after it is requested via the
 *                      {@link #requestEditedImage()} method.
 */
public LiveImageEditor(ImageReceiver imageReceiver) {
    this.imageReceiver = imageReceiver;
    setWidth(100, Unit.PERCENTAGE);

    addFunction("updateServerState", new JavaScriptFunction() {
        @Override
        public void call(JsonArray arguments) {
            try {
                updateServerState(arguments);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}
项目:vaadin-medium-editor    文件:MediumEditor.java   
@SuppressWarnings("serial")
private void init() {
    setSizeFull();
    // this function can be called in medium-editor-connector e.g. self.onValueChange(stringValue)
    addFunction("onValueChange", new JavaScriptFunction() {
        @Override
        public void call(JsonArray args) {
            String value = args.getString(0);
            if (value != null && (value.isEmpty() || value.equals("<p><br></p>"))) {
                value = null;
            }
            for (BlurListener l : blurListeners) {
                l.valueChange(value);
            }
        }
    });
}
项目:metasfresh-procurement-webui    文件:SwipeHelper.java   
@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);
        }
    });
}
项目:hybridbpm    文件:CookieManager.java   
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
    ));

}
项目:vaadin-medium-editor    文件:MediumEditor.java   
@SuppressWarnings("serial")
private void init() {
    setSizeFull();
    // this function can be called in medium-editor-connector e.g. self.onValueChange(stringValue)
    addFunction("onValueChange", new JavaScriptFunction() {
        @Override
        public void call(JsonArray args) {
            String value = args.getString(0);
            if (value != null && (value.isEmpty() || value.equals("<p><br></p>"))) {
                value = null;
            }
            for (BlurListener l : blurListeners) {
                l.valueChange(value);
            }
        }
    });
}
项目:vaadin-jsclipboard-addon    文件:ClipboardButton.java   
private void setUpClipboardCommon() {
    setClipboardButtonClass();
    addFunction("notifyStatus", new JavaScriptFunction() {

        private static final long serialVersionUID = 3082847352373465144L;

        @Override
        public void call(JsonArray arguments) {
            boolean status = arguments.getBoolean(0);
            if (status) {
                for (SuccessListener successListener : successListeners) {
                    successListener.onSuccess();
                }
            } else {
                for (ErrorListener errorListener : errorListeners) {
                    errorListener.onError();
                }
            }
        }
    });
}
项目:vaadin-jsclipboard-addon    文件:JSClipboard.java   
public JSClipboard() {
    setClipboardButtonClass();
    addFunction("notifyStatus", new JavaScriptFunction() {
        @Override
        public void call(JsonArray arguments) {
            boolean status = arguments.getBoolean(0);
            if (status) {
                for (SuccessListener successListener : successListeners) {
                    successListener.onSuccess();
                }
            } else {
                for (ErrorListener errorListener : errorListeners) {
                    errorListener.onError();
                }
            }
        }
    });
}
项目:viritin    文件:BrowserCookie.java   
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
    ));

}
项目:textfieldformatter    文件:CreditCardFieldFormatter.java   
public void addCreditCardChangedListener(CreditCardChangedListener listener) {
    if (listeners.isEmpty()) {
        addFunction("onCreditCardChanged", new JavaScriptFunction() {
            @Override
            public void call(JsonArray arguments) {
                final CreditCardType cardType = (arguments != null && arguments.length() > 0
                        && arguments.getString(0).length() > 0) ? CreditCardType.valueOf(arguments.getString(0).toUpperCase())
                                : CreditCardType.UNKNOWN;
                listeners.forEach(l -> l
                        .creditCardChanged(new CreditCardChangedEvent(CreditCardFieldFormatter.this, cardType)));
            }
        });
    }
    listeners.add(listener);
}
项目:vaadin-chartjs    文件:ChartJs.java   
private void addJsFunctions() {
        // this function can be called in chartjs-connector e.g. self.onDataPointClick(datasetIndex, dataIndex)
        addFunction("onDataPointClick", new JavaScriptFunction() {
            private static final long serialVersionUID = -6280339244713509848L;

            @Override
            public void call(JsonArray arguments) {
                int datasetIndex = (int) arguments.getNumber(0);
                int dataIndex = (int) arguments.getNumber(1);
                for (DataPointClickListener l : dataPointClickListeners) {
                    l.onDataPointClick(datasetIndex, dataIndex);
                }
            }
        });

//        addFunction("sendImageDataUrl",  new JavaScriptFunction() {
//            private static final long serialVersionUID = -6280339244713509848L;
//
//            @Override
//            public void call(JsonArray arguments) {
//                String dataUrl = arguments.getString(0);
//                String encodingPrefix = "base64,";
//                int contentStartIndex = dataUrl.indexOf(encodingPrefix) + encodingPrefix.length();
//                byte[] imageData = Base64.getDecoder().decode(dataUrl.substring(contentStartIndex));
//                for (DownloadListener l : downloadListeners) {
//                    l.onDownload(imageData);
//                }
//            }
//        });
    }
项目:vaangular    文件:NgTemplateTest.java   
@Test
public void testAddService() {
    final Set<String> addedServices = new HashSet<>();
    NgTemplate template = new NgTemplate("--", "NgTemplateTest") {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        protected void addFunction(String functionName,
                JavaScriptFunction function) {
            addedServices.add(functionName);
        }
    };
    template.addService("testService", new Object() {

        @ServiceMethod
        public void test1() {
        }

        @ServiceMethod
        public void test2() {
        }

        @SuppressWarnings("unused")
        public void test3() {
        }

        @SuppressWarnings("unused")
        private void test4() {
        }
    });
    assertEquals(2, addedServices.size());
    assertTrue(addedServices.contains("testService_test1"));
    assertTrue(addedServices.contains("testService_test2"));
    assertFalse(addedServices.contains("testService_test3"));
    assertFalse(addedServices.contains("testService_test4"));
}
项目:vaangular    文件:NgTemplatePlusTest.java   
@Test
public void testAddService() {
    final Set<String> addedServices = new HashSet<>();
    NgTemplatePlus template = new NgTemplatePlus("--", "NgTemplateTest") {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        protected void addFunction(String functionName,
                JavaScriptFunction function) {
            addedServices.add(functionName);
        }
    };
    template.addService("testService", new Object() {

        @ServiceMethod
        public void test1() {
        }

        @ServiceMethod
        public void test2() {
        }

        @SuppressWarnings("unused")
        public void test3() {
        }

        @SuppressWarnings("unused")
        private void test4() {
        }
    });
    assertEquals(2, addedServices.size());
    assertTrue(addedServices.contains("testService_test1"));
    assertTrue(addedServices.contains("testService_test2"));
    assertFalse(addedServices.contains("testService_test3"));
    assertFalse(addedServices.contains("testService_test4"));
}
项目:serverside-elements    文件:ElementImpl.java   
JavaScriptFunction getCallback(int cid) {
    return callbacks.get(Integer.valueOf(cid));
}
项目:serverside-elements    文件:ElementImpl.java   
@Override
public void addEventListener(String eventName, JavaScriptFunction listener,
        String... arguments) {
    String argumentBuilder = String.join(",", arguments);
    eval("e.addEventListener('" + eventName + "', function (event) { $0("
            + argumentBuilder + ") })", listener);
}
项目:serverside-elements    文件:ElementImpl.java   
@Override
public void addEventListener(EventListener listener) {
    List<Method> listenerMethods = findInterfaceMethods(
            listener.getClass());

    for (Method method : listenerMethods) {
        if (method.getDeclaringClass() == Object.class) {
            // Ignore
            continue;
        }

        String name = method.getName();
        if (!name.startsWith("on")) {
            throw new RuntimeException(method.toString());
        }

        name = name.substring(2).toLowerCase();

        if (method.getParameterCount() != 1) {
            throw new RuntimeException();
        }

        if (method.getReturnType() != void.class) {
            throw new RuntimeException();
        }

        Map<String, Integer> methodOrder = new HashMap<>();
        Class<?> eventType = method.getParameterTypes()[0];

        Method[] eventGetters = eventType.getDeclaredMethods();
        String[] argumentBuilders = new String[eventGetters.length];

        for (int i = 0; i < eventGetters.length; i++) {
            Method getter = eventGetters[i];
            if (getter.getParameterCount() != 0) {
                throw new RuntimeException(getter.toString());
            }

            String paramName = ElementReflectHelper
                    .getPropertyName(getter.getName());

            methodOrder.put(getter.getName(), Integer.valueOf(i));
            argumentBuilders[i] = "event." + paramName;
        }

        addEventListener(name, new JavaScriptFunction() {
            @Override
            public void call(final JsonArray arguments) {
                InvocationHandler invocationHandler = (proxy, calledMethod,
                        args) -> {
                    if (calledMethod.getDeclaringClass() == Object.class) {
                        // Standard object methods
                        return calledMethod.invoke(proxy, args);
                    } else {
                        String methodName = calledMethod.getName();
                        int indexOf = methodOrder.get(methodName)
                                .intValue();
                        return JsonCodec.decodeInternalOrCustomType(
                                calledMethod.getGenericReturnType(),
                                arguments.get(indexOf), null);
                    }
                };

                Object event = Proxy.newProxyInstance(
                        eventType.getClassLoader(),
                        new Class[] { eventType }, invocationHandler);

                try {
                    method.invoke(listener, event);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }, argumentBuilders);
    }
}
项目:serverside-elements    文件:RootImpl.java   
void eval(ElementImpl element, String script, Object[] arguments) {
    // Param values
    JsonArray params = Json.createArray();

    // Array of param indices that should be treated as callbacks
    JsonArray callbacks = Json.createArray();

    for (int i = 0; i < arguments.length; i++) {
        Object value = arguments[i];
        Class<? extends Object> type = value.getClass();

        if (JavaScriptFunction.class.isAssignableFrom(type)) {
            // TODO keep sequence per element instead of "global"
            int cid = callbackIdSequence++;
            element.setCallback(cid, (JavaScriptFunction) value);

            value = Integer.valueOf(cid);
            type = Integer.class;

            callbacks.set(callbacks.length(), i);
        }

        EncodeResult encodeResult = JsonCodec.encode(value, null, type,
                null);
        params.set(i, encodeResult.getEncodedValue());
    }

    addCommand("eval", element, Json.create(script), params, callbacks);
}
项目:serverside-elements    文件:RootImpl.java   
public void handleCallback(JsonArray arguments) {
    JsonArray attributeChanges = arguments.getArray(1);
    for (int i = 0; i < attributeChanges.length(); i++) {
        JsonArray attributeChange = attributeChanges.getArray(i);
        int id = (int) attributeChange.getNumber(0);
        String attribute = attributeChange.getString(1);
        JsonValue value = attributeChange.get(2);

        NodeImpl target = idToNode.get(Integer.valueOf(id));
        if (value.getType() == JsonType.NULL) {
            target.node.removeAttr(attribute);
        } else {
            target.node.attr(attribute, value.asString());
        }
    }

    JsonArray callbacks = arguments.getArray(0);
    for (int i = 0; i < callbacks.length(); i++) {
        JsonArray call = callbacks.getArray(i);

        int elementId = (int) call.getNumber(0);
        int cid = (int) call.getNumber(1);
        JsonArray params = call.getArray(2);

        ElementImpl element = (ElementImpl) idToNode
                .get(Integer.valueOf(elementId));
        if (element == null) {
            System.out.println(cid + " detached?");
            return;
        }

        JavaScriptFunction callback = element.getCallback(cid);
        callback.call(params);
    }
}
项目:highcharts-vaadin7    文件:HighChartDemoUI.java   
@Override
protected void init(VaadinRequest request) {
    final AceEditor chartCodeField = new AceEditor() {{
        setCaption("Chart Code");
        setSizeFull();
        setMode(AceMode.javascript);
        setValue(INITIAL_HCJS);
    }};

    final HighChart chart = new HighChart() {{
        setSizeFull();
        setHcjs(chartCodeField.getValue());

        addFunction("onClick", (JavaScriptFunction) args -> {
            Notification.show("Chart clicked: (" + args.getNumber(0) + ", " + args.getNumber(1) + ")", Notification.Type.TRAY_NOTIFICATION);

            manipulateChart(
                    "chart.addSeries({\n" +
                    "    name: 'pos',\n" +
                    "    data: [{x: " + args.getNumber(0) + ", y: " + args.getNumber(1) + "}]\n" +
                    "});"
            );
        });
    }};

    chartCodeField.addValueChangeListener(e -> chart.setHcjs(e.getValue()));

    HorizontalLayout horizontalLayout = new HorizontalLayout() {{
        setSizeFull();
        setMargin(true);
        setSpacing(true);
        addComponent(chartCodeField);
        setExpandRatio(chartCodeField, 1);
        addComponent(chart);
        setExpandRatio(chart, 1);
    }};

    setContent(horizontalLayout);
}
项目:Vaadin-SignatureField    文件:SignatureFieldExtension.java   
public SignatureFieldExtension(SignatureField target) {
    // extend the target
    super(target);

    /*
     * Gets called from the client-side when it wants to change the signatue
     * value at the server-side.
     */
    addFunction("fireSignatureChange", new JavaScriptFunction() {

        @Override
        public void call(JsonArray arguments) {
            String signature;
            JsonValue jsonValue = arguments.get(0);
            if (jsonValue instanceof JsonString) {
                signature = jsonValue.asString();
            } else {
                signature = null;
            }
            setSignature(signature, true);
            fireSignatureChangeEvent(signature);
        }
    });
}
项目:VaadinUtils    文件:JSCallWithReturnValue.java   
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);

            }

        }
    });

}
项目:PersonaForVaadin    文件:Persona.java   
public Persona(UI ui, String audience) {
    this.audience = audience;

    callFunction("watch");

    registerRpc(new PersonaRpc() {
        @Override
        public void onlogout() {
            fireLogoutEvent();
        }

        @Override
        public void onlogin(String assertion) {
            checkAssertion(assertion);
        }

        @Override
        public void oncancel() {
            fireCancelEvent();
        }
    });

    addFunction("error", new JavaScriptFunction() {
        @Override
        public void call(JSONArray arguments) throws JSONException {
            String message = null;
            if (arguments.length() > 0) {
                message = arguments.getString(0).toString();
            }
            fireError(new PersonaErrorEvent(Persona.this, message));
        }
    });

    extend(ui);
}
项目:Persephone    文件:LogsPage.java   
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);
}
项目:serverside-elements    文件:Element.java   
public void addEventListener(String eventName, JavaScriptFunction listener,
String... arguments);
项目:serverside-elements    文件:ElementImpl.java   
void setCallback(int cid, JavaScriptFunction callback) {
    callbacks.put(Integer.valueOf(cid), callback);
}
项目:VaadinUtils    文件:JSCallWithReturnValue.java   
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);

}
项目:usergrid    文件:JavaScriptUtil.java   
public static void loadChart(String chart, String jsCallbackName, JavaScriptFunction jsCallback) {
    execute(chart);
    addCallback(jsCallbackName, jsCallback);
}
项目:usergrid    文件:JavaScriptUtil.java   
private static void addCallback(String jsCallbackName, JavaScriptFunction jsCallback) {
    JavaScript.getCurrent().addFunction(jsCallbackName, jsCallback);
}